hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
194298e54aeac10a8493562905e9426592ffb067
2,158
cpp
C++
Days 091 - 100/Day 099/LongestSequence.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 091 - 100/Day 099/LongestSequence.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 091 - 100/Day 099/LongestSequence.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstddef> #include <functional> #include <iostream> #include <iterator> #include <unordered_map> #include <vector> struct Range { int start; int end; Range() noexcept = default; Range(int start, int end) noexcept : start(start), end(end) { } }; template <> struct std::hash<Range> { inline std::size_t operator ()(const Range& range) const noexcept { return std::hash<int>()(range.start) + std::hash<int>()(range.end); } }; void AddNumberToRanges(int number, std::unordered_map<int, Range>& rangeStarts, std::unordered_map<int, Range>& rangeEnds) noexcept { if (rangeStarts.find(number + 1) != std::cend(rangeStarts) && rangeEnds.find(number - 1) != std::cend(rangeEnds)) { Range newStart = rangeEnds[number - 1]; Range newEnd = rangeStarts[number + 1]; Range newRange(newStart.start, newStart.end); rangeStarts[newRange.start] = newRange; rangeEnds[newRange.end] = newRange; rangeStarts.erase(newEnd.start); rangeEnds.erase(newStart.end); return; } else if (rangeStarts.find(number + 1) != std::cend(rangeStarts)) { Range newRange = rangeStarts[number + 1]; newRange.start = number; rangeStarts[number] = newRange; rangeEnds.erase(number + 1); return; } else if (rangeEnds.find(number - 1) != std::cend(rangeEnds)) { Range newRange = rangeEnds[number - 1]; newRange.end = number; rangeEnds[number] = newRange; rangeEnds.erase(number - 1); return; } Range newRange(number, number); rangeStarts[number] = newRange; rangeEnds[number] = newRange; } unsigned int GetLongestSequenceLength(const std::vector<int>& numbers) noexcept { std::unordered_map<int, Range> rangeStarts; std::unordered_map<int, Range> rangeEnds; for (const int number : numbers) { AddNumberToRanges(number, rangeStarts, rangeEnds); } unsigned int maxLength = 0; for (const auto&[number, range] : rangeStarts) { unsigned int length = range.end - range.start + 1; maxLength = std::max(length, maxLength); } return maxLength; } int main(int argc, char* argv[]) { std::cout << GetLongestSequenceLength({ 100, 4, 200, 1, 3, 2 }) << "\n"; std::cin.get(); return 0; }
21.58
131
0.691844
LucidSigma
19434a0c00bc20f96bd4b74cf9856481faa1c72f
1,219
cpp
C++
PAT (Advanced Level) Practice/1153 Decode Registration Card of PAT (25).cpp
vuzway/PAT
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
5
2020-02-10T08:26:19.000Z
2020-07-09T00:11:16.000Z
PAT (Advanced Level) Practice/1153 Decode Registration Card of PAT (25).cpp
Assassin2016/zju_data_structures_and_algorithms_in_MOOC
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
null
null
null
PAT (Advanced Level) Practice/1153 Decode Registration Card of PAT (25).cpp
Assassin2016/zju_data_structures_and_algorithms_in_MOOC
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; struct node { string id; int g; }; bool cmp(const node &a, const node &b) { return a.g != b.g ? a.g > b.g : a.id < b.id; } int main() { int n, k, num; string s; cin >> n >> k; vector<node> v(n); for (int i = 0; i < n; i++) cin >> v[i].id >> v[i].g; for (int i = 1; i <= k; i++) { cin >> num >> s; printf("Case %d: %d %s\n", i, num, s.c_str()); vector<node> ans; int cnt = 0, sum = 0; if (num == 1) { for (int j = 0; j < n; j++) if (v[j].id[0] == s[0]) ans.push_back(v[j]); } else if (num == 2) { for (int j = 0; j < n; j++) if (v[j].id.substr(1, 3) == s) { cnt++; sum += v[j].g; } if (cnt != 0) printf("%d %d\n", cnt, sum); } else { unordered_map<string, int> m; for (int j = 0; j < n; j++) if (v[j].id.substr(4, 6) == s) m[v[j].id.substr(1, 3)]++; for (auto it : m) ans.push_back({it.first, it.second}); } sort(ans.begin(), ans.end(), cmp); for (int j = 0; j < ans.size(); j++) printf("%s %d\n", ans[j].id.c_str(), ans[j].g); if (((num == 1 || num == 3) && ans.size() == 0) || (num == 2 && cnt == 0)) printf("NA\n"); } return 0; }
25.395833
92
0.484003
vuzway
194a13063d656e908e4d4ddc449b5e9d4a57ae90
1,413
cpp
C++
events/create_plane_trigger_event.cpp
canuc/meow-engine
25f5396136d90691e4a4451f382a45da9fdcebc0
[ "BSD-3-Clause" ]
1
2020-01-24T01:14:04.000Z
2020-01-24T01:14:04.000Z
events/create_plane_trigger_event.cpp
canuc/meow-engine
25f5396136d90691e4a4451f382a45da9fdcebc0
[ "BSD-3-Clause" ]
null
null
null
events/create_plane_trigger_event.cpp
canuc/meow-engine
25f5396136d90691e4a4451f382a45da9fdcebc0
[ "BSD-3-Clause" ]
1
2020-06-05T07:00:16.000Z
2020-06-05T07:00:16.000Z
// // Created by julian on 3/30/16. // #include "events/create_plane_trigger_event.h" CreatePlaneTriggerEvent::CreatePlaneTriggerEvent(WorkQueue<LuaEvent> * promiseQueue): LuaPromiseEvent(promiseQueue, CREATE_PLANE_TRIGGER_EVENT_ID, CREATE_PLANE_TRIGGER_EVENT) { }; void CreatePlaneTriggerEvent::readEventData(lua_State* L) { assert(L && lua_type(L,-1) == LUA_TTABLE ); lua_pushnil(L); while(lua_next(L, -2) != 0) { const char *eventType = lua_tostring(L, -2); if (strncmp(eventType, NORMAL_POSITION_KEY, strlen(NORMAL_POSITION_KEY)) == 0 && lua_istable(L, -1)) { normal = lua_getvec3(L); } else if (strncmp(eventType, PLANE_D_KEY, strlen(PLANE_D_KEY)) == 0 && lua_isnumber(L,-1)) { d = lua_tointeger(L,-1); } else if (strncmp(eventType, CALLBACK_FUNCTION, strlen(CALLBACK_FUNCTION)) == 0 && lua_isfunction(L,-1)) { stackDump(L); int ref = luaL_ref(L, LUA_REGISTRYINDEX); callback = LuaFunc(ref, LUA_FUNC_NO_SCOPE, true); lua_rawgeti(L, LUA_REGISTRYINDEX, ref); stackDump(L); } lua_pop(L, 1); stackDump(L); } } const LuaFunc & CreatePlaneTriggerEvent::getCallback() const { return callback; } float CreatePlaneTriggerEvent::getPlaneD() const { return d; } glm::vec3 CreatePlaneTriggerEvent::getNormal() const { return normal; }
32.860465
115
0.652512
canuc
1950fbf9d2383d5c34cbf772b124bde57828d968
1,220
hpp
C++
src/Shaders/ConeTraceShader.hpp
jaafersheriff/Clouds
00de0a33f6e6fe43c3287de5cba9228c70693110
[ "MIT" ]
6
2019-06-30T20:20:52.000Z
2022-01-07T06:31:18.000Z
src/Shaders/ConeTraceShader.hpp
jaafersheriff/Clouds
00de0a33f6e6fe43c3287de5cba9228c70693110
[ "MIT" ]
null
null
null
src/Shaders/ConeTraceShader.hpp
jaafersheriff/Clouds
00de0a33f6e6fe43c3287de5cba9228c70693110
[ "MIT" ]
3
2020-10-08T16:37:07.000Z
2022-01-07T06:31:22.000Z
#pragma once #ifndef _CONE_TRACE_SHADER_HPP_ #define _CONE_TRACE_SHADER_HPP_ #include "Shader.hpp" #include "CloudVolume.hpp" class ConeTraceShader : public Shader { public: ConeTraceShader(const std::string &r, const std::string &v, const std::string &f); void coneTrace(CloudVolume *); /* Noise map parameters */ float stepSize = 0.01f; float noiseOpacity = 4.0; int numOctaves = 4; float freqStep = 3.f; float persStep = 0.5f; float adjustSize = 40.f; int minNoiseSteps = 2; int maxNoiseSteps = 8; float minNoiseColor = 0.2f; float noiseColorScale = 0.45f; glm::vec3 windVel = glm::vec3(0.01f, 0, 0); /* Cone trace parameters */ int vctSteps = 16; float vctConeAngle = 0.9f; float vctConeInitialHeight = 0.1f; float vctLodOffset = 0.f; float vctDownScaling = 1.f; bool showQuad = false; bool doConeTrace = true; bool doNoiseSample = true; private: void bindVolume(CloudVolume *); void unbindVolume(); void initNoiseMap(int); GLuint noiseMapId; float totalTime = 0.f; }; #endif
25.957447
90
0.59918
jaafersheriff
19553e616a65ab492fc3c4ba8bf086b8022d5a24
813
cpp
C++
Deitel/Chapter16/examples/16.07/Integer.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter16/examples/16.07/Integer.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter16/examples/16.07/Integer.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 "Integer.hpp" #include <iostream> Integer::Integer(int i) : value(i) { std::cout << "Constructor for Integer " << value << std::endl; } Integer::~Integer() { std::cout << "Destructor for Integer " << value << std::endl; } // set Integer value void Integer::setInteger(int i) { value = i; } // get Integer value int Integer::getInteger() const { return value; }
25.40625
88
0.450185
SebastianTirado
19581a6d361ff29a81886a9f963298482577d540
8,960
cpp
C++
misc/vtk/src/processors/vtkunstructuredgridtorectilineargrid.cpp
JochenJankowai/modules
20c5c2df6af4fe5faaa87a9a61432406a6d750e0
[ "BSD-2-Clause" ]
null
null
null
misc/vtk/src/processors/vtkunstructuredgridtorectilineargrid.cpp
JochenJankowai/modules
20c5c2df6af4fe5faaa87a9a61432406a6d750e0
[ "BSD-2-Clause" ]
null
null
null
misc/vtk/src/processors/vtkunstructuredgridtorectilineargrid.cpp
JochenJankowai/modules
20c5c2df6af4fe5faaa87a9a61432406a6d750e0
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/vtk/processors/vtkunstructuredgridtorectilineargrid.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/clock.h> #include <inviwo/vtk/util/vtkutil.h> #include <warn/push> #include <warn/ignore/all> #include <vtkDataArray.h> #include <vtkDataSet.h> #include <vtkDoubleArray.h> #include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkUnstructuredGrid.h> #include <vtkProbeFilter.h> #include <vtkCallbackCommand.h> #include <vtkCellTreeLocator.h> #include <vtkRectilinearGrid.h> #include <warn/pop> namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo VTKUnstructuredGridToRectilinearGrid::processorInfo_{ "org.inviwo.VTKUnstructuredGridToRectilinearGrid", // Class identifier "VTK Unstructured Grid To Rectilinear Grid", // Display name "VTK", // Category CodeState::Experimental, // Code state Tags::CPU, // Tags }; const ProcessorInfo VTKUnstructuredGridToRectilinearGrid::getProcessorInfo() const { return processorInfo_; } VTKUnstructuredGridToRectilinearGrid::VTKUnstructuredGridToRectilinearGrid() : Processor() , ActivityIndicatorOwner() , maxDimension_("maxDimension", "Max output dimension", 32, 2, 2048) , button_("button", "Convert Data") , abortButton_("abortButton", "Abort Conversion", InvalidationLevel::Valid) , inport_("inport") , outport_("outport") , state_(std::make_shared<WorkerState>()) { addProperty(maxDimension_); addProperty(button_); addProperty(abortButton_); button_.onChange([this]() { if (state_->state != State::Working) { loadData(); } }); abortButton_.onChange([this]() { if (state_->state == State::Working) { state_->abortConversion_ = true; } }); progressBar_.hide(); addPort(inport_); addPort(outport_); } VTKUnstructuredGridToRectilinearGrid::~VTKUnstructuredGridToRectilinearGrid() { state_->processorExists_ = false; state_->abortConversion_ = true; } void VTKUnstructuredGridToRectilinearGrid::process() {} void VTKUnstructuredGridToRectilinearGrid::loadData() { state_->abortConversion_ = false; const auto done = [this, state = state_]() { if (state->processorExists_) { dispatchFront([this]() { progressBar_.hide(); getActivityIndicator().setActive(false); }); } }; const auto abort = [state = state_, done]() { state->state = State::Abort; LogWarnCustom("VTK conversion", "Conversion aborted."); done(); }; auto grid = **inport_.getData(); if (grid->GetDataObjectType() != VTK_UNSTRUCTURED_GRID) { LogError("Input is not an unstructured grid but a " + std::string{grid->GetClassName()} + ". Aborting."); return; } auto unstructuredGrid = vtkUnstructuredGrid::SafeDownCast(grid); auto bounds = unstructuredGrid->GetBounds(); const auto xRange = std::abs(bounds[0] - bounds[1]); const auto yRange = std::abs(bounds[2] - bounds[3]); const auto zRange = std::abs(bounds[4] - bounds[5]); const auto largestRange = std::max(xRange, std::max(yRange, zRange)); const auto maxDim = maxDimension_.get(); const int xDim = static_cast<int>((xRange / largestRange) * maxDim); const int yDim = static_cast<int>((yRange / largestRange) * maxDim); const int zDim = static_cast<int>((zRange / largestRange) * maxDim); state_->dims_ = {xDim, yDim, zDim}; auto dispatch = [this, done, abort, unstructuredGrid, activityIndicator = &getActivityIndicator(), state = state_]() mutable -> void { auto updateActivity = [activityIndicator, state](bool active) { if (state->processorExists_) { dispatchFront([active](ActivityIndicator* i) { i->setActive(active); }, activityIndicator); } }; updateActivity(true); this->state_->state = State::Working; if (this->state_->abortConversion_) { abort(); return; } const auto bounds = unstructuredGrid->GetBounds(); const auto gridSize = this->state_->dims_; const auto gridBounds = dvec3(gridSize - ivec3(1)); vtkSmartPointer<vtkCallbackCommand> progressCallback = vtkSmartPointer<vtkCallbackCommand>::New(); progressCallback->SetCallback(vtkProgressBarCallback); progressCallback->SetClientData(&progressBar_); auto pointSet = vtkSmartPointer<vtkRectilinearGrid>::New(); pointSet->SetDimensions(glm::value_ptr(gridSize)); auto xCoordinates = vtkSmartPointer<vtkDoubleArray>::New(); auto yCoordinates = vtkSmartPointer<vtkDoubleArray>::New(); auto zCoordinates = vtkSmartPointer<vtkDoubleArray>::New(); const auto xRange = std::abs(bounds[0] - bounds[1]); const auto yRange = std::abs(bounds[2] - bounds[3]); const auto zRange = std::abs(bounds[4] - bounds[5]); const auto stepSize = dvec3(xRange / gridBounds.x, yRange / gridBounds.y, zRange / gridBounds.z); for (int z = 0; z < gridSize.z; z++) { const auto zCoord = bounds[4] + static_cast<double>(z) * stepSize.z; zCoordinates->InsertNextValue(zCoord); } for (int y = 0; y < gridSize.y; y++) { const auto yCoord = bounds[2] + static_cast<double>(y) * stepSize.y; yCoordinates->InsertNextValue(yCoord); } for (int x = 0; x < gridSize.x; x++) { const auto xCoord = bounds[0] + static_cast<double>(x) * stepSize.x; xCoordinates->InsertNextValue(xCoord); } pointSet->SetXCoordinates(xCoordinates); pointSet->SetYCoordinates(yCoordinates); pointSet->SetZCoordinates(zCoordinates); if (this->state_->abortConversion_) { abort(); return; } vtkSmartPointer<vtkCellTreeLocator> cellLocator = vtkSmartPointer<vtkCellTreeLocator>::New(); cellLocator->SetDataSet(pointSet); cellLocator->BuildLocator(); if (this->state_->abortConversion_) { abort(); return; } auto probeFilter = vtkSmartPointer<vtkProbeFilter>::New(); probeFilter->SetSourceData(unstructuredGrid); probeFilter->SetCellLocatorPrototype(cellLocator); probeFilter->SetInputData(pointSet); probeFilter->AddObserver(vtkCommand::ProgressEvent, progressCallback); probeFilter->Update(); if (this->state_->abortConversion_) { abort(); return; } dataSet_ = probeFilter->GetRectilinearGridOutput(); done(); updateActivity(false); this->state_->state = State::Done; dispatchFront([this]() { data_ = std::make_shared<VTKDataSet>(dataSet_); outport_.setData(data_); }); }; state_->state = State::NotStarted; dispatchPool(dispatch); } } // namespace inviwo
36.129032
97
0.636942
JochenJankowai
195a82fd13fa2b303499d647185f7b5d9a854399
9,902
hpp
C++
third-party/Empirical/include/emp/tools/TypeTracker.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/include/emp/tools/TypeTracker.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/include/emp/tools/TypeTracker.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
/** * @note This file is part of Empirical, https://github.com/devosoft/Empirical * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2016-2018 * * @file TypeTracker.hpp * @brief Track class types abstractly to dynamically call correct function overloads. * @note Status: BETA * * TypeTracker is a templated class that must be declared with all of the types that can * possibly be tracked. For example: * * emp::TypeTracker<int, std::string, double> tt; * * ...would create a TypeTracker that can manage the three types listed and convert back. * * @todo Should use std::is_convertible<X,Y>::value to determine if casting on base type is allowed. * @todo Functions should be able to have fixed type values mixed in. */ #ifndef EMP_TYPE_TRACKER_H #define EMP_TYPE_TRACKER_H #include <unordered_map> #include "../base/array.hpp" #include "../base/assert.hpp" #include "../meta/meta.hpp" #include "../base/Ptr.hpp" #include "../datastructs/map_utils.hpp" #include "../functional/GenericFunction.hpp" #include "../math/math.hpp" namespace emp { /// The proxy base class of any type to be tracked. struct TrackedInfo_Base { virtual size_t GetTypeID() const noexcept = 0; virtual ~TrackedInfo_Base () {;} virtual emp::Ptr<TrackedInfo_Base> Clone() const = 0; }; /// The actual TrackedVar object that manages a Ptr to the value. struct TrackedVar { emp::Ptr<TrackedInfo_Base> ptr; // Note: This is the primary constructor for new TrackedVar and non-null values should be // built only in TypeTracker; since that is a template, it can't be a friend. TrackedVar(emp::Ptr<TrackedInfo_Base> _ptr) : ptr(_ptr) { ; } /// Copy constructor; use judiciously since it copies the contents! TrackedVar(const TrackedVar & _in) : ptr(nullptr) { if (_in.ptr) ptr = _in.ptr->Clone(); } /// Move constructor takes control of the pointer. TrackedVar(TrackedVar && _in) : ptr(_in.ptr) { _in.ptr = nullptr; } /// Cleanup ptr on destruct. ~TrackedVar() { if (ptr) ptr.Delete(); } /// Move assignment hands over control of the pointer. TrackedVar & operator=(const TrackedVar & _in) { if (ptr) ptr.Delete(); ptr = _in.ptr->Clone(); return *this; } /// Move assignment hands over control of the pointer. TrackedVar & operator=(TrackedVar && _in) { if (ptr) ptr.Delete(); ptr = _in.ptr; _in.ptr = nullptr; return *this; } size_t GetTypeID() const noexcept { return ptr->GetTypeID(); } }; /// TrackedInfo_Value store both the real type and an ID for it (to be identified from /// the base class for each conversion back.) template <typename REAL_T, size_t ID> struct TrackedInfo_Value : public TrackedInfo_Base { using real_t = REAL_T; using this_t = TrackedInfo_Value<REAL_T,ID>; REAL_T value; TrackedInfo_Value(const REAL_T & in) : value(in) { ; } TrackedInfo_Value(REAL_T && in) : value(std::forward<REAL_T>(in)) { ; } TrackedInfo_Value(const TrackedInfo_Value &) = default; TrackedInfo_Value(TrackedInfo_Value &&) = default; TrackedInfo_Value & operator=(const TrackedInfo_Value &) = default; TrackedInfo_Value & operator=(TrackedInfo_Value &&) = default; size_t GetTypeID() const noexcept override { return ID; } /// Build a copy of this TrackedInfo_Value; recipient is in charge of deletion. emp::Ptr<TrackedInfo_Base> Clone() const override { return emp::NewPtr<this_t>(value); } }; /// Dynamic functions that are indexed by parameter types; calls lookup the correct function /// to forward arguments into. template <typename... TYPES> class TypeTracker { protected: /// fun_map is a hash table that maps a set of inputs to the appropriate function. std::unordered_map<size_t, Ptr<emp::GenericFunction>> fun_map; public: // Constructors! TypeTracker() = default; TypeTracker(const TypeTracker &) = default; TypeTracker(TypeTracker &&) = default; TypeTracker & operator=(const TypeTracker &) = default; TypeTracker & operator=(TypeTracker &&) = default; // Destructor! ~TypeTracker() { for (auto x : fun_map) delete x.second; // Clear out Functions. } using this_t = TypeTracker<TYPES...>; template <typename REAL_T> using wrap_t = TrackedInfo_Value< REAL_T, get_type_index<REAL_T,TYPES...>() >; /// How many types are we working with? constexpr static size_t GetNumTypes() { return sizeof...(TYPES); } /// How many combinations of V types are there? constexpr static size_t GetNumCombos(size_t vals=2) { size_t result = 1; for (size_t v = 0; v < vals; v++) result *= GetNumTypes(); return result; } /// How many combinations are the of the given number of types OR FEWER? constexpr static size_t GetCumCombos(size_t vals=2) { size_t cur_result = 1; size_t cum_result = 1; for (size_t v = 0; v < vals; v++) { cur_result *= GetNumTypes(); cum_result += cur_result; } return cum_result; } /// Each type should have a unique ID. template <typename T> constexpr static size_t GetID() { static_assert(get_type_index<T,TYPES...>() != -1, "Can only get IDs for pre-specified types."); return (size_t) get_type_index<T,TYPES...>(); } /// Each set of types should have an ID unique within that number of types. template <typename T1, typename T2, typename... Ts> constexpr static size_t GetID() { return GetID<T1>() + GetID<T2,Ts...>() * GetNumTypes(); } /// A ComboID should be unique *across* all size combinations. template <typename... Ts> constexpr static size_t GetComboID() { return GetCumCombos(sizeof...(Ts)-1) + GetID<Ts...>(); } /// A Tracked ID is simply the unique ID of the type being tracked. static size_t GetTrackedID(const TrackedVar & tt) { return tt.GetTypeID(); } /// Or set of types being tracked... template <typename... Ts> static size_t GetTrackedID(const TrackedVar & tt1, const TrackedVar & tt2, const Ts &... ARGS) { return tt1.GetTypeID() + GetTrackedID(tt2, ARGS...) * GetNumTypes(); } /// A tracked COMBO ID, is an ID for this combination of types, unique among all possible type /// combinations. Consistent with GetComboID with the same underlying types. template <typename... Ts> constexpr static size_t GetTrackedComboID(const Ts &... ARGS) { return GetCumCombos(sizeof...(Ts)-1) + GetTrackedID(ARGS...); } /// Convert an input value into a TrackedInfo_Value maintaining the value (universal version) template <typename REAL_T> static TrackedVar Convert(const REAL_T & val) { emp_assert((has_type<REAL_T,TYPES...>())); // Make sure we're wrapping a legal type. using decay_t = std::decay_t<REAL_T>; return TrackedVar( NewPtr<wrap_t<decay_t>>(val) ); } /// Test if the tracked type is TEST_T template <typename TEST_T> static bool IsType( TrackedVar & tt ) { return tt.GetTypeID() == get_type_index<TEST_T,TYPES...>(); } /// Convert the tracked type back to REAL_T. Assert that this is type safe! template <typename REAL_T> static REAL_T ToType( TrackedVar & tt ) { emp_assert(IsType<REAL_T>(tt)); return (tt.ptr.Cast<wrap_t<REAL_T>>() )->value; } /// Cast the tracked type to OUT_T. Try to do so even if NOT original type! template <typename OUT_T> static OUT_T Cast( TrackedVar & tt ) { return tt.ptr.Cast<wrap_t<OUT_T>>()->value; } /// var_decoy converts any variable into a TrackedVar (used to have correct number of vars) template <typename T> using var_decoy = TrackedVar; /// Add a new std::function that this TypeTracker should call if the appropriate types are /// passed in. template <typename... Ts> this_t & AddFunction( std::function<void(Ts...)> fun ) { constexpr size_t ID = GetComboID<Ts...>(); // We need to ensure there are the same number of TrackedVar parameters in the wrapped // function as there were typed parameters in the original. To accomplish this task, we // will expand the original type pack, but use decoys to convert to TrackedVar. auto fun_wrap = [fun](var_decoy<Ts> &... args) { // Ensure all types can be cast appropriately emp_assert( AllTrue( args.ptr. template DynamicCast<wrap_t<Ts>>()... ) ); // Now run the function with the correct type conversions fun( (args.ptr. template Cast<wrap_t<Ts>>())->value... ); }; fun_map[ID] = new Function<void(var_decoy<Ts> &...)>(fun_wrap); return *this; } /// Add a new function pointer that this TypeTracker should call if the appropriate types are /// passed in. template <typename... Ts> this_t & AddFunction( void (*fun)(Ts...) ) { return AddFunction( std::function<void(Ts...)>(fun) ); } /// Add a new lambda function that this TypeTracker should call if the appropriate types are /// passed in. template <typename LAMBDA_T> this_t & AddFunction( const LAMBDA_T & fun ) { return AddFunction( to_function(fun) ); } /// Run the appropriate function based on the argument types received. template <typename... Ts> void RunFunction( Ts &&... args ) { // args must all be TrackedVar pointers! const size_t pos = GetTrackedComboID(args...); if (Has(fun_map, pos)) { // If a redirect exists, use it! Ptr<GenericFunction> gfun = fun_map[pos]; gfun->Call<void, var_decoy<Ts> &...>(args...); } } /// Call TypeTracker as a function (refers call to RunFunction) template <typename... Ts> void operator()(Ts &&... args) { RunFunction(args...); } }; } #endif
37.507576
101
0.660675
koellingh
195a934f6a21088d3c3126ef013b810a5ed00544
1,369
cpp
C++
bark/world/evaluation/ltl/evaluator_right_overtake.cpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/evaluation/ltl/evaluator_right_overtake.cpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/evaluation/ltl/evaluator_right_overtake.cpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
// Copyright (c) 2020 fortiss GmbH // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "bark/world/evaluation/ltl/evaluator_right_overtake.hpp" #include "bark/world/evaluation/ltl/label_functions/behind_of_label_function.hpp" #include "bark/world/evaluation/ltl/label_functions/dense_traffic_label_function.hpp" #include "bark/world/evaluation/ltl/label_functions/front_of_label_function.hpp" #include "bark/world/evaluation/ltl/label_functions/right_of_label_function.hpp" namespace bark { namespace world { namespace evaluation { /// Do not overtake to the right, if traffic is not dense! const char EvaluatorRightOvertake::formula_[] = "G (!dense -> !(behind#0 & X[!](behind#0 U right#0 U front#0)))"; const LabelFunctions EvaluatorRightOvertake::labels_ = { LabelFunctionPtr(new DenseTrafficLabelFunction("dense", 20.0, 8)), LabelFunctionPtr(new RightOfLabelFunction("right")), LabelFunctionPtr(new FrontOfLabelFunction("front")), LabelFunctionPtr(new BehindOfLabelFunction("behind"))}; const char EvaluatorRightOvertakeAssumption::formula_[] = "G !dense"; const LabelFunctions EvaluatorRightOvertakeAssumption::labels_ = { LabelFunctionPtr(new DenseTrafficLabelFunction("dense", 20.0, 8))}; } // namespace evaluation } // namespace world } // namespace bark
39.114286
85
0.775749
GAIL-4-BARK
195ab728038284f416bbeb584d51a026ec676bd1
1,493
hpp
C++
RSDKv4/Ini.hpp
0xR00KIE/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
2
2022-01-15T05:05:39.000Z
2022-03-19T07:36:31.000Z
RSDKv4/Ini.hpp
LittlePlanetCD/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
null
null
null
RSDKv4/Ini.hpp
LittlePlanetCD/Decomp-for-S1F
c8ffedd211f25bb46803f9d637baf1b1fc635db0
[ "Unlicense" ]
null
null
null
#ifndef INI_H #define INI_H class IniParser { public: enum ItemType { INI_ITEM_STRING, INI_ITEM_INT, INI_ITEM_FLOAT, INI_ITEM_BOOL, INI_ITEM_COMMENT, }; struct ConfigItem { ConfigItem() { sprintf(section, "%s", ""); sprintf(key, "%s", ""); sprintf(value, "%s", ""); hasSection = false; type = INI_ITEM_STRING; } char section[0x20]; bool hasSection = false; char key[0x40]; char value[0x100]; byte type = INI_ITEM_STRING; }; IniParser() { memset(items, 0, 0x80 * sizeof(ConfigItem)); } IniParser(const char *filename, bool addPath = true); int GetString(const char *section, const char *key, char *dest); int GetInteger(const char *section, const char *key, int *dest); int GetFloat(const char *section, const char *key, float *dest); int GetBool(const char *section, const char *key, bool *dest); int SetString(const char *section, const char *key, char *value); int SetInteger(const char *section, const char *key, int value); int SetFloat(const char *section, const char *key, float value); int SetBool(const char *section, const char *key, bool value); int SetComment(const char *section, const char *key, const char *comment); void Write(const char *filename, bool addPath = true); ConfigItem items[0x80]; int count = 0; }; #endif // !INI_H
29.86
78
0.607502
0xR00KIE
195c6f8a5950f26994334bb2b5d77f53ea9ad523
1,015
cpp
C++
mmap_demo/main.cpp
xum07/small_demos
8e727cb7e005d7beb998419025cb1d47be9d0399
[ "BSD-3-Clause" ]
null
null
null
mmap_demo/main.cpp
xum07/small_demos
8e727cb7e005d7beb998419025cb1d47be9d0399
[ "BSD-3-Clause" ]
null
null
null
mmap_demo/main.cpp
xum07/small_demos
8e727cb7e005d7beb998419025cb1d47be9d0399
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <cstring> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include "mmap_utils.h" #include "utils.h" using std::string; bool WriteInMmap(string content, FileMmap *dstFileMmap) { if (EnlargeFileMmap(dstFileMmap, content.length()) == false) { PRINT_ERROR("failed to enlarge dstFileMmap to size(%u).", content.length()); return false; } content.copy(reinterpret_cast<char *>(dstFileMmap->freeBuff), content.length()); return true; } int main() { string dstFile = "dst_file"; remove(dstFile.c_str()); auto dstFileMmap = OpenFileMmap(dstFile.c_str()); if (dstFileMmap == nullptr) { PRINT_ERROR("failed to open file(%s) through mmap.", dstFile); return -1; } // write something to mmap auto result = WriteInMmap("Hello world!\n", dstFileMmap); if (result) { WriteInMmap("This is a mmap test.\n", dstFileMmap); } CloseFileMmap(dstFileMmap); return 0; }
24.166667
84
0.652217
xum07
195e399b868f63bf1b547c79b42d50c1adca4145
1,804
cpp
C++
src/windows/DiffWindowRastports.cpp
rosneru/ADiffView
5f7d6cf4c7b5c65ba1221370d272ba12c21f4911
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/windows/DiffWindowRastports.cpp
rosneru/ADiffView
5f7d6cf4c7b5c65ba1221370d272ba12c21f4911
[ "BSD-3-Clause", "MIT" ]
7
2019-02-09T18:27:06.000Z
2021-07-13T09:47:18.000Z
src/windows/DiffWindowRastports.cpp
rosneru/ADiffView
5f7d6cf4c7b5c65ba1221370d272ba12c21f4911
[ "BSD-3-Clause", "MIT" ]
null
null
null
#ifdef __clang__ #include <clib/graphics_protos.h> #else #include <proto/graphics.h> #endif #include "DiffWindowRastports.h" DiffWindowRastports::DiffWindowRastports(struct Window* pIntuiWindow, const ADiffViewPens& pens) { SetAPen(pIntuiWindow->RPort, pens.NormalText()); m_RPortWindow = *pIntuiWindow->RPort; m_RPortAPenBackgr = *pIntuiWindow->RPort; SetAPen(&m_RPortAPenBackgr, pens.Background()); m_RPortLineNum = *pIntuiWindow->RPort; SetBPen(&m_RPortLineNum, pens.Gray()); m_RPortTextDefault = *pIntuiWindow->RPort; SetBPen(&m_RPortTextDefault, pens.Background()); m_RPortTextSelected = *pIntuiWindow->RPort; SetAPen(&m_RPortTextSelected, pens.NormalText()); SetBPen(&m_RPortTextSelected, pens.HighlightedText()); m_RPortTextRedBG = *pIntuiWindow->RPort; SetBPen(&m_RPortTextRedBG, pens.Red()); m_RPortTextGreenBG = *pIntuiWindow->RPort; SetBPen(&m_RPortTextGreenBG, pens.Green()); m_RPortTextYellowBG = *pIntuiWindow->RPort; SetBPen(&m_RPortTextYellowBG, pens.Yellow()); } DiffWindowRastports::~DiffWindowRastports() { } struct RastPort* DiffWindowRastports::Window() { return &m_RPortWindow; } struct RastPort* DiffWindowRastports::APenBackgr() { return &m_RPortAPenBackgr; } struct RastPort* DiffWindowRastports::getLineNumText() { return &m_RPortLineNum; } struct RastPort* DiffWindowRastports::TextDefault() { return &m_RPortTextDefault; } struct RastPort* DiffWindowRastports::TextSelected() { return &m_RPortTextSelected; } struct RastPort* DiffWindowRastports::TextRedBG() { return &m_RPortTextRedBG; } struct RastPort* DiffWindowRastports::TextGreenBG() { return &m_RPortTextGreenBG; } struct RastPort* DiffWindowRastports::TextYellowBG() { return &m_RPortTextYellowBG; }
21.223529
69
0.748337
rosneru
195fcf5933d162d057aeb703df0b804b5386d481
596
cpp
C++
PXG3D/PXG3D/Subject.cpp
Developer-The-Great/Wooly
31619dec3baa165e7ae2b082aa026a467d1370ab
[ "Apache-2.0" ]
5
2020-02-13T08:54:46.000Z
2021-08-30T05:04:49.000Z
PXG3D/PXG3D/Subject.cpp
Developer-The-Great/Wooly
31619dec3baa165e7ae2b082aa026a467d1370ab
[ "Apache-2.0" ]
1
2020-02-11T11:46:37.000Z
2020-02-11T11:46:37.000Z
PXG3D/PXG3D/Subject.cpp
Developer-The-Great/Wooly
31619dec3baa165e7ae2b082aa026a467d1370ab
[ "Apache-2.0" ]
1
2020-03-19T13:05:22.000Z
2020-03-19T13:05:22.000Z
#include <vector> #include "Subject.h" #include "Subscriber.h" namespace PXG { void subject_base::notify(const event_t e) { for (subscriber_base* view : m_views) { view->onNotify(this, e); } } void subject_base::notifyFirst(const event_t e) { if (!m_views.empty()) m_views.front()->onNotify(this, e); } void subject_base::notifyLast(const event_t e) { if (!m_views.empty()) m_views.back()->onNotify(this, e); } void subject_base::notifyNext(const event_t e) { if (m_iter > m_views.size()) m_iter = 0; if (!m_views.empty()) m_views[m_iter++]->onNotify(this, e); } }
20.551724
61
0.671141
Developer-The-Great
19604b8b4b184db02c3f257f48a48cb8f5a6c3e6
3,322
cpp
C++
tests/depends/mmpa/src/mmpa_stub.cpp
fletcherjiang/ssm-alipay
d7cd911c72c2538859597b9ed3c96d02693febf2
[ "Apache-2.0" ]
169
2021-10-07T03:50:42.000Z
2021-12-20T01:55:51.000Z
tests/depends/mmpa/src/mmpa_stub.cpp
fletcherjiang/ssm-alipay
d7cd911c72c2538859597b9ed3c96d02693febf2
[ "Apache-2.0" ]
11
2021-10-09T01:53:49.000Z
2021-10-09T01:53:49.000Z
tests/depends/mmpa/src/mmpa_stub.cpp
JoeAnimation/ssm-alipay
d7cd911c72c2538859597b9ed3c96d02693febf2
[ "Apache-2.0" ]
56
2021-10-07T03:50:53.000Z
2021-10-12T00:41:59.000Z
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * 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 "mmpa/mmpa_api.h" #include "acl_stub.h" #include <string.h> INT32 aclStub::mmScandir2(const CHAR *path, mmDirent2 ***entryList, mmFilter2 filterFunc, mmSort2 sort) { return 0; } void* aclStub::mmAlignMalloc(mmSize mallocSize, mmSize alignSize) { return malloc(mallocSize); } INT32 mmScandir(const CHAR *path, mmDirent ***entryList, mmFilter filterFunc, mmSort sort) { return 0; } VOID mmScandirFree(mmDirent **entryList, INT32 count) { } INT32 mmScandir2(const CHAR *path, mmDirent2 ***entryList, mmFilter2 filterFunc, mmSort2 sort) { return MockFunctionTest::aclStubInstance().mmScandir2(path, entryList, filterFunc, sort); } VOID mmScandirFree2(mmDirent2 **entryList, INT32 count) { } INT32 mmAccess2(const CHAR *pathName, INT32 mode) { return 0; } INT32 mmGetEnv(const CHAR *name, CHAR *value, UINT32 len) { char environment[MMPA_MAX_PATH] = ""; (void)memcpy_s(value, MMPA_MAX_PATH, environment, MMPA_MAX_PATH); return 0; } INT32 mmRealPath(const CHAR *path, CHAR *realPath, INT32 realPathLen) { INT32 ret = EN_OK; if (path == nullptr || realPath == nullptr || realPathLen < MMPA_MAX_PATH) { return EN_INVALID_PARAM; } char *ptr = realpath(path, realPath); if (ptr == nullptr) { ret = EN_ERROR; } return ret; } INT32 mmStatGet(const CHAR *path, mmStat_t *buffer) { if ((path == nullptr) || (buffer == nullptr)) { return EN_INVALID_PARAM; } INT32 ret = stat(path, buffer); if (ret != EN_OK) { return EN_ERROR; } return EN_OK; } INT32 mmGetErrorCode() { return 0; } mmTimespec mmGetTickCount() { mmTimespec time; time.tv_nsec = 1; time.tv_sec = 1; return time; } INT32 mmGetTid() { INT32 ret = (INT32)syscall(SYS_gettid); if (ret < MMPA_ZERO) { return EN_ERROR; } return ret; } INT32 mmIsDir(const CHAR *fileName) { return 0; } INT32 mmGetPid() { return (INT32)getpid(); } INT32 mmGetTimeOfDay(mmTimeval *timeVal, mmTimezone *timeZone) { if (timeVal == nullptr) { return -1; } int32_t ret = gettimeofday((struct timeval *)timeVal, (struct timezone *)timeZone); return ret; } INT32 mmSleep(UINT32 milliSecond) { usleep(milliSecond); return 0; } mmSize mmGetPageSize() { return 2; } void *mmAlignMalloc(mmSize mallocSize, mmSize alignSize) { return MockFunctionTest::aclStubInstance().mmAlignMalloc(mallocSize, alignSize); } VOID mmAlignFree(VOID *addr) { if (addr != nullptr) { free(addr); } }
21.712418
105
0.647803
fletcherjiang
1962c69dee531f67c312f6c2ae98d2b023ba966a
13,123
cpp
C++
test/world_tests.cpp
extramask93/RayTracer
ba7f46fb212971e47b296991a7a7e981fef50dda
[ "Unlicense" ]
null
null
null
test/world_tests.cpp
extramask93/RayTracer
ba7f46fb212971e47b296991a7a7e981fef50dda
[ "Unlicense" ]
null
null
null
test/world_tests.cpp
extramask93/RayTracer
ba7f46fb212971e47b296991a7a7e981fef50dda
[ "Unlicense" ]
null
null
null
// // Created by damian on 09.07.2020. // #include <catch2/catch.hpp> #include <world/World.h> #include <lights/PointLight.h> #include <Tuple.h> #include <Color.h> #include <shapes/Sphere.h> #include <misc/Computations.h> #include <misc/Shader.h> #include <shapes/Plane.h> #include <patterns/TestPattern.h> SCENARIO("Creating a world") { GIVEN("A world") { auto w = rt::World(); THEN("") { REQUIRE(w.lights().size() == 0); REQUIRE(w.lights().size() == 0); } } } SCENARIO("The default world") { GIVEN("A light and spheres") { WHEN("Getting default values") { auto w = rt::World::defaultWorld(); THEN("") { REQUIRE(w->shapes().size() == 2); REQUIRE(w->lights().size() ==1); } } } } SCENARIO("Intersect a world with a ray"){ GIVEN("Default world") { auto w = rt::World::defaultWorld(); AND_GIVEN("A ray") { auto r = rt::Ray(util::Tuple::point(0,0,-5), util::Tuple::vector(0,0,1)); WHEN("Intersecting the world") { auto xs = w->intersect(r); THEN("") { REQUIRE(xs.size() == 4); REQUIRE(xs[0].t() == 4); REQUIRE(xs[1].t() == 4.5); REQUIRE(xs[2].t() == 5.5); REQUIRE(xs[3].t() == 6); } } } } } SCENARIO("Shading an instersection") { GIVEN("") { auto w = rt::World::defaultWorld(); auto r = rt::Ray(util::Tuple::point(0,0,-5), util::Tuple::vector(0,0,1)); auto shape = w->shapes()[0].get(); auto i = rt::Intersection(4,shape); WHEN("") { auto comps=rt::prepareComputations(i,r); auto c = rt::Shader::shadeHit(*w,comps); THEN("") { REQUIRE(c == util::Color(0.38066,0.47583,0.2855)); } } } } SCENARIO("Shading an instersection from the inside") { GIVEN("") { auto w = rt::World::defaultWorld(); w->lights()[0].reset(new rt::PointLight(util::Tuple::point(0,0.25,0), util::Color(1,1,1))); auto r = rt::Ray(util::Tuple::point(0,0,0), util::Tuple::vector(0,0,1)); auto shape = w->shapes()[1].get(); auto i = rt::Intersection(0.5,shape); WHEN("") { auto comps=rt::prepareComputations(i,r); auto c = rt::Shader::shadeHit(*w,comps); THEN("") { REQUIRE(c == util::Color(0.90498,0.90498,0.90498)); } } } } SCENARIO("The color when a ray misses") { GIVEN("") { auto w = rt::World::defaultWorld(); auto r = rt::Ray(util::Tuple::point(0,0,-5),util::Tuple::vector(0,1,0)); WHEN("") { auto c = rt::colorAt(*w,r); THEN("") { REQUIRE(c == util::Color(0,0,0)); } } } } SCENARIO("The color when a ray hits") { GIVEN("") { auto w = rt::World::defaultWorld(); auto r = rt::Ray(util::Tuple::point(0,0,-5),util::Tuple::vector(0,0,1)); WHEN("") { auto c = rt::colorAt(*w,r); THEN("") { REQUIRE(c == util::Color(0.38066,0.47583,0.2855)); } } } } SCENARIO("The color with an intersection behind the ray") { GIVEN("") { auto w = rt::World::defaultWorld(); auto outer = w->shapes()[0].get(); auto material = outer->material(); material.setAmbient(1); outer->setMaterial(material); auto inner = w->shapes()[1].get(); material = inner->material(); material.setAmbient(1); inner->setMaterial(material); auto r = rt::Ray(util::Tuple::point(0,0,0.75),util::Tuple::vector(0,0,-1)); WHEN("") { auto c = rt::colorAt(*w,r); THEN("") { REQUIRE(c == inner->material().color()); } } } } SCENARIO("There is no shadow when nothing is collinear with point and light") { GIVEN("") { auto w = rt::World::defaultWorld(); auto p = util::Tuple::point(0,10,0); THEN("") { REQUIRE(rt::isShadowed(*w,p) == false); } } } SCENARIO("The shadow when an object is between the point and the light") { GIVEN("") { auto w = rt::World::defaultWorld(); auto p = util::Tuple::point(10,-10,10); THEN("") { REQUIRE(rt::isShadowed(*w, p)); } } } SCENARIO("There is no shadow when an object is behind the light") { GIVEN("") { auto w = rt::World::defaultWorld(); auto p = util::Tuple::point(-20,20,-20); THEN("") { REQUIRE(rt::isShadowed(*w,p) == false); } } } SCENARIO("There is no shadow when an object is behind the point") { GIVEN("") { auto w = rt::World::defaultWorld(); auto p = util::Tuple::point(-2,2,-2); THEN("") { REQUIRE(rt::isShadowed(*w,p) == false); } } } SCENARIO("shadeHit is given an intersection in shadow") { GIVEN("") { auto world = rt::World(); world.lights().emplace_back(std::make_unique<rt::PointLight>(util::Tuple::point(0,0,-10),util::Color(1,1,1))); world.shapes().emplace_back(std::make_unique<rt::Sphere>()); world.shapes().emplace_back(std::make_unique<rt::Sphere>()); world.shapes()[1].get()->setTransform(util::Matrixd::translation(0,0,10)); auto r = rt::Ray(util::Tuple::point(0,0,5), util::Tuple::vector(0,0,1)); auto i = rt::Intersection(4,world.shapes()[1].get()); auto comps = rt::prepareComputations(i,r); auto c = rt::Shader::shadeHit(world,comps); THEN("") { REQUIRE(c == util::Color(0.1,0.1,0.1)); } } } SCENARIO("The reflected color for a nonreflective material") { GIVEN("") { auto world = rt::World::defaultWorld(); world->shapes()[1].get()->material().setAmbient(1); auto r = rt::Ray(util::Tuple::point(0,0,0), util::Tuple::vector(0,0,1)); auto i = rt::Intersection(1,world->shapes()[1].get()); auto comps = rt::prepareComputations(i,r); auto c = rt::reflectedColor(*world,comps,2); THEN("") { REQUIRE(c == util::Color(0,0,0)); } } } SCENARIO("The reflected color for a reflective material") { GIVEN("") { auto world = rt::World::defaultWorld(); auto shape = new rt::Plane(); shape->material().setReflective(0.5); shape->transform() = util::Matrixd::translation(0,-1,0); world->shapes().emplace_back(shape); auto r = rt::Ray(util::Tuple::point(0,0,-3), util::Tuple::vector(0,-sqrt(2)/2,sqrt(2)/2)); auto i = rt::Intersection(sqrt(2),world->shapes()[2].get()); auto comps = rt::prepareComputations(i,r); auto c = rt::reflectedColor(*world,comps); THEN("") { REQUIRE(c == util::Color(0.19033,0.23791,0.14274)); } } } SCENARIO("shadeHit with a reflective material") { GIVEN("") { auto world = rt::World::defaultWorld(); auto shape = new rt::Plane(); shape->material().setReflective(0.5); shape->transform() = util::Matrixd::translation(0,-1,0); world->shapes().emplace_back(shape); auto r = rt::Ray(util::Tuple::point(0,0,-3), util::Tuple::vector(0,-sqrt(2)/2,sqrt(2)/2)); auto i = rt::Intersection(sqrt(2),world->shapes()[2].get()); auto comps = rt::prepareComputations(i,r); auto c = rt::Shader::shadeHit(*world,comps); THEN("") { REQUIRE(c == util::Color(0.87676,0.92434,0.82918)); } } } SCENARIO("colorAt with mutually reflective surfaces") { GIVEN("") { auto world = rt::World(); world.lights().emplace_back(std::make_unique<rt::PointLight>(util::Tuple::point(0,0,0),util::Color(1,1,1))); auto lower = new rt::Plane(); lower->material().setReflective(1); lower->transform() = util::Matrixd::translation(0,-1,0); world.shapes().emplace_back(lower); auto upper = new rt::Plane(); upper->material().setReflective(1); upper->transform() = util::Matrixd::translation(0,1,0); world.shapes().emplace_back(upper); auto r = rt::Ray(util::Tuple::point(0,0,0), util::Tuple::vector(0,1,0)); THEN("") { REQUIRE_NOTHROW(rt::colorAt(world,r)); } } } SCENARIO("The reflected color at the maximum recursive depth") { GIVEN("") { auto world = rt::World::defaultWorld(); auto shape = new rt::Plane(); shape->material().setReflective(0.5); shape->transform() = util::Matrixd::translation(0,-1,0); world->shapes().emplace_back(shape); auto r = rt::Ray(util::Tuple::point(0,0,-3), util::Tuple::vector(0,-sqrt(2)/2,sqrt(2)/2)); auto i = rt::Intersection(sqrt(2),world->shapes()[2].get()); auto comps = rt::prepareComputations(i,r); auto c = rt::reflectedColor(*world,comps,0); THEN("") { REQUIRE(c == util::Color(0,0,0)); } } } SCENARIO("The refracted color with an opaque surface") { GIVEN("") { auto world = rt::World::defaultWorld(); auto shape = world->shapes()[0].get(); auto ray = rt::Ray(util::Tuple::point(0,0,-5), util::Tuple::vector(0,0,1)); auto xs = rt::Intersections{rt::Intersection(4,shape), rt::Intersection(6,shape)}; WHEN(""){ auto comps = rt::prepareComputations(xs[0],ray,xs); auto c = rt::refractedColor(*world,comps,5); THEN(""){ REQUIRE(c == util::Color(0,0,0)); } } } } SCENARIO("The refracted color at the maximum recursive dept") { GIVEN("") { auto world = rt::World::defaultWorld(); auto shape = world->shapes()[0].get(); shape->material().setRefractionIndex(1.5); shape->material().setTransparency( 1.0); auto ray = rt::Ray(util::Tuple::point(0,0,-5), util::Tuple::vector(0,0,1)); auto xs = rt::Intersections{rt::Intersection(4,shape), rt::Intersection(6,shape)}; WHEN(""){ auto comps = rt::prepareComputations(xs[0],ray,xs); auto c = rt::refractedColor(*world,comps,0); THEN(""){ REQUIRE(c == util::Color(0,0,0)); } } } } SCENARIO("The refracted color under total internal reflection") { GIVEN("") { auto world = rt::World::defaultWorld(); auto shape = world->shapes()[0].get(); shape->material().setRefractionIndex(1.5); shape->material().setTransparency( 1.0); auto ray = rt::Ray(util::Tuple::point(0,0,sqrt(2)/2), util::Tuple::vector(0,1,0)); auto xs = rt::Intersections{rt::Intersection(-sqrt(2)/2,shape), rt::Intersection(sqrt(2)/2,shape)}; WHEN(""){ auto comps = rt::prepareComputations(xs[1],ray,xs); auto c = rt::refractedColor(*world,comps,5); THEN(""){ REQUIRE(c == util::Color(0,0,0)); } } } } SCENARIO("The refracted color with a refracted ray") { GIVEN("") { auto world = rt::World::defaultWorld(); auto A = world->shapes()[0].get(); A->material().setAmbient(1.0); A->material().setPattern( std::make_unique<rt::TestPattern>(util::Color::BLACK, util::Color::BLACK)); auto B = world->shapes()[1].get(); B->material().setTransparency(1.0); B->material().setRefractionIndex( 1.5); auto ray = rt::Ray(util::Tuple::point(0,0,0.1), util::Tuple::vector(0,1,0)); auto xs = rt::Intersections{rt::Intersection(-0.9899,A), rt::Intersection(-0.4899,B), rt::Intersection(0.4899,B),rt::Intersection(0.9899,A)}; WHEN(""){ auto comps = rt::prepareComputations(xs[2],ray,xs); //std::swap(comps.n1,comps.n2); auto c = rt::refractedColor(*world,comps,5); THEN(""){ REQUIRE(c == util::Color(0,0.99888,0.04725)); } } } } SCENARIO("ShadeHit with a transparent material") { GIVEN("") { auto world = rt::World::defaultWorld(); world->shapes().emplace_back(std::make_unique<rt::Plane>()); auto floor = world->shapes()[2].get(); floor->transform() = util::Matrixd::translation(0,-1,0); floor->material().setTransparency(0.5); floor->material().setRefractionIndex(1.5); world->shapes().emplace_back(std::make_unique<rt::Sphere>()); auto ball = world->shapes()[3].get(); ball->transform() = util::Matrixd::translation(0,-3.5,-0.5); ball->material().setColor(util::Color(1,0,0)); ball->material().setAmbient(0.5); auto ray = rt::Ray(util::Tuple::point(0,0,-3), util::Tuple::vector(0,-sqrt(2)/2,sqrt(2)/2)); auto xs = rt::Intersections{rt::Intersection(sqrt(2),world->shapes()[2].get())}; WHEN(""){ auto comps = rt::prepareComputations(xs[0],ray,xs); auto c = rt::Shader::shadeHit(*world,comps,5); THEN(""){ REQUIRE(c == util::Color(0.93642,0.68642,0.68642)); } } } } SCENARIO("ShadeHit with a reflective, transparent material") { GIVEN("") { auto world = rt::World::defaultWorld(); world->shapes().emplace_back(std::make_unique<rt::Plane>()); auto floor = world->shapes()[2].get(); floor->transform() = util::Matrixd::translation(0,-1,0); floor->material().setTransparency(0.5); floor->material().setReflective(0.5); floor->material().setRefractionIndex(1.5); world->shapes().emplace_back(std::make_unique<rt::Sphere>()); auto ball = world->shapes()[3].get(); ball->transform() = util::Matrixd::translation(0,-3.5,-0.5); ball->material().setColor(util::Color(1,0,0)); ball->material().setAmbient(0.5); auto ray = rt::Ray(util::Tuple::point(0,0,-3), util::Tuple::vector(0,-sqrt(2)/2,sqrt(2)/2)); auto xs = rt::Intersections{rt::Intersection(sqrt(2),world->shapes()[2].get())}; WHEN(""){ auto comps = rt::prepareComputations(xs[0],ray,xs); auto c = rt::Shader::shadeHit(*world,comps,5); THEN(""){ REQUIRE(c == util::Color(0.93391,0.69643,0.69243)); } } } }
33.648718
114
0.588356
extramask93
196ac2543fd31bd2893b01fa002fadb19cd97a11
1,176
cpp
C++
Recursion 2/checkAB.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
2
2021-02-25T11:54:50.000Z
2021-02-25T11:54:54.000Z
Recursion 2/checkAB.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
null
null
null
Recursion 2/checkAB.cpp
PranavDherange/Data_Structures
9962b5145f6b42d9317e2c328c2b3124f028ca70
[ "MIT" ]
1
2021-10-03T17:39:10.000Z
2021-10-03T17:39:10.000Z
/*Problem Statement: Check AB Problem Level: MEDIUM Problem Description: Suppose you have a string, S, made up of only 'a's and 'b's. Write a recursive function that checks if the string was generated using the following rules: a. The string begins with an 'a' b. Each 'a' is followed by nothing or an 'a' or "bb" c. Each "bb" is followed by nothing or an 'a' If all the rules are followed by the given string, return true otherwise return false. Input format : String S Output format : 'true' or 'false' Constraints : 0 <= |S| <= 1000 where |S| represents length of string S. Sample Input 1 : abb Sample Output 1 : true Sample Input 2 : abababa Sample Output 2 : false*/ #include<iostream> #include<string> using namespace std; bool check(string s){ if(s.length() ==1 || s.length() == 0){ return true; } if(s[1] == 'b' && s.length() == 2){ return false; } if(s.length()>= 3 && s[0] == 'a' && s[1] == 'b' && s[2] == 'a'){ return false; } return check(s.substr(1)); } int main(){ string s; cin>>s; if(s[0] != 'a'){ cout<<false; return 0; } cout<<check(s); return 0; }
19.6
154
0.605442
PranavDherange
196b329ba87ccb6226e99712fc9251f0bbd725b7
1,222
cpp
C++
laborator1/problema3/problema3/Source.cpp
aquamineralis/oop-2022
d49475a00cafc2b3b35286e741506341c0ec9702
[ "MIT" ]
null
null
null
laborator1/problema3/problema3/Source.cpp
aquamineralis/oop-2022
d49475a00cafc2b3b35286e741506341c0ec9702
[ "MIT" ]
null
null
null
laborator1/problema3/problema3/Source.cpp
aquamineralis/oop-2022
d49475a00cafc2b3b35286e741506341c0ec9702
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <cstring> void sortWords(char words[][100], int wordCount) { for (int i = 0; i < wordCount - 1; i++) for (int j = i + 1; j < wordCount; j++) { if (strlen(words[i]) < strlen(words[j])) { char temp[100]; strcpy(temp, words[i]); strcpy(words[i], words[j]); strcpy(words[j], temp); } else if (strlen(words[i]) == strlen(words[j])) { if (strcmp(words[i], words[j]) > 0) { char temp[100]; strcpy(temp, words[i]); strcpy(words[i], words[j]); strcpy(words[j], temp); } } } } void solve() { int wordCount = 0; char words[100][100]; char string[10000]; scanf("%[^\n]s", string); char* word = strtok(string, " \n"); while (word != NULL) { strcpy(words[wordCount++], word); word = strtok(NULL, " \n"); } sortWords(words, wordCount); for (int i = 0; i < wordCount; i++) printf("%s\n", words[i]); } int main() { // I went to the library yesterday solve(); return 0; }
26.565217
62
0.467267
aquamineralis
19742e387c48a7a7b600adf985511a65ee672d5d
141
hpp
C++
libSrc/Color/ColorModule.hpp
burkeac/MPS_Tool_Kit
0da53595118dfbee37c0ec91681fd134b6479264
[ "MIT" ]
null
null
null
libSrc/Color/ColorModule.hpp
burkeac/MPS_Tool_Kit
0da53595118dfbee37c0ec91681fd134b6479264
[ "MIT" ]
1
2020-06-11T20:45:25.000Z
2020-06-11T20:45:25.000Z
libSrc/Color/ColorModule.hpp
burkeac/MPS_Tool_Kit
0da53595118dfbee37c0ec91681fd134b6479264
[ "MIT" ]
null
null
null
// ColorModule.hpp // Adam C. Burke (adam.burke603@gmail.com) // June 1, 2020 #pragma once #include "ColorSpaces.hpp" #include "deltaE.hpp"
17.625
42
0.70922
burkeac
198181b07a5f16250e6cdc50137b942e023ac448
2,679
cpp
C++
test/thread/source/TestThreadThreadPool.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
255
2019-06-11T07:05:51.000Z
2022-03-08T20:35:12.000Z
test/thread/source/TestThreadThreadPool.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
4
2019-08-10T21:35:17.000Z
2021-11-24T10:42:24.000Z
test/thread/source/TestThreadThreadPool.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
75
2019-07-08T00:16:33.000Z
2022-02-25T03:41:13.000Z
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include "TestThread.h" #include <EATest/EATest.h> #include <eathread/eathread_pool.h> #include <eathread/eathread_atomic.h> #include <stdlib.h> using namespace EA::Thread; const int kMaxConcurrentThreadCount = EATHREAD_MAX_CONCURRENT_THREAD_COUNT; struct TPWorkData { int mnWorkItem; TPWorkData(int nWorkItem) : mnWorkItem(nWorkItem) {} }; static AtomicInt32 gWorkItemsCreated = 0; static AtomicInt32 gWorkItemsProcessed = 0; static intptr_t WorkerFunction(void* pvWorkData) { TPWorkData* pWorkData = (TPWorkData*)pvWorkData; ThreadId threadId = GetThreadId(); EA::UnitTest::ReportVerbosity(1, "Work %4d starting for thread %s.\n", pWorkData->mnWorkItem, EAThreadThreadIdToString(threadId)); EA::UnitTest::ThreadSleepRandom(200, 600); ++gWorkItemsProcessed; EA::UnitTest::ReportVerbosity(1, "Work %4d ending for thread %s.\n", pWorkData->mnWorkItem, EAThreadThreadIdToString(threadId)); delete pWorkData; return 0; } int TestThreadThreadPool() { int nErrorCount(0); #if EA_THREADS_AVAILABLE { ThreadPoolParameters tpp; tpp.mnMinCount = kMaxConcurrentThreadCount - 1; tpp.mnMaxCount = kMaxConcurrentThreadCount - 1; tpp.mnInitialCount = 0; tpp.mnIdleTimeoutMilliseconds = EA::Thread::kTimeoutNone; // left in to test the usage of this kTimeout* defines. tpp.mnIdleTimeoutMilliseconds = 20000; ThreadPool threadPool(&tpp); int nResult; for(unsigned int i = 0; i < gTestLengthSeconds * 3; i++) { const int nWorkItem = (int)gWorkItemsCreated++; TPWorkData* const pWorkData = new TPWorkData(nWorkItem); EA::UnitTest::ReportVerbosity(1, "Work %4d created.\n", nWorkItem); nResult = threadPool.Begin(WorkerFunction, pWorkData, NULL, true); EATEST_VERIFY_MSG(nResult != ThreadPool::kResultError, "Thread pool failure in Begin."); EA::UnitTest::ThreadSleepRandom(300, 700); //Todo: If the pool task length gets too long, wait some more. } EA::UnitTest::ReportVerbosity(1, "Shutting down thread pool.\n"); bool bShutdownResult = threadPool.Shutdown(ThreadPool::kJobWaitAll, GetThreadTime() + 60000); EATEST_VERIFY_MSG(bShutdownResult, "Thread pool failure in Shutdown (waiting for jobs to complete)."); } EATEST_VERIFY_MSG(gWorkItemsCreated == gWorkItemsProcessed, "Thread pool failure: gWorkItemsCreated != gWorkItemsProcessed."); #endif return nErrorCount; }
26.524752
133
0.677118
tlzyh
198290997275a037c5c00df0f1cd698578d85c99
5,156
hxx
C++
include/usb/platforms/atxmega256a3u/types.hxx
DX-MON/dragonUSB
e3b43d786f767577822ba5e777d01328cd92a80d
[ "BSD-3-Clause" ]
4
2021-06-20T02:20:03.000Z
2021-12-30T01:43:02.000Z
include/usb/platforms/atxmega256a3u/types.hxx
DX-MON/dragonUSB
e3b43d786f767577822ba5e777d01328cd92a80d
[ "BSD-3-Clause" ]
null
null
null
include/usb/platforms/atxmega256a3u/types.hxx
DX-MON/dragonUSB
e3b43d786f767577822ba5e777d01328cd92a80d
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause #ifndef USB_PLATFORMS_ATXMEGA256A3U_TYPES___HXX #define USB_PLATFORMS_ATXMEGA256A3U_TYPES___HXX #include <flash.hxx> #include "usb/descriptors.hxx" template<> struct flash_t<usb::descriptors::usbMultiPartDesc_t> final { private: using T = usb::descriptors::usbMultiPartDesc_t; const T *value_; public: constexpr flash_t(const T *const value) noexcept : value_{value} { } constexpr flash_t(const flash_t &) noexcept = default; constexpr flash_t(flash_t &&) noexcept = default; constexpr flash_t &operator =(const flash_t &) noexcept = default; constexpr flash_t &operator =(flash_t &&) noexcept = default; ~flash_t() noexcept = default; T operator *() const noexcept { T result{}; const auto resultAddr{reinterpret_cast<uint32_t>(&result)}; const auto valueAddr{reinterpret_cast<uint32_t>(value_)}; const uint8_t x{RAMPX}; const uint8_t z{RAMPZ}; static_assert(sizeof(T) == 3); __asm__(R"( movw r26, %[result] out 0x39, %C[result] movw r30, %[value] out 0x3B, %C[value] elpm r16, Z+ st X+, r16 elpm r16, Z+ st X+, r16 elpm r16, Z st X+, r16 )" : : [result] "g" (resultAddr), [value] "g" (valueAddr) : "r16", "r26", "r27", "r30", "r31" ); RAMPZ = z; RAMPX = x; return result; } constexpr std::ptrdiff_t operator -(const flash_t &other) const noexcept { return value_ - other.value_; } constexpr flash_t operator +(const size_t offset) const noexcept { return {value_ + offset}; } constexpr flash_t &operator ++() noexcept { ++value_; return *this; } T operator[](const size_t offset) const noexcept { return *(*this + offset); } constexpr bool operator ==(const flash_t &other) const noexcept { return value_ == other.value_; } constexpr bool operator !=(const flash_t &other) const noexcept { return value_ != other.value_; } constexpr bool operator >=(const flash_t &other) const noexcept { return value_ >= other.value_; } [[nodiscard]] constexpr const T *pointer() const noexcept { return value_; } }; namespace usb::descriptors { struct usbMultiPartTable_t final { private: flash_t<usbMultiPartDesc_t> _begin{nullptr}; flash_t<usbMultiPartDesc_t> _end{nullptr}; public: constexpr usbMultiPartTable_t() noexcept = default; constexpr usbMultiPartTable_t(const usbMultiPartTable_t &) noexcept = default; constexpr usbMultiPartTable_t(usbMultiPartTable_t &&) noexcept = default; constexpr usbMultiPartTable_t(const usbMultiPartDesc_t *const begin, const usbMultiPartDesc_t *const end) noexcept : _begin{begin}, _end{end} { } ~usbMultiPartTable_t() noexcept = default; [[nodiscard]] constexpr auto begin() const noexcept { return _begin; } [[nodiscard]] constexpr auto end() const noexcept { return _end; } [[nodiscard]] constexpr auto count() const noexcept { return _end - _begin; } [[nodiscard]] auto part(const std::size_t index) const noexcept { if (_begin + index >= _end) return _end; return _begin + index; } auto operator [](const std::size_t index) const noexcept { return part(index); } [[nodiscard]] auto totalLength() const noexcept { // TODO: Convert to std::accumulate() later. std::uint16_t count{}; for (const auto descriptor : *this) count += descriptor.length; return count; } constexpr usbMultiPartTable_t &operator =(const usbMultiPartTable_t &) noexcept = default; constexpr usbMultiPartTable_t &operator =(usbMultiPartTable_t &&) noexcept = default; usbMultiPartTable_t &operator =(const flash_t<usbMultiPartTable_t> &data) noexcept; }; } // namespace usb::descriptors template<> struct flash_t<usb::descriptors::usbMultiPartTable_t> final { private: using T = usb::descriptors::usbMultiPartTable_t; T value_; public: constexpr flash_t(const T value) noexcept : value_{value} { } operator T() const noexcept { T result{}; const auto resultAddr{reinterpret_cast<uint32_t>(&result)}; const auto valueAddr{reinterpret_cast<uint32_t>(&value_)}; const uint8_t x{RAMPX}; const uint8_t z{RAMPZ}; static_assert(sizeof(T) == 4); __asm__(R"( movw r26, %[result] out 0x39, %C[result] movw r30, %[value] out 0x3B, %C[value] elpm r16, Z+ st X+, r16 elpm r16, Z+ st X+, r16 elpm r16, Z+ st X+, r16 elpm r16, Z st X+, r16 )" : : [result] "g" (resultAddr), [value] "g" (valueAddr) : "r16", "r26", "r27", "r30", "r31" ); RAMPZ = z; RAMPX = x; return result; } T operator *() const noexcept { return T{*this}; } [[nodiscard]] auto totalLength() const noexcept { const T table{*this}; return table.totalLength(); } }; namespace usb::descriptors { inline usbMultiPartTable_t & usbMultiPartTable_t::operator =(const flash_t<usbMultiPartTable_t> &data) noexcept { *this = usbMultiPartTable_t{data}; return *this; } inline namespace constants { using namespace usb::constants; } extern const std::array<flash_t<usbMultiPartTable_t>, configsCount> configDescriptors; extern const std::array<flash_t<usbMultiPartTable_t>, stringCount> strings; } // namespace usb::descriptors #endif /*USB_PLATFORMS_ATXMEGA256A3U_TYPES___HXX*/
27.72043
92
0.703064
DX-MON
1987e86ba760ec306b0a117367a42b8d081b7393
745
cpp
C++
src/util/tests/get_matches.t.cpp
cmburn/ope-c
208b2911ed0b7ffc0209bb4d5f9169a32e5433d8
[ "0BSD" ]
null
null
null
src/util/tests/get_matches.t.cpp
cmburn/ope-c
208b2911ed0b7ffc0209bb4d5f9169a32e5433d8
[ "0BSD" ]
null
null
null
src/util/tests/get_matches.t.cpp
cmburn/ope-c
208b2911ed0b7ffc0209bb4d5f9169a32e5433d8
[ "0BSD" ]
null
null
null
/* -*- mode: c++; c-default-style: "bsd"; -*- */ /* Copyright (c) 2020-2022 Charlie Burnett <burne251@umn.edu> */ /* SPDX-License-Identifier: ISC OR Apache-2.0 */ #include <gtest/gtest.h> #include "../util_hidden.h" TEST(get_matches, word) { auto m = ope::get_matches("foo", "foo"); auto count = ope::matches_get_count(m); ASSERT_NE(count, 0); /* avoid SEGFAULT */ EXPECT_EQ(count, 1); EXPECT_STREQ(ope::matches_get_at_index(m, 0), "foo"); ope::match_destroy(m); } TEST(get_matches, regexp) { auto m = ope::get_matches("foo bar baz", "[bar]{3}"); auto count = ope::matches_get_count(m); ASSERT_NE(count, 0); /* avoid SEGFAULT */ EXPECT_EQ(count, 1); EXPECT_STREQ(ope::matches_get_at_index(m, 0), "bar"); ope::match_destroy(m); }
26.607143
64
0.66443
cmburn
198973e29154634e3d2bf173f4641b8078942af0
281
cpp
C++
learnQtCreator/MathFunctions/MathFunctions.cpp
BigWhiteCat/Qt-QML
7d601721db535167ea257e8baffc1de83cc0aa15
[ "MIT" ]
null
null
null
learnQtCreator/MathFunctions/MathFunctions.cpp
BigWhiteCat/Qt-QML
7d601721db535167ea257e8baffc1de83cc0aa15
[ "MIT" ]
null
null
null
learnQtCreator/MathFunctions/MathFunctions.cpp
BigWhiteCat/Qt-QML
7d601721db535167ea257e8baffc1de83cc0aa15
[ "MIT" ]
null
null
null
#include "MathFunctions.h" MathFunctions::MathFunctions() { } unsigned long MathFunctions::factorial(unsigned int n) { switch (n) { case 0: return 0; case 1: return 1; default: return n * factorial(n - 1); } }
17.5625
56
0.530249
BigWhiteCat
19897cab7eee829a1322b1590b14289e163be31e
51
hpp
C++
src/boost_thread_win32_interlocked_read.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_thread_win32_interlocked_read.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_thread_win32_interlocked_read.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/thread/win32/interlocked_read.hpp>
25.5
50
0.823529
miathedev
1989dbb700696524f4dedb864728d15573c38b09
3,288
cpp
C++
src/swift2d/gui/FullscreenGuiSpriteComponent.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/gui/FullscreenGuiSpriteComponent.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/gui/FullscreenGuiSpriteComponent.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2015 Simon Schneegans & Felix Lauer // // // // This software may be modified and distributed under the terms // // of the MIT license. See the LICENSE file for details. // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/gui/FullscreenGuiSpriteComponent.hpp> #include <swift2d/gui/GuiShader.hpp> #include <swift2d/graphics/WindowManager.hpp> #include <swift2d/graphics/RendererPool.hpp> #include <swift2d/graphics/Pipeline.hpp> #include <swift2d/settings.hpp> namespace swift { //////////////////////////////////////////////////////////////////////////////// FullscreenGuiSpriteComponent::FullscreenGuiSpriteComponent() : Opacity(1) , Texture(nullptr) {} //////////////////////////////////////////////////////////////////////////////// void FullscreenGuiSpriteComponent::update(double time) { Component::update(time); DepthComponent::update(time, get_user()); } //////////////////////////////////////////////////////////////////////////////// void FullscreenGuiSpriteComponent::Renderer::draw(RenderContext const& ctx, int start, int end) { for (int i(start); i<end; ++i) { auto& o(objects[i]); o.Texture->bind(ctx, 0); GuiShader::get().use(); math::vec2 size( 1.0 * o.Size.x() / ctx.window_size.x(), 1.0 * o.Size.y() / ctx.window_size.y() ); math::vec3 offset( (2.0 * o.Offset.x() + o.Anchor.x() * (ctx.window_size.x() - o.Size.x()))/ctx.window_size.x(), (2.0 * o.Offset.y() + o.Anchor.y() * (ctx.window_size.y() - o.Size.y()))/ctx.window_size.y(), 0 ); GuiShader::get().size.Set(size); GuiShader::get().opacity.Set(o.Opacity); GuiShader::get().offset_rot.Set(offset); GuiShader::get().diffuse.Set(0); Quad::get().draw(); } } //////////////////////////////////////////////////////////////////////////////// void FullscreenGuiSpriteComponent::serialize(SerializedScenePtr& scene) const { Serialized s; s.Depth = WorldDepth(); s.Opacity = Opacity(); s.Size = SettingsWrapper::get().Settings->WindowSize(); s.Anchor = math::vec2(0.f, 0.f); s.Offset = math::vec2(0.f, 0.f); s.Texture = Texture(); scene->renderers().gui_sprite_elements.add(std::move(s)); } //////////////////////////////////////////////////////////////////////////////// void FullscreenGuiSpriteComponent::accept(SavableObjectVisitor& visitor) { Component::accept(visitor); DepthComponent::accept(visitor); visitor.add_member("Opacity", Opacity); visitor.add_object_property("Texture", Texture); } //////////////////////////////////////////////////////////////////////////////// }
36.94382
99
0.438564
Simmesimme
1989f9b5367e69ac41824af574e22b4cbbb9d21a
436
hpp
C++
TCCore/QuickGraphCut.hpp
SeaTurtle22/TinyCrayon-iOS-SDK
729c182c282c72d408902e4dd092b464e4904aed
[ "MIT" ]
null
null
null
TCCore/QuickGraphCut.hpp
SeaTurtle22/TinyCrayon-iOS-SDK
729c182c282c72d408902e4dd092b464e4904aed
[ "MIT" ]
null
null
null
TCCore/QuickGraphCut.hpp
SeaTurtle22/TinyCrayon-iOS-SDK
729c182c282c72d408902e4dd092b464e4904aed
[ "MIT" ]
null
null
null
// // QuickGraphCut.hpp // TinyCrayon // // Created by Xin Zeng on 11/14/15. // Copyright © 2015 Xin Zeng. All rights reserved. // #ifndef QuickGraphCut_hpp #define QuickGraphCut_hpp #import <opencv2/opencv.hpp> #import <opencv2/imgproc/imgproc_c.h> #include <stdio.h> #include "FGMM.hpp" #include "FGCGraph.hpp" using namespace cv; bool quickGraphCut(const Mat &img, Mat &mask, int iterCount); #endif /* QuickGraphCut_hpp */
18.166667
61
0.722477
SeaTurtle22
198b4afac7899caee79a88cdfa8cc53a45018d49
433
cpp
C++
Engine/02_system/04_render/02_GL/01_Objects/GL_VBO.cpp
TB989/Fierce-Engine
4fa97b55fafdf97ee0b9eb72203425490b7a01c5
[ "Apache-2.0" ]
null
null
null
Engine/02_system/04_render/02_GL/01_Objects/GL_VBO.cpp
TB989/Fierce-Engine
4fa97b55fafdf97ee0b9eb72203425490b7a01c5
[ "Apache-2.0" ]
43
2020-03-01T12:55:12.000Z
2021-07-10T20:51:23.000Z
Engine/02_system/04_render/02_GL/01_Objects/GL_VBO.cpp
TB989/Fierce-Engine
4fa97b55fafdf97ee0b9eb72203425490b7a01c5
[ "Apache-2.0" ]
null
null
null
#include "GL_VBO.h" GL_VBO::GL_VBO(GLenum type){ m_type = type; glGenBuffers(1, &m_id); } GL_VBO::~GL_VBO(){ glDeleteBuffers(1, &m_id); } void GL_VBO::bind(){ glBindBuffer(m_type, m_id); } void GL_VBO::unbind(){ glBindBuffer(m_type, 0); } void GL_VBO::loadData(GLsizeiptr size,const void *data,GLenum usage){ m_size = size; glBindBuffer(m_type, m_id); glBufferData(m_type, size, data, usage); glBindBuffer(m_type, 0); }
17.32
69
0.702079
TB989
198e588d41158b856f1489777ad472beb9cdf55d
546
hpp
C++
library/ATF/$CE1967C81C4C59269727E4AA1D2A6A5A.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/$CE1967C81C4C59269727E4AA1D2A6A5A.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/$CE1967C81C4C59269727E4AA1D2A6A5A.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <HBITMAP__.hpp> #include <HENHMETAFILE__.hpp> #include <IStorage.hpp> #include <IStream.hpp> START_ATF_NAMESPACE union $CE1967C81C4C59269727E4AA1D2A6A5A { HBITMAP__ *hBitmap; void *hMetaFilePict; HENHMETAFILE__ *hEnhMetaFile; void *hGlobal; wchar_t *lpszFileName; IStream *pstm; IStorage *pstg; }; END_ATF_NAMESPACE
22.75
108
0.692308
lemkova
19904b9a8cd3973ba4571a40c3f1bf13c35789f5
7,423
cpp
C++
sources/HybridDetector/VectorClock.cpp
onderkalaci/dyndatarace
8e916b11d2d4f6d812d4b0c5a2616387be4d6572
[ "Intel" ]
6
2018-01-11T01:47:01.000Z
2022-03-08T16:22:59.000Z
sources/HybridDetector/VectorClock.cpp
chakku000/dyndatarace
8e916b11d2d4f6d812d4b0c5a2616387be4d6572
[ "Intel" ]
1
2018-01-11T02:36:09.000Z
2018-01-12T03:32:41.000Z
sources/HybridDetector/VectorClock.cpp
chakku000/dyndatarace
8e916b11d2d4f6d812d4b0c5a2616387be4d6572
[ "Intel" ]
2
2018-01-15T02:37:50.000Z
2021-03-21T14:53:44.000Z
# # +--------------------------------------------------------------------------+ # |Copyright (C) 2014 Bogazici University | # | onderkalaci@gmail.com | # | | # | This is free software: you can redistribute it and/or modify | # | it under the terms of the GNU Lesser General Public License as published | # | by the Free Software Foundation, either version 2.1 of the License, or | # | (at your option) any later version. | # | | # | This is distributed in the hope that it will be useful, | # | but WITHOUT ANY WARRANTY; without even the implied warranty of | # | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | # | GNU Lesser General Public License for more details. | # | | # | You should have received a copy of the GNU Lesser General Public License | # | along with this program. If not, see <http://www.gnu.org/licenses/>. | # +--------------------------------------------------------------------------+ /* * VectorClock.cpp * * Created on: Apr 19, 2013 * Author: onder */ #include "VectorClock.h" using namespace::std; /** * Vector Clock Implementation * * **/ /* * This parameter is utilezed * for Vector Clock History Cache optimization * If this value equals zero, the optimization is not executed * */ extern UINT64 maxVCHistoryCount; /* * total process count defines * the size of vector clock * for our experiments these parameters * are statically defined befor run time */ int VectorClock::totalProcessCount = 48; /* * This function is intended for debug purposes * It prints vector clock nicely */ ostream& operator<<(ostream& os, const VectorClock& v) { os << "Vector Clock Of " << v.processId << ":" << endl; unsigned int *values = v.getValues(); for (int i = 0; i < v.totalProcessCount; ++i) { os << setw(32) << values[i]; if ( (i +1) % 8 == 0) os << endl; } return os; } /* * Vector clock increment operations, both post and pre increments * ++v or v++ * */ VectorClock& VectorClock::operator++() //++v; { v[processId]++; return *this; } VectorClock VectorClock::operator++(int) //v++; { VectorClock tmp = *this; v[processId]++; return tmp; } bool VectorClock::operator<=(const VectorClock& vRight) { if (operator<(vRight) || operator==(vRight) ) //kucuk ya da esitse, kucuk esittir return true; return false; } bool VectorClock::operator<(const VectorClock& vRight) { bool strictlySmaller = false; unsigned int* vRightValues = vRight.getValues(); for (int i = 0; i < totalProcessCount; ++i) { if ( v[i] < vRightValues[i] ) //at least ONE value is stricly smaller strictlySmaller = true; else if (v[i] > vRightValues[i]) //if any value of v[i] is greater, than no way v<vRight return false; } return strictlySmaller; //if there happened strictlySmaller, then smaller operation returns true; } extern UINT64 isPairExistsVectorCount ; extern UINT64 addVectorCount ; /* * isPairExistsVector function is used * for Vector Clock History cache improvement * if the same comparison is done before, return true */ inline bool VectorClock::isPairExistsVector(UINT64 key, UINT64 InprocessId) { ++isPairExistsVectorCount; return maxVCHistoryCount && (/*(InprocessId == (UINT64) this->processId) ||*/ find(vcHistoryVector.begin(), vcHistoryVector.end(), (UINT64)key) != vcHistoryVector.end() ); } /* * addNodeVectorToHistory adds new vector clock id to * vector clock history cache */ inline void VectorClock::addNodeVectorToHistory(UINT64 id) //this method adds the node at the end of the chain { if (maxVCHistoryCount) return; if (alreadyFilled /*&&size >= maxVCHistoryCount*/) vcHistoryVector[id % maxVCHistoryCount] = id; else { vcHistoryVector.push_back(id); if (vcHistoryVector.size() == maxVCHistoryCount ) alreadyFilled = true; } } extern UINT64 vcHitCount; extern UINT64 vcNonHitCount; /* * v1->happensBefore(v2) returns true * iff v1 happens before v2 :) * Moreover, if vector clock comp. cache is enabled, * the comparion is added to cache of v1 * */ bool VectorClock::happensBefore(VectorClock* input) { if ( isPairExistsVector((UINT64)input,input->processId)) { ++vcHitCount; //just for statistical information //return val; return true; } else ++vcNonHitCount; int thisProcessId = this->processId; int inputProcessId = input->processId; if ( ((this->v[thisProcessId] <= input->v[thisProcessId] ) && (this->v[inputProcessId] < input->v[inputProcessId] ))) { addNodeVectorToHistory((UINT64)input); return true; } return false; } /* * Basic VC operations != and == is defined */ bool VectorClock::operator!=(const VectorClock& vRight) { return !(operator==(vRight)); } bool VectorClock::operator==(const VectorClock& vRight) { unsigned int *vRightValues = vRight.getValues(); for (int i = 0; i < totalProcessCount; ++i) if (v[i] != vRightValues[i]) return false; return true; } /* * Create vector clock for each thread * */ VectorClock::VectorClock(int processIdIn) { processId = processIdIn; alreadyFilled = false; vcHistoryVector.reserve(maxVCHistoryCount); size_t size_of_bytes = sizeof(int) * totalProcessCount; v = (unsigned int*)malloc(size_of_bytes); bzero(v, size_of_bytes); //bzero yapmak onemli v[processIdIn] = 1; //this->history = new VCHistoryNode(UINT64(this)); } /* * Initilaze vector clock from an existing clock * For instance, this kind of constructor is used * when a new segment is created * */ VectorClock::VectorClock(VectorClock* inClockPtr, int processIdIn) { this->vcHistoryVector = inClockPtr->vcHistoryVector; alreadyFilled = inClockPtr->alreadyFilled; processId = processIdIn; //processId su an isimize yaramaz bu sekilde olustrulan vector clock icin, ancak ilerde yarayabilir size_t size_of_bytes = sizeof(int) * totalProcessCount; v = (unsigned int*)malloc(size_of_bytes); bzero(v, size_of_bytes); //bzero yapmak onemli for (int i = 0; i < totalProcessCount; ++i ) v[i] = inClockPtr->v[i]; } int VectorClock::totalDeletedLockCount = 0; //just for statistical analysis /* * Vector clock destructor free the integers */ VectorClock::~VectorClock() { //cout << "Vector Clock Destructor Called" << endl; totalDeletedLockCount++; //free(v); free(v); } void VectorClock::sendEvent() { event(); } /* * Internal VC event */ void VectorClock::event() { v[processId]++; } /* * Get Values for VC comparison */ unsigned int* VectorClock::getValues() const { return v; } /* * v1->receiveAction(v2) ie v1 waits on cond. var. and * v2 notifies */ void VectorClock::receiveAction(VectorClock* vectorClockReceived) { unsigned int *vOfReceivedClock = vectorClockReceived->getValues(); for (int i = 0; i < totalProcessCount; ++i) v[i] = ( v[i] > vOfReceivedClock[i] ) ? v[i] : vOfReceivedClock[i]; //event(); } void VectorClock::toString() { //cout << "segmentId:" << processId << "\t"; //for (int i=0; i < totalProcessCount; ++i) //cout << v[i] << " " ; //cout << endl; }
25.596552
177
0.637748
onderkalaci
1997f42758e867ce0c0d2f335681b590126ab221
1,315
cpp
C++
main.cpp
sl1pkn07/Phonon_Tester
05d3cf8f5ff4329234430f3cd925407d08d4539d
[ "BSD-3-Clause" ]
null
null
null
main.cpp
sl1pkn07/Phonon_Tester
05d3cf8f5ff4329234430f3cd925407d08d4539d
[ "BSD-3-Clause" ]
null
null
null
main.cpp
sl1pkn07/Phonon_Tester
05d3cf8f5ff4329234430f3cd925407d08d4539d
[ "BSD-3-Clause" ]
null
null
null
#include <QApplication> #include <QCommandLineParser> #include <KAboutData> #include <KLocalizedString> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); KAboutData aboutData(QStringLiteral("PhononTester"), i18n("Phonon Tester. only Audio"), QStringLiteral("1.0"), i18n("A Phonon tester. only Audio."), KAboutLicense::BSDL, i18n("(c) 2019")); aboutData.setHomepage(QStringLiteral("https://github.com/sl1pkn07")); aboutData.setBugAddress("https://github.com/sl1pkn07/Phonon_Tester/issues"); aboutData.addAuthor(i18n("Gustavo Alvarez. (c) 2019"), i18n(" "), QStringLiteral("sl1pkn07@gmail.com")); aboutData.addAuthor(i18n("Jon Ander Peñalba. Original author. (c) 2011-2013"), i18n(" "), QStringLiteral("jonan88@gmail.com")); KAboutData::setApplicationData(aboutData); QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); aboutData.setupCommandLine(&parser); parser.process(app); aboutData.processCommandLine(&parser); MainWindow *window = new MainWindow(); window->show(); return app.exec(); }
33.717949
114
0.612928
sl1pkn07
1998d5e4732f34012af5d1f223cf638c6cb4efa5
13,103
cpp
C++
clientwidget.cpp
GiadaTrevisani/SimpleBusinessManager
dec23378faffd4390befecfd52df8103a78b8523
[ "MIT" ]
2
2018-10-09T19:55:59.000Z
2019-05-10T09:11:51.000Z
clientwidget.cpp
GiadaTrevisani/SimpleBusinessManager
dec23378faffd4390befecfd52df8103a78b8523
[ "MIT" ]
null
null
null
clientwidget.cpp
GiadaTrevisani/SimpleBusinessManager
dec23378faffd4390befecfd52df8103a78b8523
[ "MIT" ]
null
null
null
#include "clientwidget.h" ClientWidget::ClientWidget(QWidget *parent) : QWidget(parent) { /* * in questa classe creiamo la window principale dei clienti, dove io mi trovo una line edit cerca * dove inserendo dei caratteri, con il connect posso cercarli dentro il mio database (guarda query * nel metodo getModel nella classe ClientiDatabaseManager) e visualizzarli nella client tab subito sotto. * se non cerco niente, nella tabella ho tutti i miei elementi, dal primo all'ultimo. * in alto a destra di fianco alla line edit cerca ho il bottone new, cliccando li sopra posso * aggiungere al database un cliente che verra visualizzato nella tableView appena inserito. * Cliccando sul tasto new si apre una finestra sopra quella attuale di clienti (reso possibile attraverso * il comadno stack e inserendo iol comando setcuirrentindex al widget del mio new) dove io posso aggiungere * un cliente (tutto specificato nella funzione NewClientClicked). * sotto invece nella table view invece ho l'elenco di tutti i miei clienti della line edit ricerca * e doppiocliccando su un elemento si aggiunge una finestra di dettaglio sopra quella dei clienti (comando stack->setcurrentindex) * dove viene visualizzato ogni elemento del cliente cliccato. c'è anche la possibilità di modifica. in pratica * la finestra di dettaglio è la stessa che usiamo per un nuovo cliente, solo che nella new il bottone * per salvare si chiama AGGIUNGI e le line edit sono vuote, invece nell'update il bottone si chiama * AGGIORNA e nelle line edit ci sono i campi riempiti e per aggiornarli basta scriverci sopra e cliccare sul bottone. * In più se ci sono dei campi che non si possono modificare nel codice inseriamo il comando setenable false. * */ newClient = new QPushButton(); txtCerca = new QLineEdit(); txtCerca->setPlaceholderText("Cerca Cliente"); txtCerca->setText(""); clientTab = new QTableView(); QHBoxLayout *h_client = new QHBoxLayout(); QVBoxLayout *v_client = new QVBoxLayout(); newClient->setText("NEW"); h_client->addWidget(txtCerca); h_client->addWidget(newClient); v_client->addLayout(h_client); v_client->addWidget(clientTab); /* * da qua in poi inseriamo il layout della finestra di dettaglio che si aprirà * con il comando stack->setcurrentIndex al doppioclick di un elemento di un determinato * cliente. in questa finestra è possibile modificare un cliente riempioendo le line * edit con queello che si vuole cambiare e cliccare su aggiorna */ //secondo layout visualizzazione in dettagilio di clienti QLabel *infoClient = new QLabel(); infoClient->setText("Informazioni cliente"); QLabel *sedeClient = new QLabel(); sedeClient->setText("Sede cliente"); QLabel *clientRagSoc = new QLabel(); QLabel *clientName = new QLabel(); QLabel *clientSurname = new QLabel(); QLabel *clientTel = new QLabel(); QLabel *clientMail = new QLabel(); QLabel *clientPIva = new QLabel(); QLabel *clientFiscalC = new QLabel(); //primary key QLabel *clientAddress = new QLabel(); QLabel *clientCity = new QLabel(); QLabel *clientCap = new QLabel(); aggiorna_add = new QPushButton(); back = new QPushButton(); txtclientName = new QLineEdit(); txtragSoc = new QLineEdit(); txtclientSurname = new QLineEdit(); txtclientTel = new QLineEdit(); txtclientMail = new QLineEdit(); txtclientPIva = new QLineEdit(); txtclientFiscalC = new QLineEdit(); txtclientAddress = new QLineEdit(); txtclientCity = new QLineEdit(); txtclientCap = new QLineEdit(); QVBoxLayout *v_finalClient = new QVBoxLayout(); QHBoxLayout *h_divide = new QHBoxLayout(); QVBoxLayout *v_divide1 = new QVBoxLayout(); QVBoxLayout *v_divide2 = new QVBoxLayout(); QHBoxLayout *h_ragSoc = new QHBoxLayout(); QHBoxLayout *h_nameC= new QHBoxLayout(); QHBoxLayout *h_surnameC= new QHBoxLayout(); QHBoxLayout *h_telC= new QHBoxLayout(); QHBoxLayout *h_mailC= new QHBoxLayout(); QHBoxLayout *h_addressC= new QHBoxLayout(); QHBoxLayout *h_pIvaC= new QHBoxLayout(); QHBoxLayout *h_cityC= new QHBoxLayout(); QHBoxLayout *h_capC= new QHBoxLayout(); QHBoxLayout *h_codeFC= new QHBoxLayout(); clientRagSoc->setText("Ragione sociale: "); clientName->setText("Nome: "); clientSurname->setText("Cognome: "); clientTel->setText("Telefono: "); clientMail->setText("Mail: "); clientAddress->setText("Indirizzo: "); clientPIva->setText("Partita iva: "); clientFiscalC->setText("Codice fiscale: "); clientCity->setText("Città: "); clientCap->setText("Cap: "); aggiorna_add->setText("AGGIORNA"); back->setText("<- Indietro"); back->setFixedSize(QSize(100,30)); h_ragSoc->addWidget(clientRagSoc); h_ragSoc->addWidget(txtragSoc); h_nameC->addWidget(clientName); h_nameC->addWidget(txtclientName); h_surnameC->addWidget(clientSurname); h_surnameC->addWidget(txtclientSurname); h_mailC->addWidget(clientMail); h_mailC->addWidget(txtclientMail); h_codeFC->addWidget(clientFiscalC); h_codeFC->addWidget(txtclientFiscalC); h_pIvaC->addWidget(clientPIva); h_pIvaC->addWidget(txtclientPIva); h_telC->addWidget(clientTel); h_telC->addWidget(txtclientTel); h_cityC->addWidget(clientCity); h_cityC->addWidget(txtclientCity); h_addressC->addWidget(clientAddress); h_addressC->addWidget(txtclientAddress); h_capC->addWidget(clientCap); h_capC->addWidget(txtclientCap); v_divide1->addWidget(infoClient); v_divide1->addLayout(h_ragSoc); v_divide1->addLayout(h_nameC); v_divide1->addLayout(h_surnameC); v_divide1->addLayout(h_codeFC); v_divide1->addLayout(h_mailC); v_divide2->addWidget(sedeClient); v_divide2->addLayout(h_pIvaC); v_divide2->addLayout(h_telC); v_divide2->addLayout(h_cityC); v_divide2->addLayout(h_addressC); v_divide2->addLayout(h_capC); h_divide->addLayout(v_divide1); h_divide->addLayout(v_divide2); v_finalClient->addWidget(back); v_finalClient->addLayout(h_divide); v_finalClient->addWidget(aggiorna_add); //-------------------------------- //Maschero i Layouts da Widget per usare il metodo addWidget() QWidget* c0 = new QWidget(); // primo stack con la vista standard c0->setLayout(v_client); QWidget* c1 = new QWidget(); // secondo stack con la vista dettaglio del cliente c1->setLayout(v_finalClient); stack = new QStackedLayout(); stack->addWidget(c0); stack->addWidget(c1); stack->setCurrentIndex(0); this->setLayout(stack); //--------------------------------------- txtclientFiscalC->setEnabled(false); //Setup model db = new ClientDatabaseManager(this); model = db->getModel(txtCerca->text()); clientTab->setModel(model); clientTab->setSelectionBehavior(QAbstractItemView::SelectRows); clientTab->setSelectionMode(QAbstractItemView::SingleSelection); /* * di seguito vengono definiti i connect, cioè ad un dato segnale corrisponde * una risposta o invocazione di un metodo*/ /* * 1° connect se si doppioclicca un cliente nella tabella dei clienti viene * chiamato il metodo clientSelected che aprirà attraverso lo stack la finestra di * dettaglio su quel cliente. */ QObject::connect(clientTab, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(clientSelected(QModelIndex))); /* * 2°connect: se io clicco su il bottone newclient in questa finestra di fianco alla search line edit * mi chiama la funzione newClientClicked dove io posso inserire un nuovo cliente. nel caso io mi sia sbagliata * a cliccare su new è possibile tornare insietro senza modificare niente. */ QObject::connect(newClient, SIGNAL(clicked(bool)), this, SLOT(newClientClicked())); /* *3° connect: se siamo nell finestra di dettaglio e vogliamo aggiornare un cliente * basta riscrivere sopra il campo che voglio cambiare il nuovo valore e cliccare * su aggiorna. quando clicco l'evento connect chiama la funzione updateClient * dove va ad aggiornare il database attraverso la query fornita dalla funzione */ QObject::connect(aggiorna_add, SIGNAL(clicked(bool)), this, SLOT(updateClient())); /* *4°connect: se cerchiamo un cliente nella line edit cerca, ad ogni carattere che inseriamo * viene chiamato il metodo serachChanged dove si fa una query al database che cerca parole * simili ai caratteri inseriti tra tutti gli alementi qstring dei clienti(tutti in questpo caso) */ QObject::connect(txtCerca, SIGNAL(textEdited(QString)), this, SLOT(searchChanged(QString))); /* *5° connect: se clicco il pulsante back ("->") chiama la funzione goToMainView e torna * attraverso il comando stack_>setCurrentIndex alla finestra principale */ QObject::connect(back, SIGNAL(clicked(bool)), this, SLOT(goToMainView())); newORdetail = false; } /* * deallochiamo il model vecchio e ne facciamo uno nuovo creando un nuovo database */ void ClientWidget::updateModel(){ //model->query().exec(); // aggiorna la vista delete model; model = db->getModel(txtCerca->text()); clientTab->setModel(model); } /* * creiamo un dizionario di nome data vuoto e inseriamo le stringhe dentro le edit line */ void ClientWidget::updateClient(){ QHash<QString, QString>* data = new QHash<QString, QString>(); data->insert("name", txtclientName->text()); data->insert("surname", txtclientSurname->text()); data->insert("ragioneSoc", txtragSoc->text()); data->insert("tel", txtclientTel->text()); data->insert("mail", txtclientMail->text()); data->insert("piva", txtclientPIva->text()); data->insert("address", txtclientAddress->text()); data->insert("city", txtclientCity->text()); data->insert("cap", txtclientCap->text()); //controlla che i campi siano tutti riempiti (quelli not null obbligatori) bool res; if(newORdetail){ res = db->insertElement(txtclientFiscalC->text(), data); } else { res = db->updateElement(txtclientFiscalC->text(), data); } this->stack->setCurrentIndex(0); delete data; updateModel(); if(!res){ QMessageBox msgBox; msgBox.setText("C'è stato un errore nell'inserimento dei dati"); msgBox.exec(); } } /* * dealloco anche qui il model e poi lo rialloco con il database */ void ClientWidget::searchChanged(QString src) { delete model; model = db->getModel(src); clientTab->setModel(model); } /* * chiamo la funzione update model che dealloca e rialloca tutto il database *e poi ritorno alla finestra principale */ void ClientWidget::goToMainView(){ updateModel(); this->stack->setCurrentIndex(0); } /* * newORdetail se è vero sono nella modalità nuovo cliente e quindi cambiano i bottoni * e le line edit */ void ClientWidget::clientSelected(QModelIndex idx){ newORdetail = false; aggiorna_add->setText("AGGIORNA"); txtclientFiscalC->setEnabled(false); //get id from table QString id = model->itemData(model->index(idx.row(), 0)).value(0).toString(); QHash<QString, QString>* data = db->getElement(id); if(data->value("error") == "true"){ QMessageBox msgBox; msgBox.setText("C'è stato un errore, elemento non esistente"); msgBox.exec(); delete data; return; } //riempi i campi txtclientName->setText(data->value("name")); txtragSoc->setText(data->value("ragioneSoc")); txtclientSurname->setText(data->value("surname")); txtclientTel->setText(data->value("tel")); txtclientMail->setText(data->value("mail")); txtclientPIva->setText(data->value("piva")); txtclientFiscalC->setText(id); txtclientAddress->setText(data->value("address")); txtclientCity->setText(data->value("city")); txtclientCap->setText(data->value("cap")); this->stack->setCurrentIndex(1); delete data; } void ClientWidget::newClientClicked() { newORdetail = true; aggiorna_add->setText("Inserisci"); txtclientFiscalC->setEnabled(true); txtclientName->setText(""); txtragSoc->setText(""); txtclientSurname->setText(""); txtclientTel->setText(""); txtclientMail->setText(""); txtclientPIva->setText(""); txtclientFiscalC->setText(""); txtclientAddress->setText(""); txtclientCity->setText(""); txtclientCap->setText(""); this->stack->setCurrentIndex(1); } ClientWidget::~ClientWidget(){ delete newClient; delete txtCerca; delete clientTab; delete newClient; delete aggiorna_add; delete txtclientName; delete txtclientSurname; delete txtclientAddress; delete txtclientCap; delete txtclientCity; delete txtclientFiscalC; delete txtclientMail; delete txtclientPIva; delete txtclientTel; delete txtragSoc; delete model; delete back; }
37.11898
135
0.695184
GiadaTrevisani
199b2ee2d0b1ca5a8f0de768563cafe1fa6586ba
758
cpp
C++
Tools/GUILayer/Exceptions.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
3
2015-12-04T09:16:53.000Z
2021-05-28T23:22:49.000Z
Tools/GUILayer/Exceptions.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
null
null
null
Tools/GUILayer/Exceptions.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
2
2015-03-03T05:32:39.000Z
2015-12-04T09:16:54.000Z
// Copyright 2016 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "Exceptions.h" #include "MarshalString.h" namespace GUILayer { System::Exception^ Marshal(const std::exception& e) { // note -- when we do this marshalling step, we loose the callstack // that we would normally get with a SEHException, but we gain // the exception message from std::exception::what() // // It's difficult to grab the callstack from when the exception // occurred, because we've caught it using the c++ mechanisms, rather than // the SEH mechanisms. return gcnew System::Exception(clix::marshalString<clix::E_UTF8>(e.what())); } }
31.583333
78
0.717678
alexgithubber
199d531524e20a4527e18545073a1b33d1b12d03
3,860
cpp
C++
src/ui/models/preferred_draw_systems_model.cpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
3
2019-04-26T17:48:24.000Z
2021-11-08T20:21:51.000Z
src/ui/models/preferred_draw_systems_model.cpp
svendcsvendsen/judoassistant
453211bff86d940c2b2de6f9eea2aabcdab830fa
[ "MIT" ]
90
2019-04-25T17:23:10.000Z
2022-02-12T19:49:55.000Z
src/ui/models/preferred_draw_systems_model.cpp
judoassistant/judoassistant
3b200d3e35d9aff16ba224e6071ee9d888a5a03c
[ "MIT" ]
null
null
null
#include "core/actions/change_draw_system_preference_identifier_action.hpp" #include "core/actions/change_draw_system_preference_limit_action.hpp" #include "ui/models/preferred_draw_systems_model.hpp" #include "ui/store_managers/store_manager.hpp" PreferredDrawSystemsModel::PreferredDrawSystemsModel(StoreManager &storeManager, QObject *parent) : mStoreManager(storeManager) { beginResetTournament(); endResetTournament(); connect(&mStoreManager, &StoreManager::tournamentAboutToBeReset, this, &PreferredDrawSystemsModel::beginResetTournament); connect(&mStoreManager, &StoreManager::tournamentReset, this, &PreferredDrawSystemsModel::endResetTournament); } void PreferredDrawSystemsModel::beginResetTournament() { beginResetModel(); while (!mConnections.empty()) { disconnect(mConnections.top()); mConnections.pop(); } } void PreferredDrawSystemsModel::endResetTournament() { auto &tournament = mStoreManager.getTournament(); mConnections.push(connect(&tournament, &QTournamentStore::preferencesChanged, this, &PreferredDrawSystemsModel::changePreferences)); mPreferredDrawSystems = tournament.getPreferences().getPreferredDrawSystems(); endResetModel(); } void PreferredDrawSystemsModel::changePreferences() { beginResetModel(); auto &tournament = mStoreManager.getTournament(); mPreferredDrawSystems = tournament.getPreferences().getPreferredDrawSystems(); endResetModel(); } int PreferredDrawSystemsModel::rowCount(const QModelIndex &parent) const { return mPreferredDrawSystems.size(); } int PreferredDrawSystemsModel::columnCount(const QModelIndex &parent) const { return COLUMN_COUNT; } QVariant PreferredDrawSystemsModel::data(const QModelIndex &index, int role) const { auto preference = mPreferredDrawSystems[index.row()]; if (role == Qt::DisplayRole) { if (index.column() == 0) return static_cast<int>(preference.playerLowerLimit); if (index.column() == 1) { const auto &drawSystem = DrawSystem::getDrawSystem(preference.drawSystem); return QString::fromStdString(drawSystem->getName()); } } if (role == Qt::EditRole) { if (index.column() == 0) return static_cast<int>(preference.playerLowerLimit); if (index.column() == 1) { return QVariant::fromValue(preference.drawSystem); } } return QVariant(); } QVariant PreferredDrawSystemsModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole) { if (orientation == Qt::Horizontal) { switch (section) { case 0: return QString(tr("Lower Player Limit")); case 1: return QString(tr("Draw System")); } } } return QVariant(); } bool PreferredDrawSystemsModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role == Qt::EditRole) { // if (!QAbstractItemModel::checkIndex(index)) // return false; if (index.column() == 0) { std::size_t limit = value.toInt(); mStoreManager.dispatch(std::make_unique<ChangeDrawSystemPreferenceLimitAction>(index.row(), limit)); } else if (index.column() == 1) { DrawSystemIdentifier identifier = value.value<DrawSystemIdentifier>(); mStoreManager.dispatch(std::make_unique<ChangeDrawSystemPreferenceIdentifierAction>(index.row(), identifier)); } return true; } return false; } Qt::ItemFlags PreferredDrawSystemsModel::flags(const QModelIndex &index) const { auto flags = QAbstractTableModel::flags(index); if (!(index.row() == 0 && index.column() == 0)) flags |= Qt::ItemIsEditable; return flags; }
34.159292
136
0.683161
svendcsvendsen
19a0ad22386a642f275d2162f242effabe52ccd4
6,348
hpp
C++
emulador/src/common/nullpo.hpp
dattebayoonline/Dattebayo
09526566f63e76b9a5ce80f1f4e3d1918e26cf01
[ "DOC", "OLDAP-2.2.1" ]
1
2022-03-24T17:24:12.000Z
2022-03-24T17:24:12.000Z
emulador/src/common/nullpo.hpp
eluvju/Dattebayo
cc0fc92d8827f4890a8595bc3be0a71ef98767c1
[ "DOC" ]
null
null
null
emulador/src/common/nullpo.hpp
eluvju/Dattebayo
cc0fc92d8827f4890a8595bc3be0a71ef98767c1
[ "DOC" ]
null
null
null
// Copyright (c) rAthena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder #ifndef NULLPO_HPP #define NULLPO_HPP #include "cbasetypes.hpp" #define NLP_MARK __FILE__, __LINE__, __func__ // enabled by default on debug builds #if defined(DEBUG) && !defined(NULLPO_CHECK) #define NULLPO_CHECK #endif #if defined(NULLPO_CHECK) /** * Macros used to check for NULL pointer and output that information. */ /** * Return 0 if pointer is not found. * @param t: Pointer to check * @return 0 if t is NULL */ #define nullpo_ret(t) \ if (nullpo_chk(NLP_MARK, (void *)(t))) {return(0);} /** * Return void if pointer is not found. * @param t: Pointer to check * @return void if t is NULL */ #define nullpo_retv(t) \ if (nullpo_chk(NLP_MARK, (void *)(t))) {return;} /** * Return the given value if pointer is not found. * @param ret: Value to return * @param t: Pointer to check * @return ret value */ #define nullpo_retr(ret, t) \ if (nullpo_chk(NLP_MARK, (void *)(t))) {return(ret);} /** * Break out of the loop/switch if pointer is not found. * @param t: Pointer to check */ #define nullpo_retb(t) \ if (nullpo_chk(NLP_MARK, (void *)(t))) {break;} // Different C compilers uses different argument formats #if __STDC_VERSION__ >= 199901L || defined(_MSC_VER) /* C99 standard */ /** * Return 0 and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description * @return 0 if t is NULL */ #define nullpo_ret_f(t, fmt, ...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return(0);} /** * Return void and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description * @return void if t is NULL */ #define nullpo_retv_f(t, fmt, ...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return;} /** * Return the given value and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description * @return ret value */ #define nullpo_retr_f(ret, t, fmt, ...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return(ret);} /** * Break out of the loop/switch and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description */ #define nullpo_retb_f(t, fmt, ...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {break;} #elif __GNUC__ >= 2 /* For GCC */ /** * Return 0 and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description * @return 0 if t is NULL */ #define nullpo_ret_f(t, fmt, args...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return(0);} /** * Return void and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description * @return void if t is NULL */ #define nullpo_retv_f(t, fmt, args...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return;} /** * Return the given value and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description * @return ret value */ #define nullpo_retr_f(ret, t, fmt, args...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return(ret);} /** * Break out of the loop/switch and display additional information if pointer is not found. * @param t: Pointer to check * @param fmt: Pass to vprintf, Format and arguments such as description */ #define nullpo_retb_f(t, fmt, args...) \ if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {break;} #else /* Otherwise... */ #endif #else /* NULLPO_CHECK */ /* No Nullpo check */ // if((t)){;} // Do nothing if Nullpo check is disabled #define nullpo_ret(t) (void)(t) #define nullpo_retv(t) (void)(t) #define nullpo_retr(ret, t) (void)(t) #define nullpo_retb(t) (void)(t) // Different C compilers uses different argument formats #if __STDC_VERSION__ >= 199901L || defined(_MSC_VER) /* C99 standard */ #define nullpo_ret_f(t, fmt, ...) (void)(t) #define nullpo_retv_f(t, fmt, ...) (void)(t) #define nullpo_retr_f(ret, t, fmt, ...) (void)(t) #define nullpo_retb_f(t, fmt, ...) (void)(t) #elif __GNUC__ >= 2 /* For GCC */ #define nullpo_ret_f(t, fmt, args...) (void)(t) #define nullpo_retv_f(t, fmt, args...) (void)(t) #define nullpo_retr_f(ret, t, fmt, args...) (void)(t) #define nullpo_retb_f(t, fmt, args...) (void)(t) #else /* Otherwise... orz */ #endif #endif /* NULLPO_CHECK */ /** * Check for NULL pointer and output information. * @param file: __FILE__ * @param line: __LINE__ * @param func: __func__ (name of the function) [NLP_MARK] * @param target: Target to check * @return 0 on success or 1 on NULL */ int nullpo_chk(const char *file, int line, const char *func, const void *target); /** * Check for NULL pointer and output detailed information. * @param file: __FILE__ * @param line: __LINE__ * @param func: __func__ (name of the function) [NLP_MARK] * @param target: Target to check * @param fmt: Passed to vprintf * @return 0 on success or 1 on NULL */ int nullpo_chk_f(const char *file, int line, const char *func, const void *target, const char *fmt, ...) __attribute__((format(printf,5,6))); /** * Display information of the code that cause this function to trigger. * @param file: __FILE__ * @param line: __LINE__ * @param func: __func__ (name of the function) [NLP_MARK] * @param target: Target to check */ void nullpo_info(const char *file, int line, const char *func); /** * Check for NULL pointer and output detailed information. * @param file: __FILE__ * @param line: __LINE__ * @param func: __func__ (name of the function) [NLP_MARK] * @param target: Target to check * @param fmt: Passed to vprintf */ void nullpo_info_f(const char *file, int line, const char *func, const char *fmt, ...) __attribute__((format(printf,4,5))); #endif /* NULLPO_HPP */
30.085308
91
0.677221
dattebayoonline
19a133af76a8be3020aee1042c49c8cf79eb7377
1,910
cpp
C++
SDL2_Wrapper/Scene.cpp
andywm/Scenegraph-Demo
5d8a2904d36f4532aa4a0299b6d3e7a4812cae6d
[ "MIT" ]
null
null
null
SDL2_Wrapper/Scene.cpp
andywm/Scenegraph-Demo
5d8a2904d36f4532aa4a0299b6d3e7a4812cae6d
[ "MIT" ]
null
null
null
SDL2_Wrapper/Scene.cpp
andywm/Scenegraph-Demo
5d8a2904d36f4532aa4a0299b6d3e7a4812cae6d
[ "MIT" ]
null
null
null
#include <memory> #include <glm\glm.hpp> #include "Scene.h" namespace Render { namespace Scene { Scene::Scene() : mBackground(glm::vec4(0.5f,0.5f,0.5f, 1.0f)), mSceneRoot(new Graph::Group), mActiveCamera(0), mSpecialRenderMode(false), mShowStatistics(true) {} std::shared_ptr<Environment::Object::Camera> Scene::makeCamera(const glm::vec3 & pos, const glm::vec2 & orient, Environment::Object::Camera::MODE mode, int lin, int rot) { mCameras.push_back( std::unique_ptr<Environment::Object::Camera>( new Environment::Object::Camera( pos, glm::vec3(orient, 0.0f), mode, lin, rot))); return mCameras[mCameras.size() - 1]; } void Scene::activateCamera(const unsigned int index) { if (index < mCameras.size()) { for (const auto & cam : mCameras) { cam->deactivate(); } mActiveCamera = index; mCameras[mActiveCamera]->activate(); } } void Scene::submitToScene(const std::shared_ptr<Graph::SGBase> node) { mSceneRoot->add(node, mSceneRoot); } void Scene::generateStaticSG() { mSGStatic = std::unique_ptr<Graph::Linearise> (new Graph::Linearise(mSceneRoot)); } void Scene::setAspect(const glm::vec2 & aspect) { if (!mCameras.empty()) { for (const auto & c : mCameras) { c->aspectRatio(static_cast<float>(aspect.x) / static_cast<float>(aspect.y)); } } } /* warning, orphans all elements in the scenegraph, all external references to those objects must also be freed for the memory to be released. */ void Scene::destroySceneGraph() { const Graph::Orphanise orphan; mSceneRoot->accept(&orphan); mSGStatic = nullptr; } void Scene::inject(const std::shared_ptr<Environment::Object::Base> obj) { const auto element = mCameras[mActiveCamera]->sgRepresentation(); obj->injectIntoCS(element); } } }
21.222222
69
0.64555
andywm
19a72e251ec8eb364caa14debb9fbbcd17979621
2,155
cpp
C++
Capilto_2/client_proj/client/source/main.cpp
dedogames/Curso_de_BoostAsio
3e9d9eb14136ef2f07c2d99ca476211c280f3f0a
[ "MIT" ]
2
2020-09-15T18:56:27.000Z
2021-01-06T23:45:20.000Z
Capilto_2/client_proj/client/source/main.cpp
dedogames/Curso_de_BoostAsio
3e9d9eb14136ef2f07c2d99ca476211c280f3f0a
[ "MIT" ]
null
null
null
Capilto_2/client_proj/client/source/main.cpp
dedogames/Curso_de_BoostAsio
3e9d9eb14136ef2f07c2d99ca476211c280f3f0a
[ "MIT" ]
null
null
null
// // main.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // Developer: Gelson Rodrigues // geoldery@gmail.com // // Very simple client // // Basically , this app connects to a server // and print on screen one trade #include <boost/asio.hpp> #include <iostream> using namespace boost; std::string name; class Server { public: Server(const std::string& raw_ip_address, unsigned short port_num) : m_ep(asio::ip::address::from_string(raw_ip_address), port_num), m_sock(m_ios) { //open socket based on endpoint m_sock.open(m_ep.protocol()); } void connect() { //connect on server m_sock.connect(m_ep); } void close() { //kills connection to the server m_sock.shutdown( boost::asio::ip::tcp::socket::shutdown_both); m_sock.close(); } void sendRequest(const std::string& request) { //Send request asio::write(m_sock, asio::buffer(request)); } std::string process_resposne() { // Read buffer asio::streambuf buf; asio::read_until(m_sock, buf, '\n'); std::istream input(&buf); // put on string std::string response; std::getline(input, response); return response; } private: //main I/0 manager asio::io_service m_ios; // server address asio::ip::tcp::endpoint m_ep; //socket to server asio::ip::tcp::socket m_sock; }; int main(int argc, char** argv) { // Check command line arguments. if (argc < 3) { std::cerr << "Usage: <host> <port> <name>\n" << "Example:\n" << " 127.0.0.1 8544 gelson\n"; return EXIT_FAILURE; } const std::string raw_ip_address = argv[1]; const unsigned short port_num = std::stod(argv[2]); name = argv[3]; try { Server server(raw_ip_address, port_num); // Sync connect. server.connect(); std::cout << "Sending request to the server... " << std::endl; server.sendRequest(name); std::string response = server.process_resposne(); std::cout << "Response received: " << response << std::endl; // Close the connection and free resources. server.close(); } catch (system::system_error &e) { std::cout << "Error occured! Error code = " << e.code() << ". Message: " << e.what(); return e.code().value(); } return 0; }
18.903509
87
0.642227
dedogames
19aaaf0ece5c8cb08b45bf48b8852e0db203c6c0
3,936
hpp
C++
packages/utility/core/src/Utility_ComparisonTraitsHelpers.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/core/src/Utility_ComparisonTraitsHelpers.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/core/src/Utility_ComparisonTraitsHelpers.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file Utility_ComparisonTraitsHelpers.hpp //! \author Alex Robinson //! \brief The comparison traits helper methods/classes declarations //! //---------------------------------------------------------------------------// #ifndef UTILITY_COMPARISON_TRAITS_HELPERS_HPP #define UTILITY_COMPARISON_TRAITS_HELPERS_HPP // Std Lib Includes #include <string> // FRENSIE Includes #include "Utility_ComparisonPolicy.hpp" #include "Utility_QuantityTraits.hpp" namespace Utility{ /*! Check the comparison result and add "passed" or "failed!" to the log * \ingroup comparison_traits */ void reportComparisonPassFail( const bool result, std::ostream& log ); namespace Details{ /*! Increment the right shift * \ingroup comparison_traits */ constexpr size_t incrementRightShift( const size_t right_shift ) { return right_shift+2; } /*! The zero helper * \ingroup comparison_traits */ template<typename T, typename Enabled = void> struct ZeroHelper; /*! STL compliant container zero helper implementation * * A partial specialization of ZeroHelper must be made for the container type * and it should inherit from this struct. * \ingroup comparison_traits */ template<typename STLCompliantContainer> struct STLCompliantContainerZeroHelper { //! Return the zero object static STLCompliantContainer zero( const STLCompliantContainer& mirror_obj ); }; /*! Create the zero object * \ingroup comparison_traits */ template<typename T> T zero( const T& mirror_obj ); /*! Default implementation of the createComparisonHeader method * \ingroup comparison_traits */ template<typename ComparisonPolicy, size_t RightShift, typename T, typename ExtraDataType> std::string createComparisonHeaderImpl( const T& left_value, const std::string& left_name, const bool log_left_name, const T& right_value, const std::string& right_name, const bool log_right_name, const std::string& name_suffix, const ExtraDataType& extra_data ); /*! Default implementation of the compare method * \ingroup comparison_traits */ template<typename ComparisonPolicy, size_t RightShift, typename T, typename ExtraDataType, typename ComparisonHeaderGenerator = decltype(&Utility::Details::createComparisonHeaderImpl<ComparisonPolicy,RightShift,T,ExtraDataType>)> bool compareImpl( const T& left_value, const std::string& left_name, const bool log_left_name, const T& right_value, const std::string& right_name, const bool log_right_name, const std::string& name_suffix, std::ostream& log, const bool log_comparison_details, const ExtraDataType& extra_data, const ComparisonHeaderGenerator header_generator = &Utility::Details::createComparisonHeaderImpl<ComparisonPolicy,RightShift,T,ExtraDataType> ); } // end Details namespace } // end Utility namespace //---------------------------------------------------------------------------// // Template Includes //---------------------------------------------------------------------------// #include "Utility_ComparisonTraitsHelpers_def.hpp" //---------------------------------------------------------------------------// #endif // end UTILITY_COMPARISON_TRAITS_HELPERS_HPP //---------------------------------------------------------------------------// // end Utility_ComparisonTraitsHelpers.hpp //---------------------------------------------------------------------------//
34.831858
147
0.573933
bam241
19acbd99e072306c1706abf3043d4c88e4415f1f
1,080
cpp
C++
gfx/gfx_colour_effect.cpp
astrellon/Rouge
088f55b331284238e807e0562b9cbbed6428c20f
[ "MIT" ]
null
null
null
gfx/gfx_colour_effect.cpp
astrellon/Rouge
088f55b331284238e807e0562b9cbbed6428c20f
[ "MIT" ]
null
null
null
gfx/gfx_colour_effect.cpp
astrellon/Rouge
088f55b331284238e807e0562b9cbbed6428c20f
[ "MIT" ]
null
null
null
#include "gfx_colour_effect.h" #include "gfx_renderable.h" namespace am { namespace gfx { ColourEffect::ColourEffect() : Effect() { } ColourEffect::ColourEffect(float effectLength, const util::Colour &startColour, const util::Colour &endColour) : Effect(effectLength), mStartColour(startColour), mEndColour(endColour) { } ColourEffect::~ColourEffect() { } void ColourEffect::setStartColour(const util::Colour &start) { mStartColour = start; } util::Colour ColourEffect::getStartColour() const { return mStartColour; } void ColourEffect::setEndColour(const util::Colour &end) { mEndColour = end; } util::Colour ColourEffect::getEndColour() const { return mEndColour; } util::Colour ColourEffect::getLerpedColour() const { return mLerped; } void ColourEffect::update(float dt) { Effect::update(dt); mLerped = mStartColour.lerp(mEndColour, getPercent()); } void ColourEffect::applyToTarget(Renderable *target) { if (target && target->getGfxComponent()) { target->getGfxComponent()->setColour(mLerped); } } } }
17.419355
113
0.710185
astrellon
30ad224bb6533eed14a0295a15c4805d39723d48
212
cpp
C++
Codechef add two nos.cpp
zoya-0509/Practice-codes
4d71b1b004f309025c215e55a504c7817b00e8c9
[ "MIT" ]
null
null
null
Codechef add two nos.cpp
zoya-0509/Practice-codes
4d71b1b004f309025c215e55a504c7817b00e8c9
[ "MIT" ]
null
null
null
Codechef add two nos.cpp
zoya-0509/Practice-codes
4d71b1b004f309025c215e55a504c7817b00e8c9
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { long long int T,A,B; cin>>T; while (T--){ cin>>A; cin>>B; cout<<A+B<<"\n"; } return 0; }
16.307692
28
0.40566
zoya-0509
30b4503b472fd0207c4bb53fa64bdc0fdbaa700b
4,602
cpp
C++
sta-src/Astro-Core/propagateTHREEbody.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
6
2018-09-05T12:41:59.000Z
2021-07-01T05:34:23.000Z
sta-src/Astro-Core/propagateTHREEbody.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-02-07T19:09:21.000Z
2015-08-14T03:15:42.000Z
sta-src/Astro-Core/propagateTHREEbody.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-03-25T15:50:31.000Z
2017-12-06T12:16:47.000Z
/* This program is free software; you can redistribute it and/or modify it under the terms of the European Union Public Licence - EUPL v.1.1 as published by the European Commission. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1 for more details. You should have received a copy of the European Union Public Licence - EUPL v.1.1 along with this program. Further information about the European Union Public Licence - EUPL v.1.1 can also be found on the world wide web at http://ec.europa.eu/idabc/eupl */ /* ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ---- */ /* ------------------ Author: Valentino Zuccarelli ------------------------------------------------- ------------------ E-mail: (Valentino.Zuccarelli@gmail.com) ---------------------------- */ #include "propagateTHREEbody.h" #include <cmath> #include "EODE/eode.h" #include <iomanip> #include <QtDebug> using namespace std; extern double Grav_Param; void threebody_EOM (double time , double sol[], double par[], double deriv[]) { double r1, r2; radius (Grav_Param, sol[3], sol[4], sol[5], r1, r2); //function call for radius //deriv[0] = (x2p) sol[0] = xp //deriv[1] = (y2p) sol[1] = yp //deriv[2] = (z2p) sol[2] = zp //deriv[3] = (xp) sol[3] = x //deriv[4] = (yp) sol[4] = y //deriv[5] = (zp) sol[5] = zp //equations of motion: CR3BP deriv[0]=2*sol[1]+sol[3]-(1-Grav_Param)*(sol[3]+Grav_Param)/(pow(r1,3))+ Grav_Param*(1-Grav_Param-sol[3])/(pow(r2,3)); deriv[1]=-2*sol[0]+sol[4]-(1-Grav_Param)*sol[4]/(pow(r1,3))-Grav_Param*sol[4]/(pow(r2,3)); deriv[2]=-(1-Grav_Param)*sol[5]/(pow(r1,3))-Grav_Param*sol[5]/(pow(r2,3)); deriv[3]=sol[0]; deriv[4]=sol[1]; deriv[5]=sol[2]; } void halorbit_EOM (double time , double sol[], double par[], double deriv[]) { double r1, r2; radius (Grav_Param, sol[3], sol[4], sol[5], r1, r2); //function call for radius //deriv[0] = (x2p) sol[0] = xp //deriv[1] = (y2p) sol[1] = yp //deriv[2] = (z2p) sol[2] = zp //deriv[3] = (xp) sol[3] = x //deriv[4] = (yp) sol[4] = y //deriv[5] = (zp) sol[5] = z //deriv[6-41]=STMp sol[6-41]=STM //equations of motion: CR3BP deriv[0]=2*sol[1]+sol[3]-(1-Grav_Param)*(sol[3]+Grav_Param)/(pow(r1,3))+ Grav_Param*(1-Grav_Param-sol[3])/(pow(r2,3)); deriv[1]=-2*sol[0]+sol[4]-(1-Grav_Param)*sol[4]/(pow(r1,3))-Grav_Param*sol[4]/(pow(r2,3)); deriv[2]=-(1-Grav_Param)*sol[5]/(pow(r1,3))-Grav_Param*sol[5]/(pow(r2,3)); deriv[3]=sol[0]; deriv[4]=sol[1]; deriv[5]=sol[2]; double F[35]; F[18]=1-(1-Grav_Param)/pow(r1,3)+3*(1-Grav_Param)*pow(sol[3]+Grav_Param,2)/pow(r1,5)-Grav_Param/pow(r2,3)+3*Grav_Param*pow(sol[3]+Grav_Param-1,2)/pow(r2,5); F[25]=1-(1-Grav_Param)/pow(r1,3)+3*(1-Grav_Param)*pow(sol[4],2)/pow(r1,5)-Grav_Param/pow(r2,3)+3*Grav_Param*pow(sol[4],2)/pow(r2,5); F[32]=(-1+Grav_Param)/pow(r1,3)-Grav_Param/pow(r2,3)+3*pow(sol[5],2)*((1-Grav_Param)/pow(r1,5)+Grav_Param/pow(r2,5)); F[19]=F[24]=3*sol[4]*((1-Grav_Param)*(sol[3]+Grav_Param)/pow(r1,5)+Grav_Param*(sol[3]+Grav_Param-1)/pow(r2,5)); F[20]=F[30]=3*sol[5]*((1-Grav_Param)*(sol[3]+Grav_Param)/pow(r1,5)+Grav_Param*(sol[3]+Grav_Param-1)/pow(r2,5)); F[26]=F[31]=3*sol[4]*sol[5]*((1-Grav_Param)/pow(r1,5)+Grav_Param/pow(r2,5)); F[3]=F[10]=F[17]=1; F[22]=2; F[27]=-2; F[0]=F[1]=F[2]=F[4]=F[5]=F[9]=F[6]=F[7]=F[8]=F[12]=F[13]=F[14]=F[11]=F[15]=F[16]= F[21]=F[23]=F[28]=F[29]=F[33]=F[34]=F[35]=0; int l, j, q; double der[42]; for (l=0; l<36; l++) {q=(l+6)/6; //number of line der[l+6]=F[(q-1)*6]*sol[(l+6)%6+6]; for (j=1; j<6; j++) {der[l+6]=der[l+6]+F[(q-1)*6+j]*sol[(l+6)%6+(j+1)*6];} deriv[l+6]=der[l+6];} } void radius (double mi, double x, double y, double z, double &R1, double &R2) { R1 = sqrt(pow(x+mi,2)+pow(y,2)+pow(z,2)); //(distance of mass 3 from mass 1) R2 = sqrt(pow(x-1+mi,2)+pow(y,2)+pow(z,2)); //(distance of mass 3 from mass 2) }
38.672269
165
0.538896
hoehnp
30b501048b7b0cd47fa3324c0d6a7690482e8eda
1,172
cpp
C++
Simplify Path.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
2
2020-06-25T12:46:13.000Z
2021-07-06T06:34:33.000Z
Simplify Path.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
Simplify Path.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
class Solution { public: string simplifyPath(string path) { int l=path.length(); stack<string> vec; string res; res.append("/"); for(int i=0;i<l;i++){ string str; while(path[i]=='/'){ i++; } while(i<path.length() && path[i]!='/'){ str+=path[i]; i++; } if(str.compare("..")==0){ if(!vec.empty()){ vec.pop(); } } else if(str.compare(".")==0){ continue; } else if(str.length()!=0){ vec.push(str); } } stack<string> st; while(!vec.empty()){ st.push(vec.top()); vec.pop(); } while(!st.empty()){ if(st.size()!=1){ res.append(st.top()+"/"); } else{ res.append(st.top()); } st.pop(); } return res; } };
22.538462
51
0.294369
durgirajesh
30be0ac22e9980e75f716c650f65ac75a19b8e74
7,223
cpp
C++
lib/circular_buffer.cpp
guruofquality/gras
a93956bfc9884f9a1c53a16e12cd7e7cd86584c4
[ "BSL-1.0" ]
9
2015-07-24T15:10:14.000Z
2021-11-08T13:18:20.000Z
lib/circular_buffer.cpp
guruofquality/gras
a93956bfc9884f9a1c53a16e12cd7e7cd86584c4
[ "BSL-1.0" ]
3
2015-02-02T01:57:26.000Z
2018-07-20T04:52:09.000Z
lib/circular_buffer.cpp
guruofquality/gras
a93956bfc9884f9a1c53a16e12cd7e7cd86584c4
[ "BSL-1.0" ]
4
2015-01-12T23:12:49.000Z
2021-09-23T18:10:58.000Z
// Copyright (C) by Josh Blum. See LICENSE.txt for licensing information. #include <gras/buffer_queue.hpp> #include <gras_impl/debug.hpp> #include <boost/format.hpp> #include <boost/bind.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/anonymous_shared_memory.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/lexical_cast.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <ctime> using namespace gras; namespace ipc = boost::interprocess; static boost::mutex alloc_mutex; /*! * This routine generates an incredibly unique name for the allocation. * * Because we are using boost IPC, and it expects that we share the memory; * IPC allocation requires a unique name to share amongst the processes. * Since we are not actually using IPC, the sharing aspect isnt very useful, * but we still need a unique name for the shared memory allocation anyway. * (I would like if a empty string would suffice as an anonymous allocation) */ static std::string omg_so_unique(void) { const std::string tid = boost::lexical_cast<std::string>(boost::this_thread::get_id()); static size_t count = 0; return boost::str(boost::format("shmem-%s-%u-%u") % tid % count++ % clock()); } //! Round a number (length or address) to an IPC boundary static size_t round_up_to_ipc_page(const size_t bytes) { const size_t chunk = ipc::mapped_region::get_page_size(); return chunk*((bytes + chunk - 1)/chunk); } /*! * OK, we need a chunk of virtual memory that can be mapped. * But we cant actually be holding exclusive access to that memory * until it it mapped... This is naturally a race condition. */ static void *probably_get_vmem(const size_t length) { void *addr = NULL; /* #if defined(linux) || defined(__linux) || defined(__linux__) addr = mmap(NULL, length, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); munmap(addr, length); return addr; #endif //*/ const std::string shm_name = omg_so_unique(); //std::cout << "make shmem 2x\n" << std::endl; ipc::shared_memory_object shm_obj_2x( ipc::create_only, //only create shm_name.c_str(), //name ipc::read_write //read-write mode ); //std::cout << "truncate 2x\n" << std::endl; shm_obj_2x.truncate(length); { //std::cout << "map region 0\n" << std::endl; ipc::mapped_region region0( shm_obj_2x, //Memory-mappable object ipc::read_write, //Access mode 0, //Offset from the beginning of shm length //Length of the region ); //std::cout << "region0.get_address() " << size_t(region0.get_address()) << std::endl; addr = region0.get_address(); } ipc::shared_memory_object::remove(shm_name.c_str()); return addr; } struct CircularBuffer { CircularBuffer(const size_t); ~CircularBuffer(void) { ipc::shared_memory_object::remove(shm_name.c_str()); } char *buff_addr; const size_t actual_length; std::string shm_name; ipc::shared_memory_object shm_obj; ipc::mapped_region region1; ipc::mapped_region region2; }; CircularBuffer::CircularBuffer(const size_t num_bytes): buff_addr(NULL), actual_length(round_up_to_ipc_page(num_bytes)) { //////////////////////////////////////////////////////////////// // Step 0) Find an address that can be mapped across 2x length: //////////////////////////////////////////////////////////////// buff_addr = (char *)probably_get_vmem(actual_length*2); //std::cout << "reserve addr " << std::hex << size_t(buff_addr) << std::dec << std::endl; //////////////////////////////////////////////////////////////// // Step 1) Allocate a chunk of physical memory of length bytes //////////////////////////////////////////////////////////////// //std::cout << "make shmem\n" << std::endl; shm_name = omg_so_unique(); shm_obj = ipc::shared_memory_object( ipc::create_only, //only create shm_name.c_str(), //name ipc::read_write //read-write mode ); //std::cout << "truncate\n" << std::endl; shm_obj.truncate(actual_length); //////////////////////////////////////////////////////////////// //Step 2) Remap region1 of the virtual memory space //////////////////////////////////////////////////////////////// //std::cout << "map region 1\n" << std::endl; region1 = ipc::mapped_region( shm_obj, //Memory-mappable object ipc::read_write, //Access mode 0, //Offset from the beginning of shm actual_length, //Length of the region buff_addr ); //std::cout << "region1.get_address() " << size_t(region1.get_address()) << std::endl; //////////////////////////////////////////////////////////////// //Step 3) Remap region2 of the virtual memory space //////////////////////////////////////////////////////////////// //std::cout << "map region 2\n" << std::endl; region2 = ipc::mapped_region( shm_obj, //Memory-mappable object ipc::read_write, //Access mode 0, //Offset from the beginning of shm actual_length, //Length of the region buff_addr + actual_length ); //std::cout << "region2.get_address() " << size_t(region2.get_address()) << std::endl; //std::cout << "diff " << (long(region2.get_address()) - long(region1.get_address())) << std::endl; //////////////////////////////////////////////////////////////// //4) Self memory test //////////////////////////////////////////////////////////////// boost::uint32_t *mem = (boost::uint32_t*)buff_addr; for (size_t i = 0; i < actual_length/sizeof(*mem); i++) { const boost::uint32_t num = std::rand(); mem[i] = num; ASSERT(mem[i+actual_length/sizeof(*mem)] == num); } //////////////////////////////////////////////////////////////// //5) Zero out the memory for good measure //////////////////////////////////////////////////////////////// std::memset(buff_addr, 0, actual_length); } static void circular_buffer_delete(SBuffer &buff, CircularBuffer *circ_buff) { boost::mutex::scoped_lock lock(alloc_mutex); delete circ_buff; } SBuffer make_circular_buffer(const size_t num_bytes) { boost::mutex::scoped_lock lock(alloc_mutex); CircularBuffer *circ_buff = NULL; size_t trial_count = 0; while (circ_buff == NULL) { trial_count++; try { circ_buff = new CircularBuffer(num_bytes); } catch(const boost::interprocess::interprocess_exception &ex) { std::cerr << boost::format( "GRAS: make_circular_buffer threw ipc exception on attempt %u\n%s" ) % trial_count % ex.what() << std::endl; if (trial_count == 3) throw ex; } catch(...) { throw; } } SBufferDeleter deleter = boost::bind(&circular_buffer_delete, _1, circ_buff); SBufferConfig config; config.memory = circ_buff->buff_addr; config.length = circ_buff->actual_length; config.deleter = deleter; return SBuffer(config); }
34.232227
103
0.574969
guruofquality
30c54f0e0d93780f939d237b0eeb7a2547864237
1,710
cpp
C++
src/kriti/render/TextureContext.cpp
etherealvisage/kriti
6397c4d20331d9f5ce07460df08bbac9653ffa8b
[ "BSD-3-Clause" ]
2
2015-10-05T19:33:19.000Z
2015-12-08T08:39:17.000Z
src/kriti/render/TextureContext.cpp
etherealvisage/kriti
6397c4d20331d9f5ce07460df08bbac9653ffa8b
[ "BSD-3-Clause" ]
1
2017-04-30T16:26:08.000Z
2017-05-01T03:00:42.000Z
src/kriti/render/TextureContext.cpp
etherealvisage/kriti
6397c4d20331d9f5ce07460df08bbac9653ffa8b
[ "BSD-3-Clause" ]
null
null
null
#include "../ogl.h" #include "TextureContext.h" #include "Texture.h" #include "ErrorTracker.h" #include "../MessageSystem.h" namespace Kriti { namespace Render { TextureContext::TextureContext() { ErrorTracker::trackFrom("Texture context constructor (before all)"); GLint count; gl::GetIntegerv(gl::MAX_COMBINED_TEXTURE_IMAGE_UNITS, &count); ErrorTracker::trackFrom( "Texture context constructor (after get unit count)"); m_bindings.assign(count, std::make_pair(-1, boost::shared_ptr<Texture>())); m_round = 0; m_lastUnit = -1; } void TextureContext::clearBindings() { m_lastUnit = -1; m_bindings.assign(m_bindings.size(), std::make_pair(-1, boost::shared_ptr<Texture>())); } int TextureContext::bind(boost::shared_ptr<Texture> texture) { // first check if it's already bound... for(int i = 0; i < m_bindings.size(); i ++) { if(m_bindings[i].second == texture) { m_bindings[i].first = m_round; return i; } } // find next available to bind on for(int i = 1; i < m_bindings.size(); i ++) { int in = (m_lastUnit+i)%m_bindings.size(); if(m_bindings[in].first >= m_round) continue; //Message3(Render, Debug, "Selecting texture unit offset " << i); m_bindings[in] = std::make_pair(m_round, texture); texture->bindToUnit(in); m_lastUnit = in; //Message3(Render, Debug, "Seting last unit to " << m_lastUnit); return in; } Message3(Render, Error, "Exhausted the supply of texture units!"); // in this case -- which shouldn't happen -- just use texture 0. return 0; } } // namespace Render } // namespace Kriti
27.142857
79
0.629825
etherealvisage
30c7a67f6c1a892da13fe734de6313beb2f54544
10,314
cpp
C++
src/uFldFlagManagerAgent/FlagManager_Info.cpp
Joe-Doyle/moos-ivp-agent
164d590808bcac6242dd22d1f25aa4248f7d9c2d
[ "MIT" ]
1
2021-11-22T00:20:18.000Z
2021-11-22T00:20:18.000Z
src/uFldFlagManagerAgent/FlagManager_Info.cpp
Joe-Doyle/moos-ivp-agent
164d590808bcac6242dd22d1f25aa4248f7d9c2d
[ "MIT" ]
15
2021-08-09T05:38:26.000Z
2021-11-11T17:16:48.000Z
src/uFldFlagManagerAgent/FlagManager_Info.cpp
Joe-Doyle/moos-ivp-agent
164d590808bcac6242dd22d1f25aa4248f7d9c2d
[ "MIT" ]
3
2021-08-09T23:55:51.000Z
2021-11-11T01:29:37.000Z
/************************************************************/ /* NAME: Mike Benjamin */ /* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */ /* FILE: FlagManager.h */ /* DATE: August 18th, 2015 */ /************************************************************/ #include <cstdlib> #include <iostream> #include "FlagManager_Info.h" #include "ColorParse.h" #include "ReleaseInfo.h" using namespace std; //---------------------------------------------------------------- // Procedure: showSynopsis void showSynopsis() { blk("SYNOPSIS: "); blk("------------------------------------ "); blk(" The uFldFlagManager is a shoreside manager used for marine "); blk(" autonomy competitions where flags are involved. Flags are "); blk(" declared at the outset each with a position and a unique "); blk(" label. Vehicles have the ability to grab a flag by posting a "); blk(" request. The flag may or not be granted, but if granted, then "); blk(" the grabbing vehicle then owns the flag and it cannot be "); blk(" grabbed by other vehicles. "); } //---------------------------------------------------------------- // Procedure: showHelpAndExit void showHelpAndExit() { blk(" "); blu("=============================================================== "); blu("Usage: uFldFlagManager file.moos [OPTIONS] "); blu("=============================================================== "); blk(" "); showSynopsis(); blk(" "); blk("Options: "); mag(" --alias","=<ProcessName> "); blk(" Launch uFldFlagManager with the given process name "); blk(" rather than uFldFlagManager. "); mag(" --example, -e "); blk(" Display example MOOS configuration block. "); mag(" --help, -h "); blk(" Display this help message. "); mag(" --interface, -i "); blk(" Display MOOS publications and subscriptions. "); mag(" --version,-v "); blk(" Display the release version of uFldFlagManager. "); blk(" "); blk("Note: If argv[2] does not otherwise match a known option, "); blk(" then it will be interpreted as a run alias. This is "); blk(" to support pAntler launching conventions. "); blk(" "); exit(0); } //---------------------------------------------------------------- // Procedure: showExampleConfigAndExit void showExampleConfigAndExit() { blk(" "); blu("=============================================================== "); blu("uFldFlagManager Example MOOS Configuration "); blu("=============================================================== "); blk(" "); blk("ProcessConfig = uFldFlagManager "); blk("{ "); blk(" AppTick = 4 "); blk(" CommsTick = 4 "); blk(" "); blk(" default_flag_width = 5 // Default is 5 meters "); blk(" default_flag_type = circle // Default is circle "); blk(" default_flag_range = 10 // Default is 10 meters "); blk(" "); blk(" poly_vertex_size = 1 // Default is 1 "); blk(" poly_edge_size = 1 // Default is 1 "); blk(" poly_veretx_color = 1 // Default is blue "); blk(" poly_edge_color = 1 // Default is grey50 "); blk(" poly_fill_color = 1 // Default is grey90 "); blk(" "); blk(" grabbed_color = white // Default is white "); blk(" ungrabbed_color = red // Default is red "); blk(" "); blk(" flag_follows_vehicle = true // Default is true "); blk(" near_flag_range_buffer = 5 // Default is 2 "); blk(" "); blk(" post_heartbeat = false // Default is true "); blk(" "); blk(" flag = x=60, y=-30, label=one, range=20, width=10 "); blk(" flag = x=60, y=-170, label=two, color=purple, type=diamond "); blk(" "); blk(" grab_post = var=SAY_MOOS, sval={say={$VNAME has $FLAG flag}} "); blk(" lose_post = var=SAY_MOOS, sval={say={$FLAG flag is reset}} "); blk(" near_post = var=SAY_MOOS, sval={file=sounds/shipbell.wav} "); blk(" away_post = var=SAY_MOOS, sval={file=sounds/buzzer.wav} "); blk(" deny_post = var=SAY_MOOS, sval={file=sounds/sf-no-soup.wav} "); blk(" home_post = var=SAY_MOOS, sval={file=sounds/i-am-back.wav} "); blk(" goal_post = var=SAY_MOOS, sval={file=sounds/goaaaal.wav} "); blk("} "); blk(" "); exit(0); } //---------------------------------------------------------------- // Procedure: showInterfaceAndExit void showInterfaceAndExit() { blk(" "); blu("=============================================================== "); blu("uFldFlagManager INTERFACE "); blu("=============================================================== "); blk(" "); showSynopsis(); blk(" "); blk("SUBSCRIPTIONS: "); blk("------------------------------------ "); blk(" NODE_REPORT = NAME=alpha,TYPE=UUV,TIME=1252348077.59, "); blk(" X=51.71,Y=-35.50, LAT=43.824981, "); blk(" LON=-70.329755,SPD=2.0,HDG=118.8, "); blk(" YAW=118.8,DEPTH=4.6,LENGTH=3.8, "); blk(" MODE=MODE@ACTIVE:LOITERING, "); blk(" THRUST_MODE_REVERSE=true "); blk(" NODE_REPORT_LOCAL = NAME=alpha,TYPE=UUV,.... "); blk(" FLAG_RESET = vname=henry "); blk(" FLAG_RESET = label=alpha "); blk(" FLAG_GRAB_REQUEST = vname=henry "); blk(" TAGGED_VEHICLES = henry,gus "); blk(" PMV_CONNECT = 0 (pub by pMarineViewer upon startup) "); blk(" APPCAST_REQ "); blk(" "); blk("PUBLICATIONS: "); blk("------------------------------------ "); blk(" HAS_FLAG_VNAME = true/false "); blk(" HAS_FLAG_ALL = false (upon global reset) "); blk(" UFMG_HEARTBEAT = 12345 "); blk(" VTEAM_FLAG_GRABBED = grabbed=one,grabbed=two "); blk(" FLAG_GRAB_REPORT = grabbed=one,grabbed=two "); blk(" FLAG_GRAB_REPORT = Nothing grabbed - vehicle is tagged "); blk(" VIEW_MARKER = x=60,y=-30,width=2,range=10.00, "); blk(" primary_color=red,secondary_color=black, "); blk(" type=circle,label=one "); blk(" "); blk(" FLAG_SUMMARY = x=50,y=-24,width=3,range=10,primary_color=red, "); blk(" type=circle,owner=evan,label=red # x=-58,y=-71,"); blk(" width=3,range=10,primary_color=blue, "); blk(" type=circle,label=blue "); blk(" "); blk(" User-configured posts via config params: "); blk(" o grab_post "); blk(" o lose_post "); blk(" o near_post "); blk(" o away_post "); blk(" o deny_post "); blk(" o home_post "); blk(" o goal_post "); blk(" "); exit(0); } //---------------------------------------------------------------- // Procedure: showReleaseInfoAndExit void showReleaseInfoAndExit() { showReleaseInfo("uFldFlagManager", "gpl"); exit(0); }
56.983425
74
0.32897
Joe-Doyle
30e39d01885554d0ffddf52b0d4d09b80f58ae06
1,548
cpp
C++
bench/cpp/msp430_mpsoc3d_testbench.cpp
PacoReinaCampo/MPSoC-MSP430
f07e3d20d4f63163e00e56d14e516341aaaec2c3
[ "MIT" ]
1
2020-02-14T00:23:08.000Z
2020-02-14T00:23:08.000Z
bench/cpp/msp430_mpsoc3d_testbench.cpp
PacoReinaCampo/MPSoC-MSP430
f07e3d20d4f63163e00e56d14e516341aaaec2c3
[ "MIT" ]
null
null
null
bench/cpp/msp430_mpsoc3d_testbench.cpp
PacoReinaCampo/MPSoC-MSP430
f07e3d20d4f63163e00e56d14e516341aaaec2c3
[ "MIT" ]
1
2021-08-08T01:07:04.000Z
2021-08-08T01:07:04.000Z
#include "Vmsp430_mpsoc3d_testbench__Syms.h" #include "Vmsp430_mpsoc3d_testbench__Dpi.h" #include <VerilatedToplevel.h> #include <VerilatedControl.h> #include <ctime> #include <cstdlib> using namespace simutilVerilator; VERILATED_TOPLEVEL(msp430_mpsoc3d_testbench, clk, rst) int main(int argc, char *argv[]) { msp430_mpsoc3d_testbench ct("TOP"); VerilatedControl &simctrl = VerilatedControl::instance(); simctrl.init(ct, argc, argv); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[0].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[1].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[2].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[3].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[4].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[5].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[6].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.addMemory("TOP.msp430_mpsoc3d_testbench.u_system.gen_ct[7].u_ct.gen_sram.u_ram.sp_ram.gen_sram_sp_impl.u_impl"); simctrl.setMemoryFuncs(do_readmemh, do_readmemh_file); simctrl.run(); return 0; }
45.529412
124
0.799742
PacoReinaCampo
30e3f3b662760b449570be52a639f02d5bd83b7d
624
cpp
C++
C语言程序设计基础/空心数字梯形.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
63
2021-01-10T02:32:17.000Z
2022-03-30T04:08:38.000Z
C语言程序设计基础/空心数字梯形.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
2
2021-06-09T05:38:58.000Z
2021-12-14T13:53:54.000Z
C语言程序设计基础/空心数字梯形.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
20
2021-01-12T11:49:36.000Z
2022-03-26T11:04:58.000Z
#include<stdio.h> int main() { int c,m,i,j; scanf("%d %d",&c,&m); if(c==1) { printf("%d",m); return 0; }else { for(i=1;i<=c;++i) { for(j=1;j<=i-1;++j) printf(" "); if(i==1) { for(int k=1;k<=(3*c-2+1)/2;++k) printf("%d",(m+k-1)%10); for(int k=(3*c-2)/2;k>=1;--k) printf("%d",(m+k-1)%10); }else if(i==c) { for(int k=1;k<=(c+1)/2;++k) printf("%d",(c+k+m-2)%10); for(int k=c/2;k>=1;--k) printf("%d",(c+m+k-2)%10); }else { printf("%d",(m+i-1)%10); for(int k=1;k<=3*c-2*i-2;++k) printf(" "); printf("%d",(m-1+i)%10); } printf("\n"); } } }
18.909091
35
0.407051
xiabee
30ebf5de6a62c5a444303f0b68ffce01e7ca9262
11,258
cpp
C++
src/core/FrameBuffer.cpp
Guarneri1743/SoftRasterizer
d7a7344e43d91ce575724cc1d121551e6008dc01
[ "MIT" ]
4
2020-12-14T10:58:35.000Z
2020-12-14T16:38:18.000Z
src/core/FrameBuffer.cpp
J-Mat/CPU-Rasterizer
d7a7344e43d91ce575724cc1d121551e6008dc01
[ "MIT" ]
null
null
null
src/core/FrameBuffer.cpp
J-Mat/CPU-Rasterizer
d7a7344e43d91ce575724cc1d121551e6008dc01
[ "MIT" ]
null
null
null
#include "FrameBuffer.hpp" #include <execution> #include <algorithm> #include "ImageUtil.hpp" namespace CpuRasterizer { FrameBuffer::FrameBuffer(size_t w, size_t h, FrameContent flag) : content_flag(flag), width(w), height(h), filtering(Filtering::kBilinear) { clear_color = {0, 0, 0, 0}; resize(w, h); } bool FrameBuffer::perform_stencil_test(stencil_t ref_val, stencil_t read_mask, CompareFunc func, size_t row, size_t col) const { if ((content_flag & FrameContent::kStencil) == FrameContent::kNone) { return false; } bool pass = false; stencil_t stencil; if (stencil_buffer->read(row, col, stencil)) { switch (func) { case CompareFunc::kNever: pass = false; break; case CompareFunc::kAlways: pass = true; break; case CompareFunc::kEqual: pass = (ref_val & read_mask) == (stencil & read_mask); break; case CompareFunc::kGreater: pass = (ref_val & read_mask) > (stencil & read_mask); break; case CompareFunc::kLEqual: pass = (ref_val & read_mask) <= (stencil & read_mask); break; case CompareFunc::kNotEqual: pass = (ref_val & read_mask) != (stencil & read_mask); break; case CompareFunc::kGEqual: pass = (ref_val & read_mask) > (stencil & read_mask); break; case CompareFunc::kLess: pass = (ref_val & read_mask) < (stencil & read_mask); break; } } return pass; } void FrameBuffer::update_stencil_buffer(size_t row, size_t col, PipelineFeature op_pass, StencilOp stencil_pass_op, StencilOp stencil_fail_op, StencilOp stencil_zfail_op, stencil_t ref_val) const { if ((content_flag & FrameContent::kStencil) == FrameContent::kNone) { return; } bool stencil_pass = (op_pass & PipelineFeature::kStencilTest) != PipelineFeature::kNone; bool z_pass = (op_pass & PipelineFeature::kDepthTest) != PipelineFeature::kNone; stencil_t stencil; stencil_buffer->read(row, col, stencil); StencilOp stencil_op; if (stencil_pass) { stencil_op = z_pass ? stencil_pass_op : stencil_zfail_op; } else { stencil_op = stencil_fail_op; } switch (stencil_op) { case StencilOp::kKeep: break; case StencilOp::kZero: stencil_buffer->write(row, col, 0); break; case StencilOp::kReplace: stencil_buffer->write(row, col, ref_val); break; case StencilOp::kIncrement: stencil_buffer->write(row, col, std::clamp((stencil_t)(stencil + 1), (stencil_t)0, (stencil_t)255)); break; case StencilOp::kDecrement: stencil_buffer->write(row, col, std::clamp((stencil_t)(stencil - 1), (stencil_t)0, (stencil_t)255)); break; case StencilOp::kIncrementWrap: stencil_buffer->write(row, col, stencil + 1); break; case StencilOp::kDecrementWrap: stencil_buffer->write(row, col, stencil - 1); break; case StencilOp::kInvert: stencil_buffer->write(row, col, ~stencil); break; } } bool FrameBuffer::perform_depth_test(CompareFunc func, size_t row, size_t col, depth_t z) const { if ((content_flag & FrameContent::kDepth) == FrameContent::kNone) { return false; } depth_t depth; bool pass = false; if (depth_buffer->read(row, col, depth)) { pass = z <= depth; switch (func) { case CompareFunc::kNever: pass = false; break; case CompareFunc::kAlways: pass = true; break; case CompareFunc::kEqual: pass = tinymath::approx(z, depth); break; case CompareFunc::kGreater: pass = z > depth; break; case CompareFunc::kLEqual: pass = z <= depth; break; case CompareFunc::kNotEqual: pass = z != depth; break; case CompareFunc::kGEqual: pass = z >= depth; break; case CompareFunc::kLess: pass = z < depth; break; } } return pass; } // todo: alpha factor tinymath::Color FrameBuffer::blend(const tinymath::Color& src_color, const tinymath::Color& dst_color, BlendFactor src_factor, BlendFactor dst_factor, const BlendFunc& op) { tinymath::Color lhs, rhs; switch (src_factor) { case BlendFactor::kOne: lhs = src_color; break; case BlendFactor::kSrcAlpha: lhs = src_color * src_color.a; break; case BlendFactor::kSrcColor: lhs = src_color * src_color; break; case BlendFactor::kOneMinusSrcAlpha: lhs = src_color * (1.0f - src_color); break; case BlendFactor::kOneMinusSrcColor: lhs = src_color * (1.0f - dst_color); break; case BlendFactor::kDstAlpha: lhs = src_color * dst_color.a; break; case BlendFactor::kDstColor: lhs = src_color * dst_color; break; case BlendFactor::kOneMinusDstAlpha: lhs = src_color * (1.0f - dst_color.a); break; case BlendFactor::kOneMinusDstColor: lhs = src_color * (1.0f - dst_color); break; } switch (dst_factor) { case BlendFactor::kOne: rhs = src_color; break; case BlendFactor::kSrcAlpha: rhs = dst_color * src_color.a; break; case BlendFactor::kSrcColor: rhs = dst_color * src_color; break; case BlendFactor::kOneMinusSrcAlpha: rhs = dst_color * (1.0f - src_color); break; case BlendFactor::kOneMinusSrcColor: rhs = dst_color * (1.0f - dst_color); break; case BlendFactor::kDstAlpha: rhs = dst_color * dst_color.a; break; case BlendFactor::kDstColor: rhs = dst_color * dst_color; break; case BlendFactor::kOneMinusDstAlpha: rhs = dst_color * (1.0f - dst_color.a); break; case BlendFactor::kOneMinusDstColor: rhs = dst_color * (1.0f - dst_color); break; } switch (op) { case BlendFunc::kAdd: return lhs + rhs; case BlendFunc::kSub: return lhs - rhs; } return lhs + rhs; } void FrameBuffer::write_color(size_t row, size_t col, const tinymath::color_rgba& color) { if ((content_flag & FrameContent::kColor) != FrameContent::kNone) { color_buffer->write(row, col, color); } } void FrameBuffer::write_depth(size_t row, size_t col, depth_t depth) { if ((content_flag & FrameContent::kDepth) != FrameContent::kNone) { depth_buffer->write(row, col, depth); } } void FrameBuffer::write_stencil(size_t row, size_t col, stencil_t stencil) { if ((content_flag & FrameContent::kStencil) != FrameContent::kNone) { stencil_buffer->write(row, col, stencil); } } void FrameBuffer::write_coverage(size_t row, size_t col, coverage_t coverage) { if ((content_flag & FrameContent::kCoverage) != FrameContent::kNone) { coverage_buffer->write(row, col, coverage); } } bool FrameBuffer::read_color(size_t row, size_t col, tinymath::color_rgba & color) { if ((content_flag & FrameContent::kColor) == FrameContent::kNone) { return false; } return color_buffer->read(row, col, color); } bool FrameBuffer::read_depth(size_t row, size_t col, depth_t& depth) { if ((content_flag & FrameContent::kDepth) == FrameContent::kNone) { return false; } return depth_buffer->read(row, col, depth); } bool FrameBuffer::read_stencil(size_t row, size_t col, stencil_t& stencil) { if ((content_flag & FrameContent::kStencil) == FrameContent::kNone) { return false; } return stencil_buffer->read(row, col, stencil); } bool FrameBuffer::read_coverage(size_t row, size_t col, coverage_t& coverage) { if ((content_flag & FrameContent::kCoverage) == FrameContent::kNone) { return false; } return coverage_buffer->read(row, col, coverage); } void FrameBuffer::write_color(float u, float v, const tinymath::color_rgba& color) { if ((content_flag & FrameContent::kColor) != FrameContent::kNone) { color_buffer->write(u, v, color); } } void FrameBuffer::write_depth(float u, float v, depth_t depth) { if ((content_flag & FrameContent::kDepth) != FrameContent::kNone) { depth_buffer->write(u, v, depth); } } void FrameBuffer::write_stencil(float u, float v, stencil_t stencil) { if ((content_flag & FrameContent::kStencil) != FrameContent::kNone) { stencil_buffer->write(u, v, stencil); } } void FrameBuffer::write_coverage(float u, float v, coverage_t coverage) { if ((content_flag & FrameContent::kCoverage) != FrameContent::kNone) { coverage_buffer->write(u, v, coverage); } } bool FrameBuffer::read_color(float u, float v, tinymath::color_rgba& color) { if ((content_flag & FrameContent::kColor) == FrameContent::kNone) { return false; } return color_buffer->read(u, v, color); } bool FrameBuffer::read_depth(float u, float v, depth_t& depth) { if ((content_flag & FrameContent::kDepth) == FrameContent::kNone) { return false; } return depth_buffer->read(u, v, depth); } bool FrameBuffer::read_stencil(float u, float v, stencil_t& stencil) { if ((content_flag & FrameContent::kStencil) == FrameContent::kNone) { return false; } return stencil_buffer->read(u, v, stencil); } bool FrameBuffer::read_coverage(float u, float v, coverage_t& coverage) { if ((content_flag & FrameContent::kCoverage) == FrameContent::kNone) { return false; } return coverage_buffer->read(u, v, coverage); } void FrameBuffer::clear(FrameContent flag) { if ((flag & content_flag & FrameContent::kColor) != FrameContent::kNone) { color_buffer->clear(clear_color); } if ((flag & content_flag & FrameContent::kDepth) != FrameContent::kNone) { depth_buffer->clear(kFarZ); } if ((flag & content_flag & FrameContent::kStencil) != FrameContent::kNone) { stencil_buffer->clear(kDefaultStencil); } if ((flag & content_flag & FrameContent::kCoverage) != FrameContent::kNone) { coverage_buffer->clear((coverage_t)0); } } void FrameBuffer::set_clear_color(const tinymath::color_rgba& color) { clear_color = color; } void FrameBuffer::resize(size_t w, size_t h) { this->width = w; this->height = h; if ((content_flag & FrameContent::kColor) != FrameContent::kNone) { if (color_buffer == nullptr) { color_buffer = std::make_unique<RawBuffer<tinymath::color_rgba>>(w, h); } else { ImageUtil::resize(*color_buffer.get(), w, h, filtering); } } if ((content_flag & FrameContent::kDepth) != FrameContent::kNone) { if (depth_buffer == nullptr) { depth_buffer = std::make_unique<RawBuffer<depth_t>>(w, h); } else { ImageUtil::resize(*depth_buffer.get(), w, h, filtering); } } if ((content_flag & FrameContent::kStencil) != FrameContent::kNone) { if (stencil_buffer == nullptr) { stencil_buffer = std::make_unique<RawBuffer<stencil_t>>(w, h); } else { ImageUtil::resize(*stencil_buffer.get(), w, h, filtering); } } if ((content_flag & FrameContent::kCoverage) != FrameContent::kNone) { if (coverage_buffer == nullptr) { coverage_buffer = std::make_unique<RawBuffer<coverage_t>>(w, h); } else { ImageUtil::resize(*coverage_buffer.get(), w, h, filtering); } } } RawBuffer<tinymath::color_rgba>* FrameBuffer::get_color_raw_buffer() const { return color_buffer.get(); } tinymath::color_rgba* FrameBuffer::get_color_buffer_ptr() const { size_t size; return color_buffer->get_ptr(size); } }
23.454167
103
0.660952
Guarneri1743
30f0dcdef28adf527912edefc649bbf4f583e06f
20,024
cpp
C++
src/Extensions/Classifiers/Barbedo/Barbedo.cpp
berkus/music-cs
099b66cb1285d19955e953f916ec6c12c68f2242
[ "MIT" ]
null
null
null
src/Extensions/Classifiers/Barbedo/Barbedo.cpp
berkus/music-cs
099b66cb1285d19955e953f916ec6c12c68f2242
[ "MIT" ]
null
null
null
src/Extensions/Classifiers/Barbedo/Barbedo.cpp
berkus/music-cs
099b66cb1285d19955e953f916ec6c12c68f2242
[ "MIT" ]
null
null
null
// Copyright (c) 2008-2009 Marcos José Sant'Anna Magalhães // // 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 "Barbedo.h" //:::::::::::::::::::::::::::::::::::::::// using namespace std; using namespace MusiC::Native; //:::::::::::::::::::::::::::::::::::::::// const int MusiC::Native::Barbedo::MAX_CANDIDATES = 20; const int MusiC::Native::Barbedo::CLUSTER_SIZE = 92; const int MusiC::Native::Barbedo::CLUSTER_COUNT = 32; const float MusiC::Native::Barbedo::RADIUS = 0.7f; const int MusiC::Native::Barbedo::FRAME_COUNT = MusiC::Native::Barbedo::CLUSTER_SIZE * MusiC::Native::Barbedo::CLUSTER_COUNT; //:::::::::::::::::::::::::::::::::::::::// /// /// /// /// <param name="szA"> /// A <see cref="std::int"/> /// </param> /// /// <param name="szB"> /// A <see cref="std::int"/> /// </param> VectorCombinationData * Barbedo::CreateCombination( ClassData * classA, ClassData * classB ) { LOG_IN(); if( classA->nFrames < 3 || classB->nFrames < 3 ) { log << "ERROR: A class must have at least 3 vectors" << endl; LOG_OUT(); return NULL; } VectorCombinationData * r = new VectorCombinationData(classA, classB); LOG_OUT(); return r; } //:::::::::::::::::::::::::::::::::::::::// /// /// /// /// <param name="cl"> /// A <see cref="MusiC::Native::ClassData"/> /// </param> DataCollection * Barbedo::FilterCandidates( DataCollection * dtCol ) { LOG_IN(); log << "Target Frame Count: " << MAX_CANDIDATES << endl << endl; log << "Std. Dev. Radius for Approval: " << RADIUS << endl << endl; // feat idx and feat count register int idx = 0; register int nFeat = dtCol->nFeatures; // Initialize statistics vector float * mean = new float[ nFeat ]; float * var = new float[ nFeat ]; float * high_bound = new float[ nFeat ]; float * low_bound = new float[ nFeat ]; float * currentFrame; DataHandler data; data.Attach( dtCol ); DataCollection * fdtCol = DataHandler::BuildDataCollection( data.GetNumFeatures() ); DataHandler fdata; fdata.Attach( fdtCol ); ClassData * cl = data.GetNextClass(); while( cl ) { ClassData * ncl = DataHandler::BuildClassData( fdtCol ); FileData * nfl = DataHandler::BuildFileData( ncl ); // loop counter int candidates_counter = 0; // Clear statistics for( idx = 0; idx < nFeat; idx++ ) { mean[ idx ] = 0.0f; var[ idx ] = 0.0f; high_bound[ idx ] = 0.0f; low_bound[ idx ] = 0.0f; } FrameData * frameDt = cl->pFirstFile->pFirstFrame; int nframes_before = ( int ) cl->nFrames; // Calculating mean, var of all frames. // var = E( x^2 ) - E( x )^2 // http://en.wikipedia.org/wiki/Computational_formula_for_the_variance while ( frameDt ) { currentFrame = frameDt->pData; for( idx = 0; idx < nFeat; idx++ ) { mean[ idx ] += currentFrame[ idx ] / cl->nFrames; var[ idx ] += currentFrame[ idx ] * currentFrame[ idx ] / cl->nFrames; } frameDt = frameDt->pNextFrame; } // Calculating limits of acceptable vectors for( idx = 0; idx < nFeat; idx++ ) { var[ idx ] = abs( var[ idx ] - mean[ idx ] * mean[ idx ] ); // 1% of the standard deviation if( var[ idx ] < 0.0001f * mean[ idx ] * mean[ idx ] ) var[ idx ] = 0.0001f * mean[ idx ] * mean[ idx ]; high_bound[ idx ] = mean[ idx ] + RADIUS * sqrt( var[ idx ] ); low_bound[ idx ] = mean[ idx ] - RADIUS * sqrt( var[ idx ] ); float std_dev = sqrt( var[ idx ] ); log << "" << idx << ": " << mean[ idx ] << " | " << var[ idx ] << " | " << std_dev << " (" << 100*std_dev / mean[ idx ]; log << "%) | " << high_bound[ idx ] << " | " << low_bound[ idx ] << endl; } // Go back to first frame frameDt = cl->pFirstFile->pFirstFrame; bool keep; while ( frameDt ) { keep = true; currentFrame = frameDt->pData; // @todo: Add comparison to force include. // Avaliate if the frame should be kept. for( idx = 0; idx < nFeat; idx++ ) { if( currentFrame[ idx ] >= high_bound[ idx ] || currentFrame[ idx ] <= low_bound[ idx ] ) { keep = false; break; } } // Is it a surplus ? if( candidates_counter >= MAX_CANDIDATES && keep ) { keep = false; // make sure we know we are loosing good frames. candidates_counter++; } if( !keep ) { frameDt = frameDt->pNextFrame; continue; } candidates_counter++; FrameData * nfr = DataHandler::BuildFrameData( nfl ); memcpy( nfr->pData, frameDt->pData, nFeat * sizeof(float) ); frameDt = frameDt->pNextFrame; } log.put('\n'); log << "- Frame Count -" << endl; log << "Initial: " << nframes_before << " Aproved: " << candidates_counter << " (" << 100*candidates_counter/nframes_before << "%) "; log << " Selected: " << ncl->nFrames << endl << endl; cl = cl->pNextClass; } delete mean; delete var; delete low_bound; delete high_bound; LOG_OUT(); return fdtCol; } //:::::::::::::::::::::::::::::::::::::::// /// /// /// /// <param name="ref"> /// A <see cref="::RefVecIndex"/> /// </param> int Barbedo::Combine( VectorCombinationData * ref ) { LOG_IN(); if( gsl_combination_next( ref->b->raw ) == GSL_FAILURE ) { if( gsl_combination_next( ref->a->raw ) == GSL_FAILURE ) { LOG_OUT(); return GSL_FAILURE; } else ref->a->update(); gsl_combination_init_first( ref->b->raw ); ref->b->reset(); } else { // update b ref->b->update(); } LOG_OUT(); return GSL_SUCCESS; } //:::::::::::::::::::::::::::::::::::::::// /// /// /// /// <param name="src"> /// A <see cref="std::float"/> /// </param> /// <param name="ref"> /// A <see cref="std::float"/> /// </param> /// <param name="size"> /// A <see cref="std::int"/> /// </param> float Barbedo::EuclideanDistance( float * src, float * ref, int size ) { LOG_IN(); // column order double ret = 0; double cum = 0; for( int idx = 0; idx < size; idx++ ) { cum = src[ idx ] - ref[ idx ]; ret += cum * cum; } LOG_OUT(); return (float) sqrt( ret ); } //:::::::::::::::::::::::::::::::::::::::// FileData * Barbedo::Filter( FileData * fileDt, unsigned int nFeat ) { LOG_IN(); // loop counters //unsigned int frame_counter = 0; unsigned int cluster_sz_counter = 0; unsigned int cluster_counter = 0; register unsigned int idx = 0; register unsigned int nfeat = nFeat; float * mean = new float[ nFeat ]; float * var = new float[ nFeat ]; float * max = new float[ nFeat ]; for( idx = 0; idx < nfeat; idx++ ) { mean[ idx ] = 0.0f; var[ idx ] = 0.0f; max[ idx ] = -INFINITY; } unsigned int firstFrameIdx = ( unsigned int ) ceil( (float) ( fileDt->nFrames - 1 ) / 2 ) - floor( (float) FRAME_COUNT / 2 ); if( firstFrameIdx < 0 ) { log << "File too short" << endl; LOG_OUT(); return NULL; } //log << "FrameCount: " << fileDt->nFrames << " Begin: " << firstFrameIdx; //log << " End: " << firstFrameIdx + FRAME_COUNT - 1 << endl << endl; FileData * nfl = new FileData(); nfl->pFirstFrame = NULL; nfl->nFrames = 0; FrameData * frameDt = fileDt->pFirstFrame; float * currentFrame; /*for( frame_counter = 0; frame_counter < firstFrameIdx; frame_counter++ ) { frameDt = frameDt->pNextFrame; }*/ for( cluster_counter = 0; cluster_counter < CLUSTER_COUNT; cluster_counter++ ) { FrameData * nfd = new FrameData( ); nfd->pData = new float[ nFeat * 3 ]; nfd->pNextFrame = NULL; for( idx = 0; idx < nfeat; idx++ ) { mean[ idx ] = 0.0f; var[ idx ] = 0.0f; max[ idx ] = -INFINITY; } unsigned int cluster_size = 0; for( cluster_sz_counter = 0; cluster_sz_counter < CLUSTER_SIZE; cluster_sz_counter++ ) { currentFrame = frameDt->pData; for( idx = 0; idx < nfeat; idx++ ) { // NaN Test if( currentFrame[ idx ] != currentFrame[ idx ] ) break; // Inf Test if( currentFrame[ idx ] > FLT_MAX || currentFrame[ idx ] < -FLT_MAX ) break; } // loop breaked if( idx != nfeat ) continue; cluster_size++; for( idx = 0; idx < nfeat; idx++ ) { mean[ idx ] += currentFrame[ idx ] / CLUSTER_SIZE; var[ idx ] += currentFrame[ idx ] * currentFrame[ idx ] / CLUSTER_SIZE; if( currentFrame[ idx ] > max[ idx ] ) max[ idx ] = currentFrame[ idx ]; } frameDt = frameDt->pNextFrame; } log << "cluster: " << cluster_counter << " - frames:" << cluster_size << endl; for( idx = 0; idx < nfeat; idx++ ) { var[ idx ] = abs( var[ idx ] - mean[ idx ] * mean[ idx ] ); // standard deviation >= 1% of the mean if( var[ idx ] < 0.0001f * mean[ idx ] * mean[ idx ] ) var[ idx ] = 0.0001f * mean[ idx ] * mean[ idx ]; nfd->pData[ 3 * idx ] = mean[ idx ]; nfd->pData[ 3 * idx + 1 ] = var[ idx ]; float ppp = max[ idx ] / mean[ idx ]; // NaN Test 0/0 if( ppp != ppp ) ppp = 1.0f; // Inf or -Inf +x/0 -x/0 if( ppp > FLT_MAX || ppp < -FLT_MAX ) ppp = max[ idx ] / std::numeric_limits<float>::epsilon(); nfd->pData[ 3 * idx + 2 ] = ppp; float std_dev = sqrt( var[ idx ] ); log << "" << idx << ": " << mean[ idx ] << " | " << var[ idx ] << " | " << std_dev; log <<" (" << 100 * std_dev/mean[ idx ] << "%) | " << max[ idx ] / mean[ idx ] << endl; } log.put('\n'); nfl->nFrames++; if( nfl->pFirstFrame == NULL ) { nfl->pFirstFrame = nfd; nfl->pLastFrame = nfd; } else { nfl->pLastFrame->pNextFrame = nfd; nfl->pLastFrame = nfd; } } delete max; delete mean; delete var; LOG_OUT(); return nfl; } //:::::::::::::::::::::::::::::::::::::::// /// /// /// DataCollection * Barbedo::Filter( DataCollection * extractedData ) { LOG_IN(); DataHandler hnd; hnd.Attach( extractedData ); log << "============ Barbedo::Filter ============" << endl; log << "Received " << hnd.GetNumClasses( ) << " Classes" << endl; log << "Received " << hnd.GetNumFeatures( ) << " Features" << endl; log << "========== Algorithm Constants ==========" << endl; log << "Frames per cluster: " << CLUSTER_SIZE << endl; log << "Clusters per file: " << CLUSTER_COUNT << endl; log << "=========================================" << endl; DataCollection * dtCol = new DataCollection( ); dtCol->nFeatures = 3 * extractedData->nFeatures; dtCol->nClasses = extractedData->nClasses; dtCol->pFirstClass = NULL; dtCol->pLastClass = NULL; ClassData * cl = extractedData->pFirstClass; for( unsigned int class_counter = 0; class_counter < dtCol->nClasses; class_counter++ ) { // New Class ClassData * ncl = new ClassData( ); ncl->pNextClass = NULL; ncl->pFirstFile = NULL; ncl->pLastFile = NULL; ncl->pCollection = dtCol; ncl->nFrames = 0; ncl->nFiles = 0; if( !dtCol->pFirstClass ) dtCol->pFirstClass = ncl; if( dtCol->pLastClass ) dtCol->pLastClass->pNextClass = ncl; dtCol->pLastClass = ncl; //////////////////////// FileData * fileDt = cl->pFirstFile; log << "class: " << class_counter << endl; log << "#files: " << cl->nFiles << " #frames: " << cl->nFrames << endl << endl; for( int file_counter = 0; file_counter < cl->nFiles; file_counter++ ) { FileData * nfl = Filter( fileDt, hnd.GetNumFeatures() ); nfl->pNextFile = NULL; nfl->pPrevFile = NULL; nfl->pClass = ncl; ncl->nFiles++; ncl->nFrames += nfl->nFrames; if( ncl->pFirstFile == NULL ) { ncl->pFirstFile = nfl; ncl->pLastFile = nfl; } else { ncl->pLastFile->pLastFrame->pNextFrame = nfl->pFirstFrame; ncl->pLastFile->pNextFile = nfl; ncl->pLastFile = nfl; } //log << endl; fileDt = fileDt->pNextFile; } //log << "Output Summary frames: " << ncl->nFrames << endl << endl; cl = cl->pNextClass; } LOG_OUT(); return dtCol; } //:::::::::::::::::::::::::::::::::::::::// /// /// /// void * Barbedo::Train( DataCollection * extractedData ) { LOG_IN(); DataHandler data; data.Attach( extractedData ); //log << "DataCollection: " << sizeof(DataCollection) << endl; //log << "ClassData: " << sizeof(ClassData) << endl; //log << "FileData: " << sizeof(FileData) << endl; //log << "FrameData: " << sizeof(FrameData) << endl; //log << "Architecture: size_t: " << sizeof(size_t) << " pointer: " << sizeof(int *) << endl; //log << "Address:" << reinterpret_cast<size_t>( extractedData ) << endl; //log << "Received " << data.GetNumClasses( ) << " Classes" << endl; //log << "Received " << data.GetNumFeatures( ) << " Features" << endl; BarbedoTData * tdata = new BarbedoTData( data.GetNumClasses(), data.GetNumFeatures() ); unsigned int genreCombinationIndex = 0; log << "========================" << endl; unsigned int genreCombinationCount = tdata->GetGenreCombinationCount(); log << "Algorithm Rounds: " << genreCombinationCount << endl; log << "========================" << endl << endl; DataCollection * filteredData = FilterCandidates( extractedData ); DataHandler fdata; fdata.Attach( filteredData ); // Genre Combination Loop gsl_combination * selectedGenres = gsl_combination_calloc( data.GetNumClasses(), 2 ); for( ;genreCombinationIndex < genreCombinationCount; genreCombinationIndex++ ) { log << "========================" << endl; log << " Round " << genreCombinationIndex << endl; log << "========================" << endl << endl; // Get Classes to Compare int a = gsl_combination_get( selectedGenres, 0 ); int b = gsl_combination_get( selectedGenres, 1 ); log << "Comparing Genres " << a << " and " << b << endl; ClassData * fClassA = fdata.GetClass( a ); ClassData * fClassB = fdata.GetClass( b ); ClassData * classA = data.GetClass( a ); ClassData * classB = data.GetClass( b ); log << "Frame Count: " << fClassA->nFrames << "/" << classA->nFrames << endl; log << "Frame Count: " << fClassB->nFrames << "/" << classB->nFrames << endl << endl; //float genre_weight = ((float) classA->nFrames / (float) classB->nFrames); float genre_weight = 1; unsigned int nclusters_a = classA->nFrames; unsigned int nclusters_b = genre_weight * classB->nFrames; // ----------- Frames Combintation -----------// long score_a, score_b, score_max, winner; long potentialsCombinationIndex = 0; score_max = winner = 0; // Create combination control structure VectorCombinationData * refVecsIndex = CreateCombination( fClassA, fClassB ); if( refVecsIndex == NULL ) { log << "Combination structure out of memory" << endl; LOG_OUT(); return NULL; } // Frames Combination Loop do { score_a = 0; score_b = 0; // Dist 1 - Class A FrameData * refVec = classA->pFirstFile->pFirstFrame; for( UInt64 idx = 0; idx < classA->nFrames; idx++ ) { if( Evaluate(refVec, refVecsIndex->a->frames, refVecsIndex->b->frames, tdata->nFeat) == 0 ) score_a++; // Get Next Frame refVec = refVec->pNextFrame; } // Dist 2 - Class B refVec = classB->pFirstFile->pFirstFrame; for( UInt64 idx = 0; idx < classB->nFrames; idx++ ) { if( Evaluate(refVec, refVecsIndex->a->frames, refVecsIndex->b->frames, tdata->nFeat) == 1 ) score_b++; refVec = refVec->pNextFrame; } // Frame Comparison unsigned int wscore_b = (genre_weight * score_b); // Scoring System if( score_a + wscore_b > score_max ) { score_max = score_a + wscore_b; winner = potentialsCombinationIndex; tdata->SetPair( genreCombinationIndex, selectedGenres, refVecsIndex ); ostringstream aElem; ostringstream bElem; aElem << "[ "; bElem << "[ "; for( int elemIdx = 0; elemIdx < 3; elemIdx++ ) { aElem << gsl_combination_get( refVecsIndex->a->raw, elemIdx ) << " "; bElem << gsl_combination_get( refVecsIndex->b->raw, elemIdx ) << " "; } aElem << "]"; bElem << "]"; log << "New Winner: " << winner << " / " << ( unsigned int ) ( gsl_sf_choose( fClassA->nFrames, 3 ) * gsl_sf_choose( fClassB->nFrames, 3 ) ) << " - score: A(" << score_a << "/" << nclusters_a << " - " << 100 * score_a / nclusters_a << "%) B(" << wscore_b << "/" << nclusters_b << " - " << 100 * wscore_b / nclusters_b << "%) - Total: " << score_max << "/" << (nclusters_a + nclusters_b) << " " << 100 * score_max / (nclusters_a + nclusters_b) << "% - Vectors: " << aElem.str( ) << " & " << bElem.str( ) << endl; } if( !(potentialsCombinationIndex % 100000) ) { log << "GenreComb " << genreCombinationIndex << " VectorComb " << potentialsCombinationIndex << std::endl; } potentialsCombinationIndex++; } while( Combine( refVecsIndex ) == GSL_SUCCESS ); // Stop Condition: Class Comparison delete refVecsIndex; if( gsl_combination_next( selectedGenres ) == GSL_FAILURE ) // Stop Condition: Genre Comparison break; } LOG_OUT(); return tdata; } //:::::::::::::::::::::::::::::::::::::::// int Barbedo::Classify( FrameData * pCurrent, FrameData ** a, FrameData ** b, unsigned int nFeat ) { return Evaluate(pCurrent, a, b, nFeat); } //:::::::::::::::::::::::::::::::::::::::// unsigned int Barbedo::Evaluate( FrameData * pCurrent, FrameData ** a, FrameData ** b, unsigned int nFeat ) { LOG_IN(); float dist_loop_min = INFINITY; float tmp_dist; unsigned int loop_min; for( unsigned int vec = 0; vec < 3; vec++ ) { float * pTarget = a[ vec ]->pData; tmp_dist = EuclideanDistance( pCurrent->pData, pTarget, nFeat ); if( tmp_dist < dist_loop_min ) { dist_loop_min = tmp_dist; loop_min = vec; } } for( unsigned int vec = 0; vec < 3; vec++ ) { float * pTarget = b[ vec ]->pData; tmp_dist = EuclideanDistance( pCurrent->pData, pTarget, nFeat ); if( tmp_dist < dist_loop_min ) { dist_loop_min = tmp_dist; loop_min = vec + 3; } } if( loop_min < 3 ) { LOG_OUT(); return 0; } LOG_OUT(); return 1; } #if defined( MUSIC_TEST ) int main() { int featCount, nFeat = 2; int classCount, nClasses = 2; int fileCount, nFiles = 3; int frame_count, nFrames = 3000; DataCollection * dtCol = new DataCollection( ); dtCol->nFeatures = nFeat; dtCol->pFirstClass = NULL; dtCol->nClasses = 0; for( classCount = 0; classCount < nClasses; classCount++ ) { ClassData * newclass = new ClassData( ); newclass->nFiles = 0; newclass->nFrames = 0; newclass->pFirstFile = NULL; newclass->pCollection = dtCol; newclass->pNextClass = dtCol->pFirstClass; dtCol->pFirstClass = newclass; dtCol->nClasses++; for( fileCount = 0; fileCount < nFiles; fileCount++ ) { FileData * newfile = new FileData( ); newfile->nFrames = 0; newfile->pFirstFrame = NULL; newfile->pClass = newclass; newfile->pNextFile = newclass->pFirstFile; newclass->pFirstFile = newfile; newclass->nFiles++; for( frame_count = 0; frame_count < nFrames; frame_count++ ) { FrameData * newFrame = new FrameData( ); newFrame->pData = new float[ nFeat ]; for( int idx = 0; idx < nFeat; idx++ ) newFrame->pData[ idx ] = 1; newFrame->pNextFrame = newfile->pFirstFrame; newfile->pFirstFrame = newFrame; newfile->nFrames++; newclass->nFrames++; } } } Barbedo b; DataCollection * col = b.Filter( dtCol ); b.Train( col ); return 0; } #endif
24.782178
135
0.593987
berkus
30f275533249e72683f36cb31fd296adfbe3a36b
757
cc
C++
constructs/test/epsilon_greedy_test.cc
shrenikm/Mnyrve
6e0f41adfc9665ab4b516db73fa64a236e684c71
[ "MIT" ]
null
null
null
constructs/test/epsilon_greedy_test.cc
shrenikm/Mnyrve
6e0f41adfc9665ab4b516db73fa64a236e684c71
[ "MIT" ]
2
2018-11-04T07:01:20.000Z
2018-11-17T07:40:19.000Z
constructs/test/epsilon_greedy_test.cc
shrenikm/Mnyrve
6e0f41adfc9665ab4b516db73fa64a236e684c71
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "constructs/include/epsilon_greedy.h" namespace { using mnyrve::constructs::EpsilonGreedy; class EpsilonGreedyTest : public ::testing::Test { protected: EpsilonGreedyTest() { } void SetUp() override { } EpsilonGreedy eg1_{EpsilonGreedy(0.1)}; }; TEST_F(EpsilonGreedyTest, InitializationCheck) { EXPECT_DOUBLE_EQ(eg1_.GetEpsilon(), 0.1); } TEST_F(EpsilonGreedyTest, SetterCheck) { eg1_.SetEpsilon(0.2); EXPECT_DOUBLE_EQ(eg1_.GetEpsilon(), 0.2); } TEST_F(EpsilonGreedyTest, OperatorCheck) { bool res = eg1_.ActGreedy(); ASSERT_TRUE((res || !res)); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
14.283019
50
0.689564
shrenikm
30fdfbe180020d573ee8bd25a1cc2e17914a6d7d
8,346
cpp
C++
PsgDBUtils/PsgDBUSpecFldEdt.cpp
rs0h/PostGISGDO
abf980569b703e80567b43817ea1d79fdee626e9
[ "Apache-2.0" ]
null
null
null
PsgDBUtils/PsgDBUSpecFldEdt.cpp
rs0h/PostGISGDO
abf980569b703e80567b43817ea1d79fdee626e9
[ "Apache-2.0" ]
null
null
null
PsgDBUtils/PsgDBUSpecFldEdt.cpp
rs0h/PostGISGDO
abf980569b703e80567b43817ea1d79fdee626e9
[ "Apache-2.0" ]
null
null
null
// Copyright 2013 Intergraph 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 "PsgDBUSpecFldEdt.hpp" #include <tchar.h> #include "PsgDBUtils.rh" INT_PTR CALLBACK DBUSpecFldDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { CDBUSpecFldDlg *cw = NULL; if(uMsg == WM_INITDIALOG) cw = (CDBUSpecFldDlg*)lParam; else cw = (CDBUSpecFldDlg*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); switch(uMsg) { case WM_INITDIALOG: return(cw->WMInitDialog(hwndDlg, (HWND)wParam, lParam)); case WM_COMMAND: return(cw->WMCommand(hwndDlg, HIWORD(wParam), LOWORD(wParam), (HWND)lParam)); default: return(FALSE); } } CDBUSpecFldDlg::CDBUSpecFldDlg(HINSTANCE hInstance) { m_hInstance = hInstance; m_lConnHandle = 0; m_hwndMain = NULL; m_hwndDlg = NULL; m_pTables = NULL; m_pCurTbl = NULL; m_bSetup = false; } CDBUSpecFldDlg::~CDBUSpecFldDlg() { delete m_pTables; } bool CDBUSpecFldDlg::ShowModal(HWND hWnd, long lConnHandle) { m_hwndMain = hWnd; m_lConnHandle = lConnHandle; m_pTables = DbuGetTables(lConnHandle); return(DialogBoxParam(m_hInstance, _T("SPECCOLLEDTDLG"), hWnd, DBUSpecFldDlgProc, (LPARAM)this)); } void CDBUSpecFldDlg::SetupListBox(HWND hwndDlg) { HWND lv = GetDlgItem(hwndDlg, CTR_SCED_FTRLB); int n = m_pTables->GetCount(); int idx; IDbuTable *ptbl; for(int i = 0; i < n; i++) { ptbl = m_pTables->GetItem(i); if(CanTableHaveColumn(ptbl)) { idx = SendMessage(lv, LB_ADDSTRING, 0, (LPARAM)ptbl->GetNamePtr()); SendMessage(lv, LB_SETITEMDATA, idx, (LPARAM)ptbl); } } return; } INT_PTR CDBUSpecFldDlg::WMInitDialog(HWND hwndDlg, HWND hwndFocus, LPARAM lInitParam) { m_hwndDlg = hwndDlg; SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lInitParam); m_bSetup = true; SendDlgItemMessage(hwndDlg, CTR_FCD_FTRDESCEDT, EM_LIMITTEXT, 256, 0); SetupListBox(hwndDlg); ShowWindow(GetDlgItem(hwndDlg, CTR_SCED_MANAGEFLDBTN), SW_HIDE); m_bSetup = false; return(1); } INT_PTR CDBUSpecFldDlg::WMCommand(HWND hwndDlg, WORD wNotifyCode, WORD wID, HWND hwndCtl) { switch(wID) { case IDCANCEL: return(CancelBtnClick(hwndDlg)); case CTR_SCED_FTRLB: return(FtrsLBCmd(hwndDlg, wNotifyCode, hwndCtl)); case CTR_SCED_GEOMCB: return(GeomCBCmd(hwndDlg, wNotifyCode, hwndCtl)); case CTR_SCED_MANAGEFLDBTN: return(ManageFldsBtnClick(hwndDlg)); default: return(0); } } INT_PTR CDBUSpecFldDlg::CancelBtnClick(HWND hwndDlg) { EndDialog(hwndDlg, 0); return(1); } INT_PTR CDBUSpecFldDlg::FtrsLBCmd(HWND hwndDlg, WORD wNotifyCode, HWND hwndCtl) { if(wNotifyCode == LBN_SELCHANGE) { HWND cb = GetDlgItem(hwndDlg, CTR_SCED_GEOMCB); SendMessage(cb, CB_RESETCONTENT, 0, 0); int idx = SendMessage(hwndCtl, LB_GETCURSEL, 0, 0); if(idx != LB_ERR) { m_pCurTbl = (IDbuTable*)SendMessage(hwndCtl, LB_GETITEMDATA, idx, 0); GetTableColumns(cb, m_pCurTbl); GeomCBCmd(hwndDlg, CBN_SELCHANGE, cb); EnableWindow(cb, TRUE); } else { m_pCurTbl = NULL; EnableWindow(cb, FALSE); } } return(0); } INT_PTR CDBUSpecFldDlg::GeomCBCmd(HWND hwndDlg, WORD wNotifyCode, HWND hwndCtl) { if(wNotifyCode == CBN_SELCHANGE) { HWND lab = GetDlgItem(hwndDlg, CTR_SCED_GEOMTYPELAB); HWND btn = GetDlgItem(hwndDlg, CTR_SCED_MANAGEFLDBTN); int idx = SendMessage(hwndCtl, CB_GETCURSEL, 0, 0); if(idx != CB_ERR) { TCHAR sBuf[64]; IDbuField *pFld = (IDbuField*) SendMessage(hwndCtl, CB_GETITEMDATA, idx, 0); switch(pFld->GetSubType()) { case 3: LoadString(m_hInstance, IDS_ANYSPATIAL, sBuf, 64); break; case 4: LoadString(m_hInstance, IDS_RASTER, sBuf, 64); break; case 5: LoadString(m_hInstance, IDS_GRAPHTEXT, sBuf, 64); break; case 10: LoadString(m_hInstance, IDS_POINT, sBuf, 64); break; default: sBuf[0] = 0; } SendMessage(lab, WM_SETTEXT, 0, (LPARAM)sBuf); SetButtonText(btn, pFld); ShowWindow(btn, SW_SHOW); } else { SendMessage(lab, WM_SETTEXT, 0, (LPARAM)_T("")); ShowWindow(btn, SW_HIDE); } } return(0); } INT_PTR CDBUSpecFldDlg::ManageFldsBtnClick(HWND hwndDlg) { UpdateGeomFields(hwndDlg); return(0); } void CDBUSpecFldDlg::UpdateGeomFields(HWND hwndDlg) { HWND cb = GetDlgItem(hwndDlg, CTR_SCED_GEOMCB); int idx = SendMessage(cb, CB_GETCURSEL, 0, 0); if(idx != CB_ERR) { IDbuField *pFld = (IDbuField*)SendMessage(cb, CB_GETITEMDATA, idx, 0); bool bRes = m_pCurTbl->ChangeSpecField(pFld); TCHAR sMsg[64]; TCHAR sCap[32]; UINT iFlag = MB_OK; if(bRes) { SetButtonText(GetDlgItem(hwndDlg, CTR_SCED_MANAGEFLDBTN), pFld); LoadString(m_hInstance, IDS_INFOBASE, sCap, 32); LoadString(m_hInstance, IDI_DONE, sMsg, 64); iFlag |= MB_ICONINFORMATION; } else { LoadString(m_hInstance, IDS_ERRORBASE, sCap, 32); LoadString(m_hInstance, IDE_FAIL, sMsg, 64); iFlag |= MB_ICONERROR; } MessageBox(hwndDlg, sMsg, sCap, iFlag); } return; } bool CDBUSpecFldDlg::CanTableHaveColumn(IDbuTable *pTbl) { bool bRes = false; IDbuFields *pFlds = pTbl->GetFields(); IDbuField *pFld; int iType; long lSubType; int iFlds = pFlds->GetCount(); int i = 0; while(!bRes && (i < iFlds)) { pFld = pFlds->GetItem(i++); iType = pFld->GetType(); if(iType > 31) { lSubType = pFld->GetSubType(); bRes = (lSubType > 2); } } return(bRes); } void CDBUSpecFldDlg::GetTableColumns(HWND hwndCB, IDbuTable *pTbl) { IDbuFields *pFlds = pTbl->GetFields(); IDbuField *pFld; int iType; long lSubType; int idx; int iFlds = pFlds->GetCount(); for(int i = 0; i < iFlds; i++) { pFld = pFlds->GetItem(i); iType = pFld->GetType(); if(iType > 31) { lSubType = pFld->GetSubType(); if(lSubType > 2) { idx = SendMessage(hwndCB, CB_ADDSTRING, 0, (LPARAM)pFld->GetNamePtr()); SendMessage(hwndCB, CB_SETITEMDATA, idx, (LPARAM)pFld); } } } SendMessage(hwndCB, CB_SETCURSEL, 0, 0); return; } void CDBUSpecFldDlg::SetButtonText(HWND hwndBtn, IDbuField *pFld) { long lSubType = pFld->GetSubType(); bool bHasField = pFld->GetHasSpecField(); TCHAR sBuf[64]; if((lSubType == 3) || (lSubType == 10)) { if(bHasField) LoadString(m_hInstance, IDS_DROPINGRFLD, sBuf, 64); else LoadString(m_hInstance, IDS_CREATEINGRFLD, sBuf, 64); } else { if(bHasField) LoadString(m_hInstance, IDS_DROPNATIVEFLD, sBuf, 64); else LoadString(m_hInstance, IDS_CREATENATIVEFLD, sBuf, 64); } SendMessage(hwndBtn, WM_SETTEXT, 0, (LPARAM)sBuf); return; }
28.195946
82
0.58531
rs0h
a500aa849dcb041a1252635160e7c55c72029d92
3,004
cpp
C++
src/dataset.cpp
ifilot/neuralnetworkdemo
bd8ade34baee843df00aa88ece5de8db1c199253
[ "MIT" ]
1
2019-07-28T20:12:38.000Z
2019-07-28T20:12:38.000Z
src/dataset.cpp
ifilot/neuralnetworkdemo
bd8ade34baee843df00aa88ece5de8db1c199253
[ "MIT" ]
null
null
null
src/dataset.cpp
ifilot/neuralnetworkdemo
bd8ade34baee843df00aa88ece5de8db1c199253
[ "MIT" ]
1
2019-07-28T20:12:39.000Z
2019-07-28T20:12:39.000Z
/************************************************************************************ * This file is part of neuralnetworkdemo. * * https://github.com/ifilot/neuralnetworkdemo * * * * MIT License * * * * Copyright (c) 2018 Ivo Filot <ivo@ivofilot.nl> * * * * 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 "dataset.h" Dataset::Dataset(unsigned int _dataset_size, unsigned int _nr_input_nodes, unsigned int _nr_output_nodes) : dataset_size(_dataset_size), nr_input_nodes(_nr_input_nodes), nr_output_nodes(_nr_output_nodes) { this->x.resize(dataset_size, std::vector<double>(this->nr_input_nodes)); this->y.resize(dataset_size, std::vector<double>(this->nr_output_nodes)); } void Dataset::set_input_vector(unsigned int i, const std::vector<double>& vals) { cblas_dcopy(vals.size(), &vals[0], 1, &this->x[i][0], 1); } void Dataset::set_output_vector(unsigned int i, const std::vector<double>& vals) { cblas_dcopy(vals.size(), &vals[0], 1, &this->y[i][0], 1); }
63.914894
107
0.478695
ifilot
a501858abeb4fad7fcbc4efacf707fde2c1e9850
9,695
cpp
C++
thirdparty/AngelCode/sdk/tests/test_feature/source/test_constobject.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
1
2021-07-25T15:10:39.000Z
2021-07-25T15:10:39.000Z
thirdparty/AngelCode/sdk/tests/test_feature/source/test_constobject.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
null
null
null
thirdparty/AngelCode/sdk/tests/test_feature/source/test_constobject.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
null
null
null
#include "utils.h" namespace TestConstObject { #define TESTNAME "TestConstObject" static const char *script2 = "const string URL_SITE = \"http://www.sharkbaitgames.com\"; \n" "const string URL_GET_HISCORES = URL_SITE + \"/get_hiscores.php\"; \n" "const string URL_CAN_SUBMIT_HISCORE = URL_SITE + \"/can_submit_hiscore.php\"; \n" "const string URL_SUBMIT_HISCORE = URL_SITE + \"/submit_hiscore.php\"; \n"; static const char *script = "void Test(obj@ o) { }"; static const char *script3 = "class CTest \n" "{ \n" " int m_Int; \n" " \n" " void SetInt(int iInt) \n" " { \n" " m_Int = iInt; \n" " } \n" "}; \n" "void func() \n" "{ \n" " const CTest Test; \n" " const CTest@ TestHandle = @Test; \n" " \n" " TestHandle.SetInt(1); \n" " Test.SetInt(1); \n" "} \n"; class CObj { public: CObj() {refCount = 1; val = 0; next = 0;} ~CObj() {if( next ) next->Release();} CObj &operator=(CObj &other) { val = other.val; if( next ) next->Release(); next = other.next; if( next ) next->AddRef(); return *this; }; void AddRef() {refCount++;} void Release() {if( --refCount == 0 ) delete this;} void SetVal(int val) {this->val = val;} int GetVal() const {return val;} int &operator[](int) {return val;} const int &operator[](int) const {return val;} int refCount; int val; CObj *next; }; CObj *CObj_Factory() { return new CObj(); } CObj c_obj; bool Test() { if( strstr(asGetLibraryOptions(), "AS_MAX_PORTABILITY") ) { printf("%s: Skipped due to AS_MAX_PORTABILITY\n", TESTNAME); return false; } int r; bool fail = false; asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); // Register an object type r = engine->RegisterObjectType("obj", sizeof(CObj), asOBJ_REF); assert( r>=0 ); r = engine->RegisterObjectBehaviour("obj", asBEHAVE_FACTORY, "obj@ f()", asFUNCTION(CObj_Factory), asCALL_CDECL); assert( r>=0 ); r = engine->RegisterObjectBehaviour("obj", asBEHAVE_ADDREF, "void f()", asMETHOD(CObj,AddRef), asCALL_THISCALL); assert( r>=0 ); r = engine->RegisterObjectBehaviour("obj", asBEHAVE_RELEASE, "void f()", asMETHOD(CObj,Release), asCALL_THISCALL); assert( r>=0 ); r = engine->RegisterObjectBehaviour("obj", asBEHAVE_ASSIGNMENT, "obj &f(const obj &in)", asMETHOD(CObj,operator=), asCALL_THISCALL); assert( r>=0 ); r = engine->RegisterObjectBehaviour("obj", asBEHAVE_INDEX, "int &f(int)", asMETHODPR(CObj, operator[], (int), int&), asCALL_THISCALL); assert( r>=0 ); r = engine->RegisterObjectBehaviour("obj", asBEHAVE_INDEX, "const int &f(int) const", asMETHODPR(CObj, operator[], (int) const, const int&), asCALL_THISCALL); assert( r>=0 ); r = engine->RegisterObjectType("prop", sizeof(int), asOBJ_VALUE | asOBJ_POD | asOBJ_APP_PRIMITIVE); assert( r>=0 ); r = engine->RegisterObjectProperty("prop", "int val", 0); assert( r>=0 ); r = engine->RegisterObjectMethod("obj", "void SetVal(int)", asMETHOD(CObj, SetVal), asCALL_THISCALL); assert( r>=0 ); r = engine->RegisterObjectMethod("obj", "int GetVal() const", asMETHOD(CObj, GetVal), asCALL_THISCALL); assert( r>=0 ); r = engine->RegisterObjectProperty("obj", "int val", offsetof(CObj,val)); assert( r>=0 ); r = engine->RegisterObjectProperty("obj", "obj@ next", offsetof(CObj,next)); assert( r>=0 ); r = engine->RegisterObjectProperty("obj", "prop p", offsetof(CObj,val)); assert( r>=0 ); r = engine->RegisterGlobalProperty("const obj c_obj", &c_obj); assert( r>=0 ); r = engine->RegisterGlobalProperty("obj g_obj", &c_obj); assert( r>= 0 ); RegisterScriptString(engine); COutStream out; engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); engine->AddScriptSection(0, "script1", script2, strlen(script2), 0); r = engine->Build(0); if( r < 0 ) fail = true; CBufferedOutStream bout; // TODO: // A member array of a const object is also const // TODO: // Parameters registered as &in and not const must make a copy of the object (even for operators) // A member object of a const object is also const bout.buffer = ""; engine->SetMessageCallback(asMETHOD(CBufferedOutStream,Callback), &bout, asCALL_THISCALL); r = engine->ExecuteString(0, "c_obj.p.val = 1;"); if( r >= 0 ) fail = true; if( bout.buffer != "ExecuteString (1, 13) : Error : Reference is read-only\n" ) fail = true; c_obj.val = 0; engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); r = engine->ExecuteString(0, "g_obj.p.val = 1;"); if( r < 0 ) fail = true; if( c_obj.val != 1 ) fail = true; // Allow overloading on const. r = engine->ExecuteString(0, "obj o; o[0] = 1;"); if( r < 0 ) fail = true; // Allow return of const ref r = engine->ExecuteString(0, "int a = c_obj[0];"); if( r < 0 ) fail = true; // Do not allow the script to call object behaviour that is not const on a const object bout.buffer = ""; engine->SetMessageCallback(asMETHOD(CBufferedOutStream,Callback), &bout, asCALL_THISCALL); r = engine->ExecuteString(0, "c_obj[0] = 1;"); if( r >= 0 ) fail = true; if( bout.buffer != "ExecuteString (1, 10) : Error : Reference is read-only\n" ) fail = true; // Do not allow the script to take a non-const handle to a const object bout.buffer = ""; r = engine->ExecuteString(0, "obj@ o = @c_obj;"); if( r >= 0 ) fail = true; if( bout.buffer != "ExecuteString (1, 10) : Error : Can't implicitly convert from 'const obj@' to 'obj@&'.\n" ) fail = true; // Do not allow the script to pass a const obj@ to a parameter that is not a const obj@ engine->AddScriptSection(0, "script", script, strlen(script)); engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); engine->Build(0); bout.buffer = ""; engine->SetMessageCallback(asMETHOD(CBufferedOutStream,Callback), &bout, asCALL_THISCALL); r = engine->ExecuteString(0, "Test(@c_obj);"); if( r >= 0 ) fail = true; if( bout.buffer != "ExecuteString (1, 1) : Error : No matching signatures to 'Test(const obj@const&)'\n" ) fail = true; // Do not allow the script to assign the object handle member of a const object bout.buffer = ""; r = engine->ExecuteString(0, "@c_obj.next = @obj();"); if( r >= 0 ) fail = true; if( bout.buffer != "ExecuteString (1, 13) : Error : Reference is read-only\n" ) fail = true; // Allow the script to change the object the handle points to engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); r = engine->ExecuteString(0, "c_obj.next.val = 1;"); if( r != 3 ) fail = true; // Allow the script take a handle to a non const object handle in a const object r = engine->ExecuteString(0, "obj @a = @c_obj.next;"); if( r < 0 ) fail = true; // Allow the script to take a const handle to a const object r = engine->ExecuteString(0, "const obj@ o = @c_obj;"); if( r < 0 ) fail = true; bout.buffer = ""; engine->SetMessageCallback(asMETHOD(CBufferedOutStream,Callback), &bout, asCALL_THISCALL); r = engine->ExecuteString(0, "obj @a; const obj @b; @a = @b;"); if( r >= 0 ) fail = true; if(bout.buffer != "ExecuteString (1, 28) : Error : Can't implicitly convert from 'const obj@&' to 'obj@&'.\n" ) fail = true; // Allow a non-const handle to be assigned to a const handle engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); r = engine->ExecuteString(0, "obj @a; const obj @b; @b = @a;"); if( r < 0 ) fail = true; // Do not allow the script to alter properties of a const object bout.buffer = ""; engine->SetMessageCallback(asMETHOD(CBufferedOutStream,Callback), &bout, asCALL_THISCALL); r = engine->ExecuteString(0, "c_obj.val = 1;"); if( r >= 0 ) fail = true; if( bout.buffer != "ExecuteString (1, 11) : Error : Reference is read-only\n" ) fail = true; // Do not allow the script to call non-const methods on a const object bout.buffer = ""; r = engine->ExecuteString(0, "c_obj.SetVal(1);"); if( r >= 0 ) fail = true; if( bout.buffer != "ExecuteString (1, 7) : Error : No matching signatures to 'obj::SetVal(const uint) const'\n" ) fail = true; // Allow the script to call const methods on a const object engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); r = engine->ExecuteString(0, "c_obj.GetVal();"); if( r < 0 ) fail = true; // Handle to const must not allow call to non-const methods bout.buffer = ""; engine->SetMessageCallback(asMETHOD(CBufferedOutStream,Callback), &bout, asCALL_THISCALL); engine->AddScriptSection(0, "script", script3, strlen(script3)); r = engine->Build(0); if( r >= 0 ) fail = true; if( bout.buffer != "script (10, 1) : Info : Compiling void func()\n" "script (15, 13) : Error : No matching signatures to 'CTest::SetInt(const uint) const'\n" "script (16, 7) : Error : No matching signatures to 'CTest::SetInt(const uint) const'\n" ) { printf(bout.buffer.c_str()); fail = true; } engine->Release(); if( fail ) printf("%s: failed\n", TESTNAME); // Success return fail; } } // namespace
38.78
176
0.6164
kcat
a503dc8f20bd4d662af0e069d2cf35cc7afd093d
2,461
hpp
C++
src/uhs/atomizer/watchtower/controller.hpp
JonWiggins/opencbdc-tx
628dfb9487390bd6a2a520645cbc5a1aaca06eac
[ "MIT" ]
null
null
null
src/uhs/atomizer/watchtower/controller.hpp
JonWiggins/opencbdc-tx
628dfb9487390bd6a2a520645cbc5a1aaca06eac
[ "MIT" ]
null
null
null
src/uhs/atomizer/watchtower/controller.hpp
JonWiggins/opencbdc-tx
628dfb9487390bd6a2a520645cbc5a1aaca06eac
[ "MIT" ]
null
null
null
// Copyright (c) 2021 MIT Digital Currency Initiative, // Federal Reserve Bank of Boston // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef OPENCBDC_TX_SRC_WATCHTOWER_CONTROLLER_H_ #define OPENCBDC_TX_SRC_WATCHTOWER_CONTROLLER_H_ #include "uhs/atomizer/archiver/client.hpp" #include "util/common/config.hpp" #include "util/network/connection_manager.hpp" #include "util/serialization/format.hpp" #include "watchtower.hpp" namespace cbdc::watchtower { /// Wrapper for the watchtower executable implementation. class controller { public: controller() = delete; controller(const controller&) = delete; auto operator=(const controller&) -> controller& = delete; controller(controller&&) = delete; auto operator=(controller&&) -> controller& = delete; /// Constructor. /// \param watchtower_id the running ID of this watchtower. /// \param opts configuration options. /// \param log pointer to shared logger. controller(uint32_t watchtower_id, config::options opts, const std::shared_ptr<logging::log>& log); ~controller(); /// Initializes the controller. /// \return true if initialization succeeded. auto init() -> bool; auto get_block_height() const -> uint64_t; private: uint32_t m_watchtower_id; cbdc::config::options m_opts; std::shared_ptr<logging::log> m_logger; watchtower m_watchtower; std::atomic<uint64_t> m_last_blk_height{0}; cbdc::network::connection_manager m_internal_network; cbdc::network::connection_manager m_external_network; cbdc::network::connection_manager m_atomizer_network; cbdc::archiver::client m_archiver_client; std::thread m_internal_server; std::thread m_external_server; std::thread m_atomizer_thread; void connect_atomizers(); auto atomizer_handler(cbdc::network::message_t&& pkt) -> std::optional<cbdc::buffer>; auto internal_server_handler(cbdc::network::message_t&& pkt) -> std::optional<cbdc::buffer>; auto external_server_handler(cbdc::network::message_t&& pkt) -> std::optional<cbdc::buffer>; }; } #endif // OPENCBDC_TX_SRC_WATCHTOWER_CONTROLLER_H_
35.157143
70
0.667208
JonWiggins
a511d94e171c69837a8206f11ffbf82243384e79
43,768
cpp
C++
src/modules/devices/sy_devices.cpp
oyranos-cms/Synnefo
ca6b8cd7055b47fc64182a4e0d1a6dcf54781fe5
[ "BSD-2-Clause" ]
4
2015-04-26T19:38:56.000Z
2018-03-02T09:02:27.000Z
src/modules/devices/sy_devices.cpp
oyranos-cms/Synnefo
ca6b8cd7055b47fc64182a4e0d1a6dcf54781fe5
[ "BSD-2-Clause" ]
1
2017-10-31T21:49:28.000Z
2017-10-31T21:49:28.000Z
src/modules/devices/sy_devices.cpp
oyranos-cms/Synnefo
ca6b8cd7055b47fc64182a4e0d1a6dcf54781fe5
[ "BSD-2-Clause" ]
null
null
null
#include <QMessageBox> #include <QProgressDialog> #include <QFile> #include <QTime> #include <QTimer> #ifdef HAVE_QT_DBUS #include <QtDBus/QtDBus> #endif #include "sy_devices.h" #include "sy_devices_config.h" // Qt Designer code translation. #include "ui_sy_devices.h" #include <oyranos.h> #include <oyranos_devices.h> #include <oyFilterNode_s.h> #include <oyObject_s.h> #include <oyProfiles_s.h> #define i18n(t) QString(t) const char * sy_devices_module_name = "Devices"; class SySleep : public QThread { public: static void sleep(double seconds) { QThread::msleep((long unsigned int)(seconds*1000)); } }; // a bag to provide a otherwise hard to obtain link to the parent widget class SyDeviceItem : public QComboBox { public: SyDeviceItem () : QComboBox() {} void setParent ( SyDevicesItem * p ) {parent_ = p;} SyDevicesItem * getParent () {return parent_;} private: SyDevicesItem * parent_; }; SyDevicesModule::SyDevicesModule(QWidget * parent) : SyModule(parent) { setModuleName(sy_devices_module_name); setDescription("Set profiles for the devices on your system."); const char * name = NULL, * description = NULL, * tooltip = NULL; oyWidgetTitleGet( oyWIDGET_GROUP_DEVICES, NULL, &name, NULL, NULL ); oyWidgetDescriptionGet( oyWIDGET_GROUP_DEVICES, &description, 0 ); setModuleName(QString::fromLocal8Bit(name)); setDescription(QString::fromLocal8Bit(description)); this->setParent(parent); devicesConfig = new SyDevicesConfig(0, sy_devices_module_name); setConfigWidget( devicesConfig ); setEditable(true); currentDevice = 0; current_device_name = 0; current_device_class = 0; listModified = false; // avoid action on signals init = true; // select profiles matching actual capabilities icc_profile_flags = oyICCProfileSelectionFlagsFromOptions( OY_CMM_STD, "//" OY_TYPE_STD "/icc_color", NULL, 0 ); ui = new Ui::syDevicesWidget; ui->setupUi(this); ui->deviceList->setMouseTracking(true); // Set column width of device list. ui->deviceList->setColumnWidth(0, 400); /* i18n */ QString qs; oyWidgetTitleGet( oyWIDGET_DEVICES_RELATED, NULL, &name, &tooltip, NULL ); qs = QString::fromLocal8Bit(tooltip); ui->relatedDeviceCheckBox->setText(qs); oyWidgetDescriptionGet( oyWIDGET_DEVICES_RELATED, &description, 0 ); qs = QString::fromLocal8Bit(description); ui->relatedDeviceCheckBox->setToolTip(qs); oyWidgetTitleGet( oyWIDGET_GROUP_DEVICES_PROFILES_TAXI, NULL, &name, &tooltip, NULL ); qs = QString::fromLocal8Bit(tooltip); ui->taxiGroupBox->setTitle(qs); oyWidgetDescriptionGet( oyWIDGET_GROUP_DEVICES_PROFILES_TAXI, &description, 0 ); qs = QString::fromLocal8Bit(description); ui->deviceProfileTaxiDBComboBox->setToolTip(qs); oyWidgetTitleGet( oyWIDGET_TAXI_PROFILE_INSTALL, NULL, &name, &tooltip, NULL ); qs = QString::fromLocal8Bit(tooltip); ui->installProfileButton->setText(qs); // first select a device, then we can do something useful ui->installProfileButton->setEnabled(false); // Load directories and device listing. populateDeviceListing(); connect( ui->relatedDeviceCheckBox, SIGNAL(stateChanged( int )), this, SLOT( updateDeviceItems( int )) ); connect( ui->deviceList, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(changeDeviceItem(QTreeWidgetItem*,int)) ); connect( ui->installProfileButton, SIGNAL(clicked()), this, SLOT(installTaxiProfile())); init = false; #ifdef HAVE_QT_DBUS if( QDBusConnection::sessionBus().connect( QString(), "/org/libelektra/configuration", "org.libelektra", QString(), this, SLOT( configChanged( QString ) )) ) fprintf(stderr, "=================== connect devices to libelektra\n" ); #endif acceptDBusUpdate = true; } void SyDevicesModule::configChanged( QString msg ) { if(acceptDBusUpdate == false) return; if(strstr(msg.toLocal8Bit().data(), OY_DEVICE_STD)) { acceptDBusUpdate = false; QTimer::singleShot(250, this, SLOT( update() )); } }; void SyDevicesModule::update() { // clear the Oyranos settings cache oyGetPersistentStrings( NULL ); populateDeviceListing(); acceptDBusUpdate = true; } // small helper to obtain a profile from a device int syDeviceGetProfile( oyConfig_s * device, uint32_t icc_profile_flags, oyProfile_s ** profile ) { oyOptions_s * options = 0; oyOptions_SetFromString( &options, "//" OY_TYPE_STD "/config/command", "list", OY_CREATE_NEW ); oyOptions_SetFromString( &options, "//" OY_TYPE_STD "/config/icc_profile.x_color_region_target", "yes", OY_CREATE_NEW ); oyOptions_SetFromInt( &options, "///icc_profile_flags", icc_profile_flags, 0, OY_CREATE_NEW ); int error = oyDeviceAskProfile2( device, options, profile ); oyOptions_Release( &options ); return error; } void SyDevicesModule::updateProfileList( QTreeWidgetItem * selected_device, bool new_device ) { QWidget * w = ui->deviceList->itemWidget(selected_device, SyDevicesModule::ITEM_COMBOBOX); if(!w) return; QLayout * layout = w->layout(); QComboBox * profileAssociationCB = dynamic_cast<QComboBox*> (layout->itemAt(0)->widget()); if(!selected_device) { ui->deviceProfileTaxiDBComboBox->clear(); ui->deviceProfileTaxiDBComboBox->setEnabled(false); return; } // Don't count top parent items as a "selected device". QTreeWidgetItem * parent = selected_device->parent(); if (parent == NULL) { ui->deviceProfileTaxiDBComboBox->setEnabled(false); return; } // The user modifies the list, but clicks away from the selected device item. listModified = false; // If we click on a device item, the current device is stored and options are available. ui->deviceProfileTaxiDBComboBox->setEnabled(true); currentDevice = selected_device; // Convert QString to proper C string. QByteArray raw_string; SyDevicesItem * device_item = dynamic_cast<SyDevicesItem*>(selected_device); raw_string = device_item->getText(DEVICE_NAME).toLocal8Bit(); setCurrentDeviceName(raw_string.data()); char * device_class = 0; if(selected_device && selected_device->parent()) { QVariant v = selected_device->parent()->data( 0, Qt::UserRole ); QString qs_device_class = v.toString(); QByteArray raw_string; raw_string = qs_device_class.toLocal8Bit(); device_class = strdup(raw_string.data()); } // Change "Available Device Profiles" combobox to device-related profiles. if ( device_class ) { oyConfDomain_s * d = oyConfDomain_FromReg( device_class, 0 ); const char * icc_profile_class = oyConfDomain_GetText( d, "icc_profile_class", oyNAME_NICK ); setCurrentDeviceClass(device_class); if(icc_profile_class && strcmp(icc_profile_class,"display") == 0) populateDeviceComboBox(*profileAssociationCB, icSigDisplayClass, new_device); else if(icc_profile_class && strcmp(icc_profile_class,"output") == 0) populateDeviceComboBox(*profileAssociationCB, icSigOutputClass, new_device); else if(icc_profile_class && strcmp(icc_profile_class,"input") == 0) populateDeviceComboBox(*profileAssociationCB, icSigInputClass, new_device); oyConfDomain_Release( &d ); free(device_class); device_class = 0; } } // ******** SIGNAL/SLOT Functions ***************** void SyDevicesModule::updateDeviceItems() { updateDeviceItems(-1); } void SyDevicesModule::updateDeviceItems(int state) { if(init) return; init = true; // skip signals in changeDeviceItem if(ui->deviceList->isVisible()) for(int i = 0; i < ui->deviceList->topLevelItemCount(); ++i) { QTreeWidgetItem* device_class_item = ui->deviceList->topLevelItem(i); for(int j = 0; j < device_class_item->childCount(); ++j) { QTreeWidgetItem * deviceItem = device_class_item->child(j); updateProfileList( deviceItem, (state == -1) ? false : true ); //qWarning( "deviceList: [%d][%d] %d", i,j,state ); } } init = false; } void SyDevicesModule::changeDeviceItem(int pos) { if(acceptDBusUpdate == false) return; SyDeviceItem * combo = dynamic_cast<SyDeviceItem*>(sender()); if(combo && !init && pos >= 0) { SyDevicesItem * device_item = combo->getParent(); // unselect all tree items for(int i = 0; i < ui->deviceList->topLevelItemCount(); ++i) { QTreeWidgetItem* device_class_item = ui->deviceList->topLevelItem(i); for(int j = 0; j < device_class_item->childCount(); ++j) { QTreeWidgetItem * deviceItem = device_class_item->child(j); if(device_item != deviceItem && deviceItem->isSelected()) deviceItem->setSelected(false); } } // select the belonging widget to this combobox //device_item->setSelected(true); // get infos QVariant v = device_item->parent()->data( 0, Qt::UserRole ); QString qs = v.toString(); QByteArray raw_string = qs.toLocal8Bit(); char * device_class = strdup(raw_string.data()); v = combo->itemData(pos, Qt::UserRole); qs = v.toString(); raw_string = qs.toLocal8Bit(); char * profile_name = strdup(raw_string.data()); raw_string = device_item->getText(DEVICE_NAME).toLocal8Bit(); char * device_name = raw_string.data(); // set internal context setCurrentDeviceClass(device_class); setCurrentDeviceName(device_name); raw_string = device_item->getText(DEVICE_NAME).toLocal8Bit(); qWarning( "%d deviceItem: %d %s %s: %s", __LINE__,pos, device_class, raw_string.data(), profile_name); // set profile oySCOPE_e scope = oySCOPE_USER; if(ui->systemWideCheckBox->isChecked()) scope = oySCOPE_SYSTEM; assignProfile(QString(profile_name), scope); } } // NOTE Dynamic item information (for each item click) update might be removed. // When the user clicks on an item in the devices tree list. void SyDevicesModule::changeDeviceItem(QTreeWidgetItem * selected_device, int pos OY_UNUSED) { ui->deviceProfileTaxiDBComboBox->clear(); ui->installProfileButton->setEnabled(false); QWidget * w = ui->deviceList->itemWidget(selected_device, SyDevicesModule::ITEM_COMBOBOX); if(!w) { ui->deviceProfileTaxiDBComboBox->setEnabled(false); return; } currentDevice = selected_device; // Convert QString to proper C string. QByteArray raw_string; SyDevicesItem * device_item = dynamic_cast<SyDevicesItem*>(selected_device); raw_string = device_item->getText(DEVICE_NAME).toLocal8Bit(); const char * t = raw_string.data(); setCurrentDeviceName(t); char * device_class = 0; if(selected_device && selected_device->parent()) { QVariant v = selected_device->parent()->data( 0, Qt::UserRole ); QString qs_device_class = v.toString(); QByteArray raw_string; raw_string = qs_device_class.toLocal8Bit(); device_class = strdup(raw_string.data()); } // Change "Available Device Profiles" combobox to device-related profiles. if ( device_class ) setCurrentDeviceClass(device_class); // asynchronous Taxi DB query oyConfig_s * device = getCurrentDevice(); if(device) { ui->deviceProfileTaxiDBComboBox->clear(); // msgWidget->setMessageType(QMessageBox::Information); ui->msgWidget->setText(i18n("Looking for Device Profiles in Taxi DB ...")); while(init) SySleep::sleep(0.3); init = true; oyConfig_s * c = oyConfig_Copy( device, oyObject_New("oyConfig_s") ); TaxiLoad * loader = new TaxiLoad( c ); connect(loader, SIGNAL(finishedSignal( char *, oyConfigs_s * )), this, SLOT( getTaxiSlot( char*, oyConfigs_s* ))); loader->start(); /* clear */ oyConfig_Release( &device ); } else ui->deviceProfileTaxiDBComboBox->setEnabled(false); } void SyDevicesModule::installTaxiProfile() { // msgWidget->setMessageType(QMessageBox::Information); ui->msgWidget->setText(i18n("Downloading Profile from Taxi DB ...")); //oySCOPE_e scope = oySCOPE_USER; QTimer::singleShot(100, this, SLOT(downloadFromTaxiDB())); } void SyDevicesModule::downloadFromTaxiDB( ) { oyProfile_s * ip = 0; oyOptions_s * options = 0; char * id = (char*)calloc(sizeof(char), 1024); oySCOPE_e scope = oySCOPE_USER; snprintf(id, 1024, "%s/0", ui->deviceProfileTaxiDBComboBox->itemData(ui->deviceProfileTaxiDBComboBox->currentIndex()).toString().toStdString().c_str()); oyOptions_SetFromString(&options, "//" OY_TYPE_STD "/db/TAXI_id", id, OY_CREATE_NEW); ip = oyProfile_FromTaxiDB(options, NULL); oyOptions_Release(&options); oyOptions_SetFromString(&options, "////device", "1", OY_CREATE_NEW); if(ui->systemWideCheckBox->isChecked()) scope = oySCOPE_SYSTEM; int error = oyProfile_Install(ip, scope, options); if(!ip) { // msgWidget->setMessageType(QMessageBox::Information); ui->msgWidget->setText(i18n("No valid profile obtained")); QByteArray raw_string( i18n("No valid profile obtained").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); } if(error == oyERROR_DATA_AMBIGUITY) { // msgWidget->setMessageType(QMessageBox::Information); ui->msgWidget->setText(i18n("Profile already installed")); QByteArray raw_string( i18n("Profile already installed").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); setProfile( QString::fromLocal8Bit(oyProfile_GetFileName( ip, 0 )), scope ); updateProfileList( currentDevice, true ); } else if(error == oyERROR_DATA_WRITE) { // msgWidget->setMessageType(QMessageBox::Error); ui->msgWidget->setText(i18n("User Path can not be written")); QByteArray raw_string( i18n("User Path can not be written").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); } else if(error == oyCORRUPTED) { // msgWidget->setMessageType(QMessageBox::Error); ui->msgWidget->setText(i18n("Profile not useable")); QByteArray raw_string( i18n("Profile not useable").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); } else if(error > 0) { QString text = i18n("Internal error") + " - " + QString::number(error); QByteArray raw_string( text.toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); // msgWidget->setMessageType(QMessageBox::Error); ui->msgWidget->setText(text); } else { // msgWidget->setMessageType(QMessageBox::Positive); ui->msgWidget->setText(i18n("Profile has been installed")); setProfile( QString::fromLocal8Bit(oyProfile_GetFileName( ip, 0 )), scope ); updateProfileList( currentDevice, true ); } oyOptions_Release(&options); oyProfile_Release(&ip); } // obtain the Taxi DB query result void SyDevicesModule::getTaxiSlot( char * for_device, oyConfigs_s * taxi_devices ) { int count = oyConfigs_Count(taxi_devices); int32_t rank = 0; oyConfig_s * taxi_device; oyConfig_s * device = getCurrentDevice(); if(!oyConfig_FindString( device, "device_name", for_device) ) { QString text = i18n("wrong device") + " ... " + QString::fromLocal8Bit(for_device); if(oy_debug) ui->msgWidget->setText(text); goto clean_getTaxiSlot; } for (int i = 0; i < count; i++) { taxi_device = oyConfigs_Get( taxi_devices, i ); oyDeviceCompare(device, taxi_device, &rank); if (rank > 0) { QString text = "[" + QString::number(rank) + "]"; text += " "; text += oyConfig_FindString(taxi_device, "TAXI_profile_description", 0); ui->deviceProfileTaxiDBComboBox->addItem(text, oyConfig_FindString(taxi_device, "TAXI_id", 0)); } oyConfig_Release(&taxi_device); } // msgWidget->setMessageType(QMessageBox::Information); if (ui->deviceProfileTaxiDBComboBox->count() > 0) { ui->msgWidget->setText(i18n("You can select and install a profile")); ui->installProfileButton->setEnabled(true); ui->deviceProfileTaxiDBComboBox->setEnabled(true); } else { ui->msgWidget->setText(i18n("Not found any profile for the selected device in Taxi DB")); ui->installProfileButton->setEnabled(false); } clean_getTaxiSlot: oyConfigs_Release(&taxi_devices); oyConfig_Release(&device); if( for_device ) free( for_device ); init = false; } // Set a new Profile and update UI. void SyDevicesModule::setProfile( QString baseFileName, oySCOPE_e scope ) { //emit changed(true); listModified = true; assignProfile( baseFileName, scope ); // Convert QString to proper C string. QByteArray raw_string; raw_string = (currentDevice->text(DEVICE_NAME)).toLocal8Bit(); setCurrentDeviceName(raw_string.data()); // Update column width of device list. for(int i = 0; i < ui->deviceList->columnCount(); i++) ui->deviceList->resizeColumnToContents(i); // Get the device that the user selected. oyConfig_s * device = 0; device = getCurrentDevice(); oyConfig_Release(&device); } void SyDevicesModule::updateLocalProfileList(QTreeWidgetItem * selected_device, bool new_device OY_UNUSED) { if(!selected_device) { ui->deviceProfileTaxiDBComboBox->clear(); ui->deviceProfileTaxiDBComboBox->setEnabled(false); return; } // Don't count top parent items as a "selected device". if (selected_device->parent() == NULL) { ui->deviceProfileTaxiDBComboBox->setEnabled(false); return; } // The user modifies the list, but clicks away from the selected device item. listModified = false; // If we click on a device item, the current device is stored and options are available. ui->deviceProfileTaxiDBComboBox->setEnabled(true); currentDevice = selected_device; // Convert QString to proper C string. QByteArray raw_string; SyDevicesItem * device_item = dynamic_cast<SyDevicesItem*>(selected_device); raw_string = device_item->getText(DEVICE_NAME).toLocal8Bit(); setCurrentDeviceName(raw_string.data()); char * device_class = 0; if(selected_device && selected_device->parent()) { QVariant v = selected_device->parent()->data( 0, Qt::UserRole ); QString qs_device_class = v.toString(); QByteArray raw_string; raw_string = qs_device_class.toLocal8Bit(); device_class = strdup(raw_string.data()); } // Change "Available Device Profiles" combobox to device-related profiles. if ( device_class ) setCurrentDeviceClass(device_class); } // ************** Private Functions ******************** // Helper to obtain device string ID. QString getDeviceName(oyConfig_s * device) { const char * manufacturer = oyConfig_FindString( device,"manufacturer",0); const char * model = oyConfig_FindString( device, "model", 0); const char * serial = oyConfig_FindString( device, "serial", 0); return QString::fromLocal8Bit(manufacturer)+" "+QString::fromLocal8Bit(model)+" "+QString::fromLocal8Bit(serial); } int SyDevicesModule::installTaxiProfile(oyConfig_s * device) { int error = 0; QString taxiProfileName = downloadTaxiProfile(device); if (!taxiProfileName.isEmpty()) { QByteArray raw_string( taxiProfileName.toLocal8Bit() ); const char * profile_name = raw_string.data(); char * pn = strdup(profile_name); // Install the profile. oySCOPE_e scope = oySCOPE_USER; if(ui->systemWideCheckBox->isChecked()) scope = oySCOPE_SYSTEM; error = oyDeviceSetProfile(device, scope, pn); error = oyDeviceUnset(device); oyOptions_s * options = NULL; oyOptions_SetFromInt( &options, "//" OY_TYPE_STD "/icc_profile_flags", icc_profile_flags, 0, OY_CREATE_NEW ); oyOptions_SetFromString( &options, + "//" OY_TYPE_STD "/config/skip_ask_for_profile", "yes", OY_CREATE_NEW ); error = oyDeviceSetup(device, options); oyOptions_Release( &options ); } else error = 1; return error; } // Ping the Taxi server for recent profiles. int SyDevicesModule::checkProfileUpdates(oyConfig_s * device) { int is_installed = 0; QString taxiProfileDescription = checkRecentTaxiProfile(device); if(!taxiProfileDescription.isEmpty()) { int error, ret = 0; QMessageBox msgBox; msgBox.setText("A new profile is available to download for " + getDeviceName(device) + "."); msgBox.setInformativeText("Do you wish to install it?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); ret = msgBox.exec(); switch(ret) { case QMessageBox::Yes: { error = installTaxiProfile(device); if(!error) is_installed = 1; else { QMessageBox msgBox; msgBox.setText("Could not install " + getDeviceName(device) + "."); msgBox.setDefaultButton(QMessageBox::Yes); ret = msgBox.exec(); } break; } case QMessageBox::No: break; default: break; } } return is_installed; } // General function to detect and retrieve devices via the Oyranos CMS backend. int SyDevicesModule::detectDevices(const char * device_type) { int error = 0; oyConfigs_s * device_list = 0; oyOptions_s * options = oyOptions_New(0); oyConfDomain_s * d = oyConfDomain_FromReg( device_type, 0 ); const char * reg_app = strrchr(device_type,'/')+1; const char * device_class = oyConfDomain_GetText( d, "device_class", oyNAME_NICK ); const char * device_class_ui = oyConfDomain_GetText( d, "device_class", oyNAME_NAME ); oyOptions_SetFromString(&options, "//" OY_TYPE_STD "/config/command", "properties", OY_CREATE_NEW); oyDevicesGet( OY_TYPE_STD, reg_app, 0, &device_list); int j = 0, device_num = oyConfigs_Count(device_list); // Must have at least one device detected to add to the list. if(device_num > 0) { // Set up Synnefo gui "logistics" for a specified device. QTreeWidgetItem * device_class_item = new QTreeWidgetItem; device_class_item->setText( ITEM_MAIN, QString::fromLocal8Bit(device_class_ui) ); QVariant v( device_class ); device_class_item->setData( 0, Qt::UserRole, v ); ui->deviceList->insertTopLevelItem( ITEM_MAIN, device_class_item ); QIcon device_icon; QSize icon_size(64, 64); QString iconPath = QString(":/resources/") + QString::fromLocal8Bit(device_class) + ".png"; device_icon.addFile( iconPath.toLower(), icon_size , QIcon::Normal, QIcon::On); QString taxiProfileDescription = ""; // Traverse through the available devices for (j = 0; j < device_num; j++) { QString deviceItemString, deviceProfileDescription; oyConfig_s * device = oyConfigs_Get(device_list, j); error = oyDeviceBackendCall(device, options); const char * device_manufacturer = 0; const char * device_model = 0; const char * device_serial = 0; char * device_designation = 0; const char * profile_filename = 0; oyProfile_s * profile = 0; device_manufacturer = oyConfig_FindString( device,"manufacturer",0); device_model = oyConfig_FindString( device, "model", 0); device_serial = oyConfig_FindString( device, "serial", 0); // Get device designation. error = oyDeviceGetInfo(device, oyNAME_NICK, 0, &device_designation, malloc); setCurrentDeviceName(device_designation); setCurrentDeviceClass(device_class); // A printer will only take a "device model" if (strcmp(device_class,"printer") != 0) { deviceItemString.append(QString::fromLocal8Bit(device_manufacturer)); deviceItemString.append(" "); } deviceItemString.append(QString::fromLocal8Bit(device_model)); if(device_serial) { deviceItemString.append(" "); deviceItemString.append(QString::fromLocal8Bit(device_serial)); } // TESTING Check device for Taxi updates. //if (strcmp(device_class, "monitor") == 0) // checkProfileUpdates(device); error = syDeviceGetProfile(device, icc_profile_flags, &profile); profile_filename = oyProfile_GetFileName(profile, 0); SyDevicesItem * deviceItem = new SyDevicesItem(0); if (profile_filename == NULL) { deviceProfileDescription = QString::fromLocal8Bit( oyProfile_GetText( profile, oyNAME_DESCRIPTION ) ); if(!deviceProfileDescription.count()) deviceProfileDescription = "(No Profile Installed!)"; profile_filename = "------"; } else deviceProfileDescription = convertFilenameToDescription(QString::fromLocal8Bit(profile_filename)); deviceItem->setIcon( ITEM_MAIN, device_icon ); deviceItem->addText(DEVICE_DESCRIPTION, deviceItemString); deviceItem->addText(DEVICE_NAME, QString::fromLocal8Bit(device_designation)); deviceItem->addText(PROFILE_DESCRIPTION, deviceProfileDescription); deviceItem->addText(PROFILE_FILENAME, QString::fromLocal8Bit(profile_filename)); deviceItem->setDevice(device); deviceItem->refreshText(); fprintf( stderr, "###### %s|%s with %s|%s\n", device_designation, deviceItemString.toLocal8Bit().data(), deviceProfileDescription.toLocal8Bit().data(), profile_filename); // add association combo box in tree widget. SyDeviceItem * profileAssociationCB = new SyDeviceItem(); connect( profileAssociationCB, SIGNAL(currentIndexChanged( int )), this, SLOT( changeDeviceItem( int )) ); QBoxLayout *layout = new QBoxLayout(QBoxLayout::LeftToRight); layout->addWidget (profileAssociationCB); profileAssociationCB->setParent(deviceItem); QWidget * w = new QWidget(); w->setLayout(layout); device_class_item->addChild( deviceItem ); ui->deviceList->setItemWidget( deviceItem, ITEM_COMBOBOX, w); updateProfileList( deviceItem, true ); oyConfig_Release( &device ); oyProfile_Release( &profile ); } } else error = -1; oyOptions_Release ( &options ); oyConfigs_Release ( &device_list ); oyConfDomain_Release( &d ); return error; } // Populate devices and profiles. void SyDevicesModule::populateDeviceListing() { ui->deviceList->clear(); // TODO Work out a solution to use raw/camera stuff. uint32_t count = 0, i = 1, * rank_list = 0; char ** texts = 0; // get all configuration filters oyConfigDomainList( "//" OY_TYPE_STD "/device/config.icc_profile", &texts, &count, &rank_list ,0 ); for (i = 0; i < count; i++) { detectDevices( texts[i] ); free( texts[i] ); } free( texts ); // Expand list for user. ui->deviceList->expandAll(); } void setItem( QComboBox & itemComboBox, int index, int count, QString text, QString data ) { if(index < count) { if(itemComboBox.itemText( index ) != text) { itemComboBox.setItemText( index, text ); itemComboBox.setItemData( index, data ); } } else itemComboBox.addItem( text, data ); } // Populate "Assign Profile" combobox. Depending on the device selected, the profile list will vary. void SyDevicesModule::populateDeviceComboBox( QComboBox & itemComboBox, unsigned int sig, bool new_device ) { int size, i, current = -1, current_tmp = -1, pos = 0; oyProfile_s * profile = 0, * temp_profile = 0; oyProfiles_s * patterns = oyProfiles_New(0), * iccs = 0; oyConfig_s * device = getCurrentDevice(); const char * profile_file_name = 0; icProfileClassSignature deviceSignature = (icProfileClassSignature) sig; syDeviceGetProfile( device, icc_profile_flags, &profile ); /* reget profile */ QString current_text = itemComboBox.currentText(); const char * desc = oyProfile_GetText( profile, oyNAME_DESCRIPTION ); if(new_device == false && (current_text.contains(QString::fromLocal8Bit(desc)) || itemComboBox.currentIndex() == -1 ) ) { oyProfile_Release( &profile ); oyConfig_Release( &device ); return; } profile_file_name = oyProfile_GetFileName( profile, 0 ); oyProfile_s * pattern_profile = oyProfile_FromSignature( deviceSignature, oySIGNATURE_CLASS, 0 ); oyProfiles_MoveIn( patterns, &pattern_profile, -1 ); iccs = oyProfiles_Create( patterns, icc_profile_flags, 0 ); oyProfiles_Release( &patterns ); oyProfile_Release( &pattern_profile ); QString getProfileDescription; size = oyProfiles_Count(iccs); int32_t * rank_list = (int32_t*) malloc( oyProfiles_Count(iccs) * sizeof(int32_t) ); oyProfiles_DeviceRank( iccs, device, rank_list ); size = oyProfiles_Count(iccs); //itemComboBox.clear(); Qt::CheckState show_only_device_related = ui->relatedDeviceCheckBox->checkState(); int empty_added = -1; for( i = 0; i < size; ++i) { const char * temp_profile_file_name; temp_profile = oyProfiles_Get( iccs, i ); // show rank number getProfileDescription = "[" + QString::number(rank_list[i]) + "] "; getProfileDescription += QString::fromLocal8Bit( oyProfile_GetText( temp_profile, oyNAME_DESCRIPTION ) ); temp_profile_file_name = oyProfile_GetFileName( temp_profile, 0 ); current_tmp = -1; if(profile_file_name && temp_profile_file_name && strcmp( profile_file_name, temp_profile_file_name ) == 0) current_tmp = pos; if(current == -1 && current_tmp != -1) current = current_tmp; if(empty_added == -1 && rank_list[i] < 1) { setItem( itemComboBox, pos, itemComboBox.count(), i18n("automatic"), QString("") ); empty_added = pos; if(current != -1 && current == pos) ++current; ++pos; } if(show_only_device_related == Qt::Unchecked || rank_list[i] > 0 || current_tmp != -1) { getProfileDescription.append(" ("); getProfileDescription.append(QString::fromLocal8Bit(temp_profile_file_name)); getProfileDescription.append(")"); setItem( itemComboBox, pos, itemComboBox.count(), getProfileDescription, QString::fromLocal8Bit(temp_profile_file_name) ); ++pos; } oyProfile_Release( &temp_profile ); } if(empty_added == -1) { setItem( itemComboBox, pos, itemComboBox.count(), i18n("automatic"), QString("") ); ++pos; if(current == -1 && current_tmp != -1) current = pos; } if(current == -1 && profile_file_name) { getProfileDescription = QString::fromLocal8Bit( oyProfile_GetText( profile, oyNAME_DESCRIPTION ) ); getProfileDescription.append("\t("); getProfileDescription.append(profile_file_name); getProfileDescription.append(")"); setItem( itemComboBox, pos, itemComboBox.count(), getProfileDescription, QString::fromLocal8Bit("") ); current = pos; } for(int i = itemComboBox.count()-1; pos < itemComboBox.count(); --i) itemComboBox.removeItem( i ); itemComboBox.setCurrentIndex( current ); oyConfig_Release( &device ); oyProfile_Release( &profile ); oyProfiles_Release( &iccs ); free( rank_list ); } oyConfig_s * SyDevicesModule::getCurrentDevice( void ) { oyConfig_s * device = 0; int error= 0; oyOptions_s * options = 0; oyOptions_SetFromString( &options, "//" OY_TYPE_STD "/config/command", "properties", OY_CREATE_NEW ); oyOptions_SetFromString( &options, "//" OY_TYPE_STD "/config/icc_profile.x_color_region_target", "yes", OY_CREATE_NEW ); if(current_device_class && current_device_name) error = oyDeviceGet( OY_TYPE_STD, current_device_class, current_device_name, options, &device ); Q_UNUSED(error); /* clear */ oyOptions_Release( &options ); return device; } void SyDevicesModule::assignProfile( QString profile_name, oySCOPE_e scope ) { oyProfile_s * profile = 0; QString description; // If current device pointer points to a MONITOR item, save default profile to Oyranos. { oyConfig_s * device = getCurrentDevice(); QByteArray raw_string( profile_name.toLocal8Bit() ); const char * profilename = raw_string.data(); char * pn = strdup(profilename); /* store a existing profile in DB */ if(strlen(pn) && QString::localeAwareCompare( QString(pn), i18n("automatic"))) oyDeviceSetProfile ( device, scope, pn ); oyDeviceUnset( device ); /* unset the device */ /* completly unset the actual profile from DB */ if(!strlen(pn) || !QString::localeAwareCompare(QString(pn), i18n("automatic"))) { oyConfig_EraseFromDB( device, scope ); oyConfig_Release( &device ); /* reopen the device to forget about the "profile_name" key */ device = getCurrentDevice(); } oyOptions_s * options = NULL; oyOptions_SetFromInt( &options, "//" OY_TYPE_STD "/icc_profile_flags", icc_profile_flags, 0, OY_CREATE_NEW ); oyOptions_SetFromString( &options, + "//" OY_TYPE_STD "/config/skip_ask_for_profile", "yes", OY_CREATE_NEW ); oyDeviceSetup( device, options ); /* reinitialise */ oyOptions_Release( &options ); /* compiz needs some time to exchange the profiles, immediately we would get the old colour server profile */ SySleep::sleep(0.3); syDeviceGetProfile( device, icc_profile_flags, &profile ); /* reget profile */ /* clear */ oyConfig_Release( &device ); if(pn) { free(pn); pn = 0; } } // Convert profile into description name... description = QString::fromLocal8Bit( oyProfile_GetText( profile, oyNAME_DESCRIPTION) ); if(!description.count()) description = "(No Profile Installed!)"; if(!profile_name.count()) profile_name = "------"; } /* ************* Oyranos Taxi Code ************* */ // TESTING Code to verify if recent Taxi profile is already installed. int isRecentProfile(oyConfig_s * device, oyConfig_s * taxi_device) { int error, is_recent = 0; char * current_profile = 0; oyProfile_s * p1 = 0; oyProfile_s * p2 = 0; oyOptions_s * options = 0; oyDeviceProfileFromDB(device, &current_profile, malloc); QString taxiIdString = QString(oyConfig_FindString(taxi_device, "TAXI_id",0)) + "/0"; QByteArray raw_string( taxiIdString.toLocal8Bit() ); error = oyOptions_SetFromString(&options, "//" OY_TYPE_STD "/argv/TAXI_id", raw_string.data(), OY_CREATE_NEW); if(!error) { p1 = oyProfile_FromTaxiDB(options, NULL); p2 = oyProfile_FromFile(current_profile, 0, 0); if(oyProfile_Equal(p1, p2)) is_recent = 1; oyProfile_Release(&p1); oyProfile_Release(&p2); free(current_profile); current_profile = 0; } oyOptions_Release(&options); return is_recent; } int compareRanks ( const void * rank1, const void * rank2 ) {int32_t *r1=(int32_t*)rank1, *r2=(int32_t*)rank2; if(r1[1] < r2[1]) return 1; else return 0;} // Helper function to get 'best-ranking' profile from the Taxi server. oyConfig_s * getTaxiBestFit(oyConfig_s * device) { int n, i = 0; int32_t * ranks; oyConfig_s * taxi_dev; oyConfigs_s * devices = 0; oyOptions_s * options = NULL; oyOptions_SetFromString(&options, "//" OY_TYPE_STD "/config/command", "properties", OY_CREATE_NEW); oyDevicesFromTaxiDB(device, options, &devices, NULL); n = oyConfigs_Count(devices); if (n) { ranks = new int32_t[n*2+1]; for(i = 0; i < n; ++i) { taxi_dev = oyConfigs_Get(devices, i); ranks[2*i+0] = i; oyDeviceCompare(device, taxi_dev, &ranks[2*i+1]); oyConfig_Release(&taxi_dev); } // TODO Fix ranking so that it uses C++ sorting algorithm instead. qsort(ranks, n, sizeof(int32_t)*2, compareRanks); // Obtain the best-ranked device profile (0). taxi_dev = oyConfigs_Get(devices, ranks[0]); delete[] ranks; } // Verify if we already have the Taxi profile installed. if(isRecentProfile(device, taxi_dev)) { oyConfig_Release(&taxi_dev); taxi_dev = 0; } oyConfigs_Release(&devices); oyOptions_Release(&options); return taxi_dev; } // Obtain either profile description or the taxi_id of a Taxi device (Server). QString SyDevicesModule::getTaxiString(oyConfig_s * device, const char * oy_taxi_string) { QString str = ""; oyConfig_s * taxi_dev = 0; taxi_dev = getTaxiBestFit(device); if(taxi_dev) { str = oyConfig_FindString(taxi_dev, oy_taxi_string, 0); oyConfig_Release(&taxi_dev); } return str; } // Obtain the profile description of the "best fit" profile from Taxi. QString SyDevicesModule::checkRecentTaxiProfile(oyConfig_s * device) { QString profileDescription = getTaxiString(device, "TAXI_profile_description"); return profileDescription; } // Download a profile from Taxi server and return its filename. QString SyDevicesModule::downloadTaxiProfile(oyConfig_s * device) { QString fileName = ""; oyProfile_s * ip = 0; oyOptions_s * options = NULL; oySCOPE_e scope = oySCOPE_USER; int error = 0; QString taxiIdString = QString( getTaxiString(device, "TAXI_id") + "/0" ); QByteArray raw_string( taxiIdString.toLocal8Bit() ); error = oyOptions_SetFromString(&options, "//" OY_TYPE_STD "/argv/TAXI_id", raw_string.data(), OY_CREATE_NEW); // Download the taxi profile. if(!error) { ip = oyProfile_FromTaxiDB(options, NULL); oyOptions_SetFromString(&options, "////device", "1", OY_CREATE_NEW); if(ui->systemWideCheckBox->isChecked()) scope = oySCOPE_SYSTEM; error = oyProfile_Install(ip, scope, options); } if(!ip) { // msgWidget->setMessageType(QMessageBox::Information); ui->msgWidget->setText(i18n("No valid profile obtained")); QByteArray raw_string( i18n("No valid profile obtained").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); } if(error == oyERROR_DATA_AMBIGUITY) { // msgWidget->setMessageType(QMessageBox::Information); ui->msgWidget->setText(i18n("Profile already installed")); QByteArray raw_string( i18n("Profile already installed").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); setProfile( QString::fromLocal8Bit(oyProfile_GetFileName( ip, 0 )), scope ); updateProfileList( currentDevice, true ); } else if(error == oyERROR_DATA_WRITE) { // msgWidget->setMessageType(QMessageBox::Error); ui->msgWidget->setText(i18n("User Path can not be written")); QByteArray raw_string( i18n("User Path can not be written").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); } else if(error == oyCORRUPTED) { // msgWidget->setMessageType(QMessageBox::Error); ui->msgWidget->setText(i18n("Profile not useable")); QByteArray raw_string( i18n("Profile not useable").toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); } else if(error > 0) { QString text = i18n("Internal error") + " - " + QString::number(error); QByteArray raw_string( text.toLocal8Bit() ); oyMessageFunc_p( oyMSG_ERROR, NULL, "%s", raw_string.data()); // msgWidget->setMessageType(QMessageBox::Error); ui->msgWidget->setText(text); } else { // msgWidget->setMessageType(QMessageBox::Positive); ui->msgWidget->setText(i18n("Profile has been installed")); setProfile( QString::fromLocal8Bit(oyProfile_GetFileName( ip, 0 )), scope ); updateProfileList( currentDevice, true ); } oyOptions_Release(&options); return fileName; } /* ************* Oyranos DB Settings ************* */ // This is so we can obtain a profile name description from a profile file name. QString SyDevicesModule::convertFilenameToDescription(QString profileFilename) { QString profileDescriptionName; oyProfile_s * profile; QByteArray raw_string( profileFilename.toLocal8Bit() ); profile = oyProfile_FromFile( raw_string.data(), 0, 0); profileDescriptionName = QString::fromLocal8Bit( oyProfile_GetText( profile, oyNAME_DESCRIPTION ) ); oyProfile_Release( &profile ); return profileDescriptionName; } SyDevicesModule::~SyDevicesModule() { #ifdef HAVE_QT_DBUS if( QDBusConnection::sessionBus().disconnect( QString(), "/org/libelektra/configuration", "org.libelektra", QString(), this, SLOT( configChanged( QString ) )) ) fprintf(stderr, "=================== disconnect devices from libelektra\n" ); #endif delete ui; } void TaxiLoad::run() { oyConfigs_s * taxi_devices = 0; char * device_name = 0; if(d_) { oyDevicesFromTaxiDB( d_, 0, &taxi_devices, 0); device_name = strdup(oyConfig_FindString( d_, "device_name", NULL )); } oyConfig_Release( &d_ ); emit finishedSignal( device_name, taxi_devices ); }
34.220485
182
0.637361
oyranos-cms
a512cb5c796fbcb21de13153973275ff68d38143
2,134
hpp
C++
three/scenes/scene.hpp
Lecrapouille/three_cpp
5c3b4f4ca02bda6af232898c17e62caf8f887aa0
[ "MIT" ]
null
null
null
three/scenes/scene.hpp
Lecrapouille/three_cpp
5c3b4f4ca02bda6af232898c17e62caf8f887aa0
[ "MIT" ]
null
null
null
three/scenes/scene.hpp
Lecrapouille/three_cpp
5c3b4f4ca02bda6af232898c17e62caf8f887aa0
[ "MIT" ]
null
null
null
#ifndef THREE_SCENE_HPP #define THREE_SCENE_HPP #include <three/common.hpp> #include <three/core/object3d.hpp> #include <three/renderers/renderables/renderable_object.hpp> namespace three { class Scene : public Object3D { public: typedef std::shared_ptr<Scene> Ptr; static Ptr create() { return make_shared<Scene>(); } ///////////////////////////////////////////////////////////////////////// IFog::Ptr fog; Material* overrideMaterial; bool matrixAutoUpdate; ///////////////////////////////////////////////////////////////////////// struct GLObject : RenderableObject { explicit GLObject(GeometryBuffer* buffer = nullptr, Object3D* object = nullptr, bool render = false, Material* opaque = nullptr, Material* transparent = nullptr, float z = 0.f) : RenderableObject(object, z), buffer(buffer), render(render), opaque(opaque), transparent(transparent) {} GeometryBuffer* buffer; bool render; Material* opaque; Material* transparent; }; std::vector<GLObject> __glObjects; std::vector<GLObject> __glObjectsImmediate; std::vector<Object3D*> __glSprites; std::vector<Object3D*> __glFlares; std::vector<Object3D*> __objects; std::vector<Light*> __lights; std::vector<Object3D::Ptr> __objectsAdded; std::vector<Object3D::Ptr> __objectsRemoved; ////////////////////////////////////////////////////////////////////////// protected: THREE_DECL virtual void __addObject(const Object3D::Ptr& object); THREE_DECL virtual void __removeObject(const Object3D::Ptr& object); protected: THREE_DECL Scene(); THREE_DECL ~Scene(); virtual THREE::Type type() const { return THREE::Scene; } THREE_DECL virtual void visit(Visitor& v); THREE_DECL virtual void visit(ConstVisitor& v) const; }; } // namespace three #if defined(THREE_HEADER_ONLY) # include <three/scenes/impl/scene.ipp> #endif // defined(THREE_HEADER_ONLY) #endif // THREE_SCENE_HPP
27.714286
118
0.584817
Lecrapouille
a517dc1e9093c1ec8c03e1815ab48fb87e92dfd4
3,903
cpp
C++
src/SP2C/SPC_Mat33.cpp
Kareus/SP2C
74a3cdb89bc5b2414277bf87e7c6a2b9d0313990
[ "MIT" ]
null
null
null
src/SP2C/SPC_Mat33.cpp
Kareus/SP2C
74a3cdb89bc5b2414277bf87e7c6a2b9d0313990
[ "MIT" ]
null
null
null
src/SP2C/SPC_Mat33.cpp
Kareus/SP2C
74a3cdb89bc5b2414277bf87e7c6a2b9d0313990
[ "MIT" ]
null
null
null
#include <SP2C/SPC_Mat33.h> namespace SP2C { SPC_Mat33::SPC_Mat33(double m00, double m01, double m02, double m10, double m11, double m12, double m20, double m21, double m22) { m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; } SPC_Mat33::SPC_Mat33(double** mat) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m[i][j] = mat[i][j]; } SPC_Mat33::SPC_Mat33() { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m[i][j] = 0; } SPC_Mat33 SPC_Mat33::operator+(SPC_Mat33 mat) { SPC_Mat33 ret; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) ret.m[i][j] = m[i][j] + mat.m[i][j]; return ret; } SPC_Mat33 SPC_Mat33::operator-(SPC_Mat33 mat) { SPC_Mat33 ret; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) ret.m[i][j] = m[i][j] - mat.m[i][j]; return ret; } SPC_Mat33 SPC_Mat33::operator*(double k) { SPC_Mat33 ret; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) ret.m[i][j] = m[i][j] * k; return ret; } SPC_Mat33 SPC_Mat33::operator*(SPC_Mat33 mat) { SPC_Mat33 ret; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 3; k++) ret.m[i][j] += m[i][k] * mat.m[k][j]; return ret; } Vec2 SPC_Mat33::operator*(Vec2 v) { return Vec2(m[0][0] * v.x + m[0][1] * v.y + m[0][2], m[1][0] * v.x + m[1][1] * v.y + m[1][2]); } SPC_Mat33& SPC_Mat33::operator+=(SPC_Mat33 mat) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m[i][j] += mat.m[i][j]; return *this; } SPC_Mat33& SPC_Mat33::operator-=(SPC_Mat33 mat) { ; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m[i][j] -= mat.m[i][j]; return *this; } SPC_Mat33& SPC_Mat33::operator*=(double k) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m[i][j] *= k; return *this; } SPC_Mat33& SPC_Mat33::operator=(SPC_Mat33 mat) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m[i][j] = mat.m[i][j]; return *this; } SPC_Mat33& SPC_Mat33::operator*=(SPC_Mat33 mat) { SPC_Mat33 val; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 3; k++) val.m[i][j] += m[i][k] * mat.m[k][j]; *this = val; return *this; } SPC_Mat33 SPC_Mat33::Transpose() { SPC_Mat33 ret; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) ret.m[i][j] = m[j][i]; return ret; } double SPC_Mat33::Determinant() { return m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); } SPC_Mat33 SPC_Mat33::Inverse() { double det = Determinant(); assert(det != 0); double invdet = 1 / det; SPC_Mat33 ret; ret.m[0][0] = (m[1][1] * m[2][2] - m[2][1] * m[1][2]) * invdet; ret.m[0][1] = (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * invdet; ret.m[0][2] = (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * invdet; ret.m[1][0] = (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * invdet; ret.m[1][1] = (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * invdet; ret.m[1][2] = (m[1][0] * m[0][2] - m[0][0] * m[1][2]) * invdet; ret.m[2][0] = (m[1][0] * m[2][1] - m[2][0] * m[1][1]) * invdet; ret.m[2][1] = (m[2][0] * m[0][1] - m[0][0] * m[2][1]) * invdet; ret.m[2][2] = (m[0][0] * m[1][1] - m[1][0] * m[0][1]) * invdet; return ret; } void SPC_Mat33::Translate(double x, double y) { m[0][2] += x; m[1][2] += y; } void SPC_Mat33::Translate(Vec2 p) { m[0][2] += p.x; m[1][2] += p.y; } void SPC_Mat33::Scale(double k) { m[0][0] *= k; m[1][1] *= k; } void SPC_Mat33::Rotate(double deg) { double cos = std::cos(deg * Const::RAD); double sin = std::sin(deg * Const::RAD); *this *= SPC_Mat33(cos, -sin, 0, sin, cos, 0, 0, 0, 0); } }
20.118557
129
0.472457
Kareus
a51aa56632abd43e5715092b750f553695b21ef0
15,591
cpp
C++
src/effects/shadows/SkSpotShadowMaskFilter.cpp
picmonkey/skia
8bc3eecfc3f688c504c64d676e7de9b2f938a866
[ "BSD-3-Clause" ]
null
null
null
src/effects/shadows/SkSpotShadowMaskFilter.cpp
picmonkey/skia
8bc3eecfc3f688c504c64d676e7de9b2f938a866
[ "BSD-3-Clause" ]
4
2016-04-08T23:04:42.000Z
2017-06-16T21:46:02.000Z
src/effects/shadows/SkSpotShadowMaskFilter.cpp
picmonkey/skia
8bc3eecfc3f688c504c64d676e7de9b2f938a866
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSpotShadowMaskFilter.h" #include "SkReadBuffer.h" #include "SkStringUtils.h" #include "SkWriteBuffer.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrRenderTargetContext.h" #include "GrFragmentProcessor.h" #include "GrStyle.h" #include "GrTexture.h" #include "GrTextureProxy.h" #include "SkStrokeRec.h" #endif class SkSpotShadowMaskFilterImpl : public SkMaskFilter { public: SkSpotShadowMaskFilterImpl(SkScalar occluderHeight, const SkPoint3& lightPos, SkScalar lightRadius, SkScalar spotAlpha, uint32_t flags); // overrides from SkMaskFilter SkMask::Format getFormat() const override; bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&, SkIPoint* margin) const override; #if SK_SUPPORT_GPU bool canFilterMaskGPU(const SkRRect& devRRect, const SkIRect& clipBounds, const SkMatrix& ctm, SkRect* maskRect) const override; bool directFilterMaskGPU(GrContext*, GrRenderTargetContext* drawContext, GrPaint&&, const GrClip&, const SkMatrix& viewMatrix, const SkStrokeRec& strokeRec, const SkPath& path) const override; bool directFilterRRectMaskGPU(GrContext*, GrRenderTargetContext* drawContext, GrPaint&&, const GrClip&, const SkMatrix& viewMatrix, const SkStrokeRec& strokeRec, const SkRRect& rrect, const SkRRect& devRRect) const override; sk_sp<GrTextureProxy> filterMaskGPU(GrContext*, sk_sp<GrTextureProxy> srcProxy, const SkMatrix& ctm, const SkIRect& maskRect) const override; #endif void computeFastBounds(const SkRect&, SkRect*) const override; SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkSpotShadowMaskFilterImpl) private: SkScalar fOccluderHeight; SkPoint3 fLightPos; SkScalar fLightRadius; SkScalar fSpotAlpha; uint32_t fFlags; SkSpotShadowMaskFilterImpl(SkReadBuffer&); void flatten(SkWriteBuffer&) const override; friend class SkSpotShadowMaskFilter; typedef SkMaskFilter INHERITED; }; sk_sp<SkMaskFilter> SkSpotShadowMaskFilter::Make(SkScalar occluderHeight, const SkPoint3& lightPos, SkScalar lightRadius, SkScalar spotAlpha, uint32_t flags) { // add some param checks here for early exit return sk_sp<SkMaskFilter>(new SkSpotShadowMaskFilterImpl(occluderHeight, lightPos, lightRadius, spotAlpha, flags)); } /////////////////////////////////////////////////////////////////////////////////////////////////// SkSpotShadowMaskFilterImpl::SkSpotShadowMaskFilterImpl(SkScalar occluderHeight, const SkPoint3& lightPos, SkScalar lightRadius, SkScalar spotAlpha, uint32_t flags) : fOccluderHeight(occluderHeight) , fLightPos(lightPos) , fLightRadius(lightRadius) , fSpotAlpha(spotAlpha) , fFlags(flags) { SkASSERT(fOccluderHeight > 0); SkASSERT(fLightPos.z() > 0 && fLightPos.z() > fOccluderHeight); SkASSERT(fLightRadius > 0); SkASSERT(fSpotAlpha >= 0); } SkMask::Format SkSpotShadowMaskFilterImpl::getFormat() const { return SkMask::kA8_Format; } bool SkSpotShadowMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src, const SkMatrix& matrix, SkIPoint* margin) const { // TODO something return false; } void SkSpotShadowMaskFilterImpl::computeFastBounds(const SkRect& src, SkRect* dst) const { // TODO compute based on ambient + spot data dst->set(src.fLeft, src.fTop, src.fRight, src.fBottom); } sk_sp<SkFlattenable> SkSpotShadowMaskFilterImpl::CreateProc(SkReadBuffer& buffer) { const SkScalar occluderHeight = buffer.readScalar(); const SkScalar lightX = buffer.readScalar(); const SkScalar lightY = buffer.readScalar(); const SkScalar lightZ = buffer.readScalar(); const SkPoint3 lightPos = SkPoint3::Make(lightX, lightY, lightZ); const SkScalar lightRadius = buffer.readScalar(); const SkScalar spotAlpha = buffer.readScalar(); const uint32_t flags = buffer.readUInt(); return SkSpotShadowMaskFilter::Make(occluderHeight, lightPos, lightRadius, spotAlpha, flags); } void SkSpotShadowMaskFilterImpl::flatten(SkWriteBuffer& buffer) const { buffer.writeScalar(fOccluderHeight); buffer.writeScalar(fLightPos.fX); buffer.writeScalar(fLightPos.fY); buffer.writeScalar(fLightPos.fZ); buffer.writeScalar(fLightRadius); buffer.writeScalar(fSpotAlpha); buffer.writeUInt(fFlags); } #if SK_SUPPORT_GPU /////////////////////////////////////////////////////////////////////////////////////////////////// bool SkSpotShadowMaskFilterImpl::canFilterMaskGPU(const SkRRect& devRRect, const SkIRect& clipBounds, const SkMatrix& ctm, SkRect* maskRect) const { // TODO *maskRect = devRRect.rect(); return true; } bool SkSpotShadowMaskFilterImpl::directFilterMaskGPU(GrContext* context, GrRenderTargetContext* rtContext, GrPaint&& paint, const GrClip& clip, const SkMatrix& viewMatrix, const SkStrokeRec& strokeRec, const SkPath& path) const { SkASSERT(rtContext); // TODO: this will not handle local coordinates properly SkRect rect; SkRRect rrect; if (path.isOval(&rect) && SkScalarNearlyEqual(rect.width(), rect.height())) { rrect = SkRRect::MakeOval(rect); return this->directFilterRRectMaskGPU(context, rtContext, std::move(paint), clip, SkMatrix::I(), strokeRec, rrect, rrect); } else if (path.isRect(&rect)) { rrect = SkRRect::MakeRect(rect); return this->directFilterRRectMaskGPU(context, rtContext, std::move(paint), clip, SkMatrix::I(), strokeRec, rrect, rrect); } else if (path.isRRect(&rrect) && rrect.isSimpleCircular()) { return this->directFilterRRectMaskGPU(context, rtContext, std::move(paint), clip, SkMatrix::I(), strokeRec, rrect, rrect); } return false; } bool SkSpotShadowMaskFilterImpl::directFilterRRectMaskGPU(GrContext*, GrRenderTargetContext* rtContext, GrPaint&& paint, const GrClip& clip, const SkMatrix& viewMatrix, const SkStrokeRec& strokeRec, const SkRRect& rrect, const SkRRect& devRRect) const { // Fast path only supports filled rrects for now. // TODO: fill and stroke as well. if (SkStrokeRec::kFill_Style != strokeRec.getStyle()) { return false; } // These should have been checked by the caller. // Fast path only supports simple rrects with circular corners. SkASSERT(devRRect.isRect() || devRRect.isCircle() || (devRRect.isSimple() && devRRect.allCornersCircular())); // Fast path only supports uniform scale. SkASSERT(viewMatrix.isSimilarity()); // Assume we have positive alpha SkASSERT(fSpotAlpha > 0); // 1/scale SkScalar devToSrcScale = viewMatrix.isScaleTranslate() ? SkScalarInvert(viewMatrix[SkMatrix::kMScaleX]) : sk_float_rsqrt(viewMatrix[SkMatrix::kMScaleX] * viewMatrix[SkMatrix::kMScaleX] + viewMatrix[SkMatrix::kMSkewX] * viewMatrix[SkMatrix::kMSkewX]); float zRatio = SkTPin(fOccluderHeight / (fLightPos.fZ - fOccluderHeight), 0.0f, 0.95f); SkScalar devSpaceSpotBlur = 2.0f * fLightRadius * zRatio; // handle scale of radius and pad due to CTM const SkScalar srcSpaceSpotBlur = devSpaceSpotBlur * devToSrcScale; // Compute the scale and translation for the spot shadow. const SkScalar spotScale = fLightPos.fZ / (fLightPos.fZ - fOccluderHeight); SkPoint spotOffset = SkPoint::Make(zRatio*(-fLightPos.fX), zRatio*(-fLightPos.fY)); // Adjust translate for the effect of the scale. spotOffset.fX += spotScale*viewMatrix[SkMatrix::kMTransX]; spotOffset.fY += spotScale*viewMatrix[SkMatrix::kMTransY]; // This offset is in dev space, need to transform it into source space. SkMatrix ctmInverse; if (!viewMatrix.invert(&ctmInverse)) { // Since the matrix is a similarity, this should never happen, but just in case... SkDebugf("Matrix is degenerate. Will not render spot shadow!\n"); return true; } ctmInverse.mapPoints(&spotOffset, 1); // Compute the transformed shadow rrect SkRRect spotShadowRRect; SkMatrix shadowTransform; shadowTransform.setScaleTranslate(spotScale, spotScale, spotOffset.fX, spotOffset.fY); rrect.transform(shadowTransform, &spotShadowRRect); SkScalar spotRadius = spotShadowRRect.getSimpleRadii().fX; // Compute the insetWidth SkScalar blurOutset = 0.5f*srcSpaceSpotBlur; SkScalar insetWidth = blurOutset; if (fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag) { // If transparent, just do a fill insetWidth += spotShadowRRect.width(); } else { // For shadows, instead of using a stroke we specify an inset from the penumbra // border. We want to extend this inset area so that it meets up with the caster // geometry. The inset geometry will by default already be inset by the blur width. // // We compare the min and max corners inset by the radius between the original // rrect and the shadow rrect. The distance between the two plus the difference // between the scaled radius and the original radius gives the distance from the // transformed shadow shape to the original shape in that corner. The max // of these gives the maximum distance we need to cover. // // Since we are outsetting by 1/2 the blur distance, we just add the maxOffset to // that to get the full insetWidth. SkScalar maxOffset; if (rrect.isRect()) { // Manhattan distance works better for rects maxOffset = SkTMax(SkTMax(SkTAbs(spotShadowRRect.rect().fLeft - rrect.rect().fLeft), SkTAbs(spotShadowRRect.rect().fTop - rrect.rect().fTop)), SkTMax(SkTAbs(spotShadowRRect.rect().fRight - rrect.rect().fRight), SkTAbs(spotShadowRRect.rect().fBottom - rrect.rect().fBottom))); } else { SkScalar dr = spotRadius - rrect.getSimpleRadii().fX; SkPoint upperLeftOffset = SkPoint::Make(spotShadowRRect.rect().fLeft - rrect.rect().fLeft + dr, spotShadowRRect.rect().fTop - rrect.rect().fTop + dr); SkPoint lowerRightOffset = SkPoint::Make(spotShadowRRect.rect().fRight - rrect.rect().fRight - dr, spotShadowRRect.rect().fBottom - rrect.rect().fBottom - dr); maxOffset = SkScalarSqrt(SkTMax(upperLeftOffset.lengthSqd(), lowerRightOffset.lengthSqd())) + dr; } insetWidth += maxOffset; } // Outset the shadow rrect to the border of the penumbra SkRect outsetRect = spotShadowRRect.rect().makeOutset(blurOutset, blurOutset); if (spotShadowRRect.isOval()) { spotShadowRRect = SkRRect::MakeOval(outsetRect); } else { SkScalar outsetRad = spotRadius + blurOutset; spotShadowRRect = SkRRect::MakeRectXY(outsetRect, outsetRad, outsetRad); } GrColor4f color = paint.getColor4f(); paint.setColor4f(color.mulByScalar(fSpotAlpha)); rtContext->drawShadowRRect(clip, std::move(paint), viewMatrix, spotShadowRRect, devSpaceSpotBlur, insetWidth); return true; } sk_sp<GrTextureProxy> SkSpotShadowMaskFilterImpl::filterMaskGPU(GrContext*, sk_sp<GrTextureProxy> srcProxy, const SkMatrix& ctm, const SkIRect& maskRect) const { // This filter is generative and doesn't operate on pre-existing masks return nullptr; } #endif #ifndef SK_IGNORE_TO_STRING void SkSpotShadowMaskFilterImpl::toString(SkString* str) const { str->append("SkSpotShadowMaskFilterImpl: ("); str->append("occluderHeight: "); str->appendScalar(fOccluderHeight); str->append(" "); str->append("lightPos: ("); str->appendScalar(fLightPos.fX); str->append(", "); str->appendScalar(fLightPos.fY); str->append(", "); str->appendScalar(fLightPos.fZ); str->append(") "); str->append("lightRadius: "); str->appendScalar(fLightRadius); str->append(" "); str->append("spotAlpha: "); str->appendScalar(fSpotAlpha); str->append(" "); str->append("flags: ("); if (fFlags) { bool needSeparator = false; SkAddFlagToString(str, SkToBool(fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag), "TransparentOccluder", &needSeparator); } else { str->append("None"); } str->append("))"); } #endif SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkSpotShadowMaskFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSpotShadowMaskFilterImpl) SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
43.672269
99
0.567122
picmonkey
a51e548ef917c3c030f04d2ca10d10057b80b465
1,142
cpp
C++
patrones/structural/bridge.cpp
jrinconada/cpp-examples
069e3cc910b2c2d0716af36bef28336003fb6d9e
[ "MIT" ]
1
2018-02-22T12:33:44.000Z
2018-02-22T12:33:44.000Z
patrones/structural/bridge.cpp
jrinconada/cpp-examples
069e3cc910b2c2d0716af36bef28336003fb6d9e
[ "MIT" ]
null
null
null
patrones/structural/bridge.cpp
jrinconada/cpp-examples
069e3cc910b2c2d0716af36bef28336003fb6d9e
[ "MIT" ]
null
null
null
#include <iostream> class Implementation { public: virtual void doSomething() = 0; }; // Clase instanciable que recibe una implemanción dependiente de la plataforma class ConcreteClass { Implementation* implementation; public: ConcreteClass(Implementation* i) { implementation = i; } void doSomething() { // En realidad no hace nada, lo hace implementation implementation->doSomething(); } }; // Implementación dependiente de la plataforma para Windows class WindowsImplementation : public Implementation { public: void doSomething() { std::cout << "Implementación concreta de Windows" << '\n'; } }; // Implementación para Linux class LinuxImplementation : public Implementation { public: void doSomething() { std::cout << "Implementación concreta de Linux" << '\n'; } }; int main () { WindowsImplementation* win = new WindowsImplementation; LinuxImplementation* lin = new LinuxImplementation; ConcreteClass concreteForWindows(win); ConcreteClass concreteForLinux(lin); concreteForWindows.doSomething(); concreteForLinux.doSomething(); }
24.297872
78
0.705779
jrinconada
a521854e66a9ea88f3402ad7657aa0d0c7c6aed9
1,162
cpp
C++
examples/contacts/server.cpp
CapacitorSet/FHE-tools
1271f2d65b3390c7156606b266b93c5d23ed398a
[ "Apache-2.0" ]
2
2018-08-28T04:50:57.000Z
2019-02-26T22:06:36.000Z
examples/contacts/server.cpp
CapacitorSet/Glovebox
1271f2d65b3390c7156606b266b93c5d23ed398a
[ "Apache-2.0" ]
null
null
null
examples/contacts/server.cpp
CapacitorSet/Glovebox
1271f2d65b3390c7156606b266b93c5d23ed398a
[ "Apache-2.0" ]
null
null
null
#include <cassert> #include <glovebox.h> #include <rpc/server.h> #include "contact.h" ServerParams server_params; Contact contacts[] = { {"", 504'305'6784}, {"", 208'348'4604}, {"", 713'729'7840}, {"", 714'543'1510}, {"", 907'553'8994}, {"", 704'551'2763}, {"", 172'265'8920}, {"", 583'642'3948}, {"", 754'768'2428}, {"", 921'915'3647}, {"", 790'793'8139}, {"", 936'327'0855}, }; int main(int argc, char **argv) { assert(argc <= 2); uint16_t port = (argc == 2) ? atoi(argv[1]) : 8000; ClientKey key = read_client_key("cloud.key"); if (key == nullptr) { puts("cloud.key not found: run ./keygen first."); return 1; } server_params = ServerParams(key); rpc::server srv(port); printf("Listening on port %d.\n", port); srv.bind("isKnownContact", [](std::string _userNumber) { puts("Received request."); PhoneNumber userNumber(_userNumber); bit_t isKnown = make_bit(); constant(isKnown, false); for (const auto &contact : contacts) { PhoneNumber contactNo(contact.phoneNumber); bit_t matches = equals(contactNo.data, userNumber.data); isKnown |= matches; } return serialize(isKnown); }); srv.run(); return 0; }
27.023256
83
0.63253
CapacitorSet
a5251d4419e9a4383d30f49455060579d6d13fa9
1,024
cpp
C++
tests/matrix_add.cpp
ivansipiran/numpyeigen
48c6ccc5724572c6107240fa472d3c1ff04d679d
[ "MIT" ]
75
2018-08-31T18:49:17.000Z
2022-02-12T11:25:00.000Z
tests/matrix_add.cpp
ivansipiran/numpyeigen
48c6ccc5724572c6107240fa472d3c1ff04d679d
[ "MIT" ]
54
2018-07-19T18:08:36.000Z
2022-01-04T15:30:52.000Z
tests/matrix_add.cpp
ivansipiran/numpyeigen
48c6ccc5724572c6107240fa472d3c1ff04d679d
[ "MIT" ]
9
2019-03-04T21:16:15.000Z
2021-10-16T10:02:34.000Z
#include <tuple> #include <Eigen/Core> #include <npe.h> npe_function(matrix_add) npe_arg(b, npe_matches(a)) npe_arg(a, dense_double, dense_float) npe_doc(R"(Add two matrices of the same type)") npe_begin_code() npe_Matrix_a ret1 = a + b; return npe::move(ret1); npe_end_code() npe_function(matrix_add2) npe_arg(a, dense_double, dense_float) npe_arg(b, npe_matches(a)) npe_doc(R"(Add two matrices of the same type)") npe_begin_code() npe_Matrix_a ret1 = a + b; return npe::move(ret1); npe_end_code() npe_function(matrix_add3) npe_arg(a, dense_double, dense_float) npe_arg(b, npe_matches(a)) npe_doc(R"(Add two matrices of the same type)") npe_begin_code() npe_Matrix_a ret1 = a + b; return npe::move(ret1); npe_end_code() npe_function(matrix_add4) npe_arg(a, dense_double, dense_float) npe_arg(b, dense_double, dense_float) npe_doc(R"(Add two matrices)") npe_begin_code() npe_Matrix_a ret1 = a + b.template cast<npe_Scalar_a>(); return npe::move(ret1); npe_end_code()
16.786885
60
0.722656
ivansipiran
a526ab9707f91ac116f7bc13791e36bdd4713fd8
1,854
cpp
C++
projectionSceneManager/src/SceneManager.cpp
c-c-c/gold-creative-coding
d7ccb5d5f706caafed27050a4c3a514c56a8230e
[ "MIT" ]
1
2020-04-25T06:34:59.000Z
2020-04-25T06:34:59.000Z
projectionSceneManager/src/SceneManager.cpp
c-c-c/gold-creative-coding-1
d7ccb5d5f706caafed27050a4c3a514c56a8230e
[ "MIT" ]
null
null
null
projectionSceneManager/src/SceneManager.cpp
c-c-c/gold-creative-coding-1
d7ccb5d5f706caafed27050a4c3a514c56a8230e
[ "MIT" ]
null
null
null
#include "SceneManager.h" //note: I could refactor in order to get rid of some of the repetition between the two functions void SceneManager::setup(string scenesFile, ofxPiMapper *_piMapper){ piMapper = _piMapper; if (result.open(scenesFile)){ cout << "file opened successfully" << endl; allowTransitions = true; } else { cout << "scene file " << scenesFile << " not found" << endl; allowTransitions = false; } sceneIndex = 0; currentPreset = result[sceneIndex]["preset"].asInt(); sceneDuration = result[sceneIndex]["duration"].asInt(); if (sceneDuration<=0) { allowTransitions = false; cout << "scene duration set to <= 0, therefore transitions turned off." << endl; } } // Don't do any drawing here void SceneManager::update(){ if (ofGetElapsedTimeMillis()>sceneDuration && allowTransitions) { sceneIndex++; if (sceneIndex >= result.size()) { cout << "Warning: end of scenes reached. Restarting from 0." << endl; sceneIndex = 0; } int targetPreset = result[sceneIndex]["preset"].asInt(); if (targetPreset>=piMapper->getNumPresets()){ cout << "ERROR: skipping scene " << sceneIndex << " as preset " << targetPreset << " does not exist" << endl; } else { piMapper->setPreset(targetPreset); int tempDuration = result[sceneIndex]["duration"].asInt(); if (tempDuration<=0){ allowTransitions = false; cout << "scene duration set to <= 0, therefore transitions turned off." << endl; return; } sceneDuration+=tempDuration; cout << sceneIndex << " changed to " << piMapper->getActivePresetIndex() << " for " << sceneDuration << endl; } } }
36.352941
121
0.587918
c-c-c
a5284c9bd4e06a506e701c1ad7a4c768efc359ef
7,079
cpp
C++
src/XliPlatform/android/EGLContext.cpp
fuse-open/uno-base
27e259c5ed34ccc68b39cb80fd9d02442ae3339e
[ "MIT" ]
4
2018-05-14T07:49:34.000Z
2018-05-21T06:40:17.000Z
src/XliPlatform/android/EGLContext.cpp
fuse-open/legacy-cpp-framework
27e259c5ed34ccc68b39cb80fd9d02442ae3339e
[ "MIT" ]
2
2018-10-21T12:40:49.000Z
2020-04-16T17:55:55.000Z
src/XliPlatform/android/EGLContext.cpp
fuse-open/legacy-cpp-framework
27e259c5ed34ccc68b39cb80fd9d02442ae3339e
[ "MIT" ]
4
2018-05-14T17:03:51.000Z
2018-12-01T08:05:02.000Z
#include <XliPlatform/GLContext.h> #include <uBase/Console.h> #include <uBase/Memory.h> #include <XliPlatform/Window.h> #include <EGL/egl.h> #include <uBase/Console.h> #include <stdlib.h> #include <string.h> #ifdef ANDROID # include <android/native_window.h> # define NATIVE_HANDLE ANativeWindow* #endif namespace Xli { class EglContext: public GLContext { Shared<Window> window; NATIVE_HANDLE handle; EGLDisplay display; EGLSurface surface; EGLContext context; EGLConfig config; int swapInterval; public: EglContext(Window* wnd, const GLContextAttributes& attribs) { swapInterval = -1; handle = NULL; context = EGL_NO_CONTEXT; surface = EGL_NO_SURFACE; display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(display, 0, 0); const EGLint iattribs[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_BLUE_SIZE, 5, EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, 16, EGL_STENCIL_SIZE, 0, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //EGL_RENDER_BUFFER, attribs.Buffers <= 1 ? EGL_SINGLE_BUFFER : EGL_BACK_BUFFER, EGL_NONE }; EGLint numConfigs; EGLConfig configs[128]; if (!eglChooseConfig(display, iattribs, configs, 128, &numConfigs) || numConfigs == 0) throw Exception("Unable to choose EGL config"); EGLint cs = 0, cd = 0, cb = 0; int cc = 0; for (int i = 0; i < numConfigs; i++) { EGLint samples, depth, stencil, buffer, r, g, b, a, render; eglGetConfigAttrib(display, configs[i], EGL_RED_SIZE, &r); eglGetConfigAttrib(display, configs[i], EGL_GREEN_SIZE, &g); eglGetConfigAttrib(display, configs[i], EGL_BLUE_SIZE, &b); eglGetConfigAttrib(display, configs[i], EGL_ALPHA_SIZE, &a); eglGetConfigAttrib(display, configs[i], EGL_BUFFER_SIZE, &buffer); eglGetConfigAttrib(display, configs[i], EGL_DEPTH_SIZE, &depth); eglGetConfigAttrib(display, configs[i], EGL_STENCIL_SIZE, &stencil); eglGetConfigAttrib(display, configs[i], EGL_SAMPLES, &samples); #ifdef DEBUG Error->WriteLine(String::Format("DEBUG: EGLConfig[%d]: M %d D %d S %d B %d R %d G %d B %d A %d", i, samples, depth, stencil, buffer, r, g, b, a)); #endif if (samples >= cs && depth >= cd && buffer >= cb && samples <= attribs.Samples && r <= attribs.ColorBits.R && g <= attribs.ColorBits.G && b <= attribs.ColorBits.B && a <= attribs.ColorBits.A) { cs = samples; cd = depth; cb = buffer; cc = i; } } config = configs[cc]; #ifdef DEBUG Error->WriteLine((String)"DEBUG: Selected EGLConfig[" + (int)cc + "]"); #endif MakeCurrent(wnd); } virtual ~EglContext() { if (display != EGL_NO_DISPLAY) { eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (context != EGL_NO_CONTEXT) eglDestroyContext(display, context); if (surface != EGL_NO_SURFACE) eglDestroySurface(display, surface); eglTerminate(display); } } virtual GLContext* CreateSharedContext() { throw NotSupportedException(U_FUNCTION); } virtual void MakeCurrent(Window* wnd) { if (wnd) window = wnd; if (wnd && (NATIVE_HANDLE)wnd->GetNativeHandle() != handle) { #ifdef ANDROID if (wnd->GetImplementation() == WindowImplementationAndroid) { EGLint format; eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry((ANativeWindow*)wnd->GetNativeHandle(), 0, 0, format); } #endif if (surface != EGL_NO_SURFACE) eglDestroySurface(display, surface); surface = eglCreateWindowSurface(display, config, (NATIVE_HANDLE)wnd->GetNativeHandle(), NULL); if (surface == EGL_NO_SURFACE) throw Exception("Unable to create EGL Surface"); if (context == EGL_NO_CONTEXT) { const EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribs); if (context == EGL_NO_CONTEXT) throw Exception("Unable to create EGL Context"); } } if (eglMakeCurrent(display, surface, surface, wnd != 0 ? context : 0) == EGL_FALSE) { throw Exception("Unable to make EGL context current"); } } virtual bool IsCurrent() { return eglGetCurrentContext() == context; } virtual void SwapBuffers() { eglSwapBuffers(display, surface); } virtual void SetSwapInterval(int value) { if (eglSwapInterval(display, value)) swapInterval = value; } virtual int GetSwapInterval() { return swapInterval; } virtual Vector2i GetDrawableSize() { return window->GetClientSize(); } virtual void GetAttributes(GLContextAttributes& result) { memset(&result, 0, sizeof(GLContextAttributes)); eglGetConfigAttrib(display, config, EGL_RED_SIZE, &result.ColorBits.R); eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &result.ColorBits.G); eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &result.ColorBits.B); eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &result.ColorBits.A); eglGetConfigAttrib(display, config, EGL_DEPTH_SIZE, &result.DepthBits); eglGetConfigAttrib(display, config, EGL_STENCIL_SIZE, &result.StencilBits); eglGetConfigAttrib(display, config, EGL_SAMPLES, &result.Samples); /* EGLint renderBuffer; eglGetConfigAttrib(display, config, EGL_RENDER_BUFFER, &renderBuffer); result.Buffers = renderBuffer == EGL_SINGLE_BUFFER ? 1 : 2; */ result.Buffers = 2; } }; GLContext* GLContext::Create(Window* window, const GLContextAttributes& attribs) { return new EglContext(window, attribs); } }
33.549763
170
0.546546
fuse-open
a528872c16255febef74c6ee063d563f34fbccf5
4,455
cpp
C++
daemons/Proxy/src/session.cpp
SorcererX/SepiaStream
e8eccdb7019dd94e8585471535debf8bae1325f5
[ "BSD-2-Clause" ]
null
null
null
daemons/Proxy/src/session.cpp
SorcererX/SepiaStream
e8eccdb7019dd94e8585471535debf8bae1325f5
[ "BSD-2-Clause" ]
6
2015-03-11T06:18:26.000Z
2017-05-01T18:40:33.000Z
daemons/Proxy/src/session.cpp
SorcererX/SepiaStream
e8eccdb7019dd94e8585471535debf8bae1325f5
[ "BSD-2-Clause" ]
null
null
null
#include "session.h" #include "msgsocket.h" #include <sepia/comm/dispatcher.h> #include <sepia/comm/observer.h> #include <functional> using sepia::network::TcpSocket; Session::Session( int a_socket ) { m_socket = new MsgSocket( a_socket ); init(); } Session::Session( sepia::network::TcpSocket* a_socket ) { m_socket = new MsgSocket( a_socket ); init(); } void Session::init() { m_recvBuffer.reserve( 1024 ); m_recvBuffer.resize( 1024 ); m_tcpReceiverThread = NULL; m_header = new sepia::comm::Header(); m_header->set_source_node( getpid() ); m_header->set_source_router( 0 ); } Session::~Session() { //m_socket->close(); delete m_socket; } void Session::start() { m_thread = new std::thread( std::bind( &Session::own_thread, this ) ); m_tcpReceiverThread = new std::thread( std::bind( &Session::tcpreceiver_thread, this ) ); } void Session::receive( const sepia::comm::internal::ForwardSubscribe* a_message ) { m_messages.insert( a_message->message_name() ); sepia::comm::internal::RemoteSubscription msg; msg.set_message_name( a_message->message_name() ); m_header->set_message_name( msg.GetTypeName() ); std::cout << msg.GetTypeName() << " TCPsend: " << msg.ShortDebugString() << std::endl; m_socket->sendMsg( m_header ); m_socket->sendMsg( a_message ); } void Session::receive(const sepia::comm::internal::ForwardUnsubscribe* a_message ) { MessageSet::iterator list_it = m_messages.find( a_message->message_name() ); m_messages.erase( list_it ); sepia::comm::internal::RemoteUnsubscription msg; msg.set_message_name( a_message->message_name() ); m_header->set_message_name( msg.GetTypeName() ); std::cout << msg.GetTypeName() << " TCPsend: " << msg.ShortDebugString() << std::endl; m_socket->sendMsg( m_header ); m_socket->sendMsg( &msg ); } void Session::receive( const sepia::comm::internal::RemoteSubscription* a_message ) { ObserverRaw::initRawReceiver( a_message->message_name() ); } void Session::receive( const sepia::comm::internal::RemoteUnsubscription* a_message ) { ObserverRaw::destroyRawReceiver( a_message->message_name() ); } void Session::receiveRaw( const sepia::comm::Header* a_header, const char* a_buffer, size_t a_size ) { std::cout << a_header->message_name() << " RawSend: <NOT DECODED>" << std::endl; m_socket->sendMsg( a_header ); m_socket->sendMsg( a_buffer, a_size ); } void Session::own_thread() { sepia::comm::Observer< sepia::comm::internal::ForwardSubscribe >::initReceiver(); sepia::comm::Observer< sepia::comm::internal::ForwardUnsubscribe >::initReceiver(); sepia::comm::Observer< sepia::comm::internal::RemoteSubscription >::initReceiver(); sepia::comm::Observer< sepia::comm::internal::RemoteUnsubscription >::initReceiver(); while( !m_terminate ) { sepia::comm::ObserverBase::threadReceiver(); } sepia::comm::Observer< sepia::comm::internal::ForwardSubscribe >::destroyReceiver(); sepia::comm::Observer< sepia::comm::internal::ForwardUnsubscribe >::destroyReceiver(); sepia::comm::Observer< sepia::comm::internal::RemoteSubscription >::destroyReceiver(); sepia::comm::Observer< sepia::comm::internal::RemoteUnsubscription >::destroyReceiver(); } void Session::tcpreceiver_thread() { sepia::comm::Header header; while( !m_terminate ) { size_t header_size = 0; m_socket->recvMsg( m_recvBuffer.data(), header_size ); header.ParseFromArray( m_recvBuffer.data(), header_size ); size_t msg_size = 0; m_socket->recvMsg( m_recvBuffer.data() + header_size , msg_size ); if( ( header.message_name() == "sepia.comm.internal.RemoteSubscription" ) || ( header.message_name() == "sepia.comm.internal.RemoteUnsubscription" ) ) { std::cout << "Got: " << header.message_name() << " routing local.." << std::endl; ObserverBase::routeMessageToThreads( &header, m_recvBuffer.data() + header_size, msg_size ); std::cout << "Routing complete." << std::endl; } else { header.set_source_node( getpid() ); std::cout << "Got: " << header.message_name() << "rawSending" << std::endl; sepia::comm::MessageSender::rawSend( &header, m_recvBuffer.data() + header_size, msg_size ); std::cout << "Rawsend complete." << std::endl; } } }
32.282609
104
0.664198
SorcererX
a52a8ec1ee7e31a4c0a2c28d751dc92cfd425d40
9,770
cpp
C++
Question1/mainwindow.cpp
A-new-b/curriculum-design
f51d8fa999aea8860267035189459affb90e5cf3
[ "MIT" ]
null
null
null
Question1/mainwindow.cpp
A-new-b/curriculum-design
f51d8fa999aea8860267035189459affb90e5cf3
[ "MIT" ]
3
2020-04-18T14:53:16.000Z
2020-04-20T01:39:47.000Z
Question1/mainwindow.cpp
A-new-b/curriculum-design
f51d8fa999aea8860267035189459affb90e5cf3
[ "MIT" ]
1
2020-04-18T06:15:58.000Z
2020-04-18T06:15:58.000Z
#include "mainwindow.h" #include "ui_mainwindow.h" #include "category.h" #include "goods_in.h" #include "goods_out.h" #include<QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); //给第一个table设置只允许单行选中且无法编辑 ui->category_table->verticalHeader()->hide();//隐藏行号 ui->category_table->setSelectionBehavior(QAbstractItemView::SelectRows); ui->category_table->setSelectionMode ( QAbstractItemView::SingleSelection); ui->category_table->setEditTriggers(QAbstractItemView::NoEditTriggers); //第二个同理 ui->goods_table->verticalHeader()->hide(); ui->goods_table->setSelectionBehavior(QAbstractItemView::SelectRows); ui->goods_table->setSelectionMode ( QAbstractItemView::SingleSelection); ui->goods_table->setEditTriggers(QAbstractItemView::NoEditTriggers); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_category_create_clicked() { category create(this); create.setWindowTitle("创建种类"); create.setfather(this); create.setInfoContent("你正在创建新商品:"); auto result = create.exec();//模态形式显示对话框 if (result==QDialog::Accepted){ create.add_accept(); } } QStandardItemModel* MainWindow::getCategoryModel() { QStandardItemModel* model=new QStandardItemModel(); QString label="编号,类型"; QStringList labels=label.split(','); model->setHorizontalHeaderLabels(labels);//设置label int row_number =0;//行数 big_category p = &market_first_node; while (p !=nullptr) { model->insertRow(row_number); model->setData(model->index(row_number, 0), row_number+1); model->setData(model->index(row_number, 1), p->category_Name); p = p->next_big_category; row_number++; } return model; } QStandardItemModel* MainWindow::getItemsModel(const QModelIndex &index){ QStandardItemModel* model=new QStandardItemModel(); QString label="数量,单位,进价,售价,商品名"; QStringList labels=label.split(','); model->setHorizontalHeaderLabels(labels); auto num=index.model()->index(index.row(),0); int position=num.data().toInt();//获取当前行的编号 big_category p = &market_first_node; p = find_category_byindex(p,position-1);//寻找商品 int row_number =0;//行数 LinkList g = p ->small_category; while (g!=nullptr) { model->insertRow(row_number); // model->setData(model->index(row_number, 0), row_number+1); model->setData(model->index(row_number, 0), g ->data.count); model->setData(model->index(row_number, 1), g->data.unit); model->setData(model->index(row_number, 2), g->data.purePrice); model->setData(model->index(row_number, 3), g->data.salePrice); model->setData(model->index(row_number, 4), g->data.name); g = g ->next; row_number++; } return model ; }//基于第一个model的位置显示第二个model的数据 QStandardItemModel* MainWindow::getItemsModel(int position){//int 重载 QStandardItemModel* model=new QStandardItemModel(); QString label="数量,单位,进价,售价,商品名"; QStringList labels=label.split(','); model->setHorizontalHeaderLabels(labels); // auto num=index.model()->index(index.row(),0); // int position=num.data().toInt();//获取当前行的编号 big_category p = &market_first_node; p = find_category_byindex(p,position-1);//寻找商品 int row_number =0;//行数 LinkList g = p ->small_category; while (g!=nullptr) { model->insertRow(row_number); // model->setData(model->index(row_number, 0), row_number+1); model->setData(model->index(row_number, 0), g ->data.count); model->setData(model->index(row_number, 1), g->data.unit); model->setData(model->index(row_number, 2), g->data.purePrice); model->setData(model->index(row_number, 3), g->data.salePrice); model->setData(model->index(row_number, 4), g->data.name); g = g ->next; row_number++; } return model ; }//基于第一个model的位置显示第二个model的数据 QStandardItemModel* MainWindow::getItemsModel(LinkList q){//LinkList 重载 QStandardItemModel* model=new QStandardItemModel(); QString label="数量,单位,进价,售价,商品名"; QStringList labels=label.split(','); model->setHorizontalHeaderLabels(labels); // auto num=index.model()->index(index.row(),0); // int position=num.data().toInt();//获取当前行的编号 // big_category p = &market_first_node; // p = find_category_byindex(p,position-1);//寻找商品 int row_number =0;//行数 LinkList g = q; while (g!=nullptr) { model->insertRow(row_number); // model->setData(model->index(row_number, 0), row_number+1); model->setData(model->index(row_number, 0), g ->data.count); model->setData(model->index(row_number, 1), g->data.unit); model->setData(model->index(row_number, 2), g->data.purePrice); model->setData(model->index(row_number, 3), g->data.salePrice); model->setData(model->index(row_number, 4), g->data.name); g = g ->next; row_number++; } return model ; }//基于第一个model的位置显示第二个model的数据 void MainWindow::on_category_table_clicked(const QModelIndex &index) { ItemsTableSet(getItemsModel(index)); } void MainWindow::CategoryTableSet (QStandardItemModel* t){ this ->ui->category_table->clearSpans(); this ->ui->category_table->setModel(t); this ->ui->category_table->setCurrentIndex(t->index(0,0)); on_category_table_clicked(t->index(0,0));//默认选中第一行 } void MainWindow::ItemsTableSet(QStandardItemModel* t){ this ->ui->goods_table->clearSpans(); this ->ui->goods_table->setModel(t); this ->ui->goods_table->setCurrentIndex(t->index(0,0)); } void MainWindow::on_category_update_clicked() { category change(this); change.setWindowTitle("修改种类"); change.setfather(this); auto position=ui->category_table->currentIndex(); QString name=position.model()->index(position.row(),1).data().toString();//获取选中行的种类名 change.setInfoContent("你正在修改种类:"+name); auto result=change.exec(); if (result==QDialog::Accepted){ change.update_accept(position.model()->index(position.row(),0).data().toInt());//将选中行的编号作为参数 } } void MainWindow::on_goods_in_clicked() { goods_in new_in(this); new_in.setWindowTitle("商品入库"); new_in.setfather(this); auto position=ui->category_table->currentIndex(); QString name=position.model()->index(position.row(),1).data().toString();//获取选中行的种类名 new_in.setInfoContent("你正在入库的商品种类为:"+name); auto result = new_in.exec(); if (result==QDialog::Accepted){ new_in.add_items_goods(position.model()->index(position.row(),0).data().toInt());//将选中行的编号作为参数 } } void MainWindow::on_goods_out_clicked() { goods_out new_out(this); new_out.setWindowTitle("商品出库"); new_out.setfather(this); auto position_category=ui->category_table->currentIndex(); QString name_category=position_category.model()->index(position_category.row(),1).data().toString();//获取选中行的种类名 auto position_goods=ui->goods_table->currentIndex(); QString name_goods=position_goods.model()->index(position_goods.row(),4).data().toString();//获取选中行的商品 new_out.setInfoContent("你正在出库的商品种类为:"+name_category+"商品名称为:"+name_goods); auto result = new_out.exec(); int g= position_goods.row(); if (result==QDialog::Accepted){ new_out.delete_items_goods(position_category.model()->index(position_category.row(),0).data().toInt(),g);//将选中行的编号作为参数 } } void MainWindow::on_search_category_clicked() { this->market_first_node = this->default_market_node; this->CategoryTableSet(this->getCategoryModel()); if(this ->ui->search_content_category->text().toStdString()=="") { this->market_first_node = this->default_market_node; this->CategoryTableSet(this->getCategoryModel()); } else { big_category p = &this->market_first_node; p=search_Big_Category(p,this ->ui->search_content_category->text().toStdString().c_str()); if(p!=nullptr) { this->market_first_node=*p; this ->market_first_node.next_big_category=nullptr; this->CategoryTableSet(this->getCategoryModel()); } else { QMessageBox::information(nullptr,"失败","无该商品种类"); } } } void MainWindow::on_search_name_clicked() { this->market_first_node = this->default_market_node; this->CategoryTableSet(this->getCategoryModel()); if(this ->ui->search_name->text().toStdString()==""&&this ->ui->search_category->text().toStdString()=="") { this->market_first_node = this->default_market_node; this->CategoryTableSet(this->getCategoryModel()); } else if(this ->ui->search_category->text().toStdString()=="") { QMessageBox::information(nullptr,"","请输入种类名"); } else if(this ->ui->search_name->text().toStdString()=="") { QMessageBox::information(nullptr,"","请输入商品名"); } else { big_category p = &this->market_first_node; p=search_Big_Category(p,this ->ui->category_in_name->text().toStdString().c_str()); if(p!=nullptr) { this->market_first_node=*p; this ->market_first_node.next_big_category=nullptr; this->CategoryTableSet(this->getCategoryModel()); LinkList q ; q = search_Item(p,this ->ui->name_in_name->text().toStdString().c_str()); if(q !=nullptr) { q->next=nullptr; this ->ItemsTableSet(this ->getItemsModel(q)); } else { QMessageBox::information(nullptr,"失败","无该商品名"); } } else { QMessageBox::information(nullptr,"失败","无该商品种类"); } } }
35.787546
126
0.659058
A-new-b
a52b9c60f73b97b3e3b90e61ce4189b9f58f6652
1,055
cpp
C++
Practice/2019.3.17/CF908G.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2019.3.17/CF908G.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2019.3.17/CF908G.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<iostream> using namespace std; const int maxN=710; const int Mod=1e9+7; char Input[maxN]; int n,Num[maxN]; int F[maxN][maxN][10][2]; void Plus(int &x,int y); int main() { scanf("%s",Input+1); n=strlen(Input+1); reverse(&Input[1],&Input[n+1]); for (int i=1; i<=n; i++) Num[i]=Input[i]-'0'; ++Num[1]; for (int i=1; i<=n; i++) Num[i+1]+=Num[i]/10,Num[i]%=10; if (Num[n+1]) ++n; for (int i=0; i<=9; i++) F[0][0][i][1]=1; for (int i=0; i<n; i++) for (int j=0; j<=i; j++) for (int k=0; k<=9; k++) for (int b=0; b<=1; b++) if (F[i][j][k][b]) for (int c=0; c<=9; c++) Plus(F[i+1][j+(c>=k)][k][(b==0&&c>Num[i+1])||(b==1&&c>=Num[i+1])],F[i][j][k][b]); int Ans=0; for (int k=1; k<=9; k++) for (int i=1,mul=1; i<=n; i++,mul=(10ll*mul+1)%Mod) if (k!=9) Plus(Ans,1ll*(F[n][i][k][0])%Mod*mul%Mod); else Plus(Ans,1ll*F[n][i][k][0]*mul%Mod); printf("%d\n",Ans); return 0; } void Plus(int &x,int y) { x+=y; if (x>=Mod) x-=Mod; return; }
22.446809
88
0.522275
SYCstudio
a52d059c158b63073d6ce9340b6d9dad008ac689
27,283
cpp
C++
ChineseChess/ChineseChess/Game.cpp
Zhang-Yu-Bo/Project01-ChineseChess
6daa4f2ad78bf572dbba3289eaa38ce9be3fece0
[ "MIT" ]
null
null
null
ChineseChess/ChineseChess/Game.cpp
Zhang-Yu-Bo/Project01-ChineseChess
6daa4f2ad78bf572dbba3289eaa38ce9be3fece0
[ "MIT" ]
null
null
null
ChineseChess/ChineseChess/Game.cpp
Zhang-Yu-Bo/Project01-ChineseChess
6daa4f2ad78bf572dbba3289eaa38ce9be3fece0
[ "MIT" ]
null
null
null
#include "Game.h" // 鍵盤掃描碼 // 上: 72 // 下: 80 // 左: 75 // 右: 77 // <: 44 // >: 46 // Enter: 13 // Esc: 27 // w 119 // a 97 // s 115 // d 100 // space 32 #ifdef _CONSOLE_INFO_HANDLE_ CONSOLE_CURSOR_INFO cci; HANDLE handle; COORD cursorPosition; #endif // _CONSOLE_INFO_HANDLE_ #ifdef _CHESS_CHINESE_ const string chessChinese[15] = { "","將","士","象","車","馬","包","卒","帥","仕","相","車","傌","炮","兵" }; #endif // _CHESS_CHINESE_ #ifdef _CELAR_BOARD_ const string clearBoard[21][18] = { {"1"," ","2"," ","3"," ","4"," ","5"," ","6"," ","7"," ","8"," ","9"}, {"‧","=","=","=","=","=","=","=","=","=","=","=","=","=","=","=","‧"}, {"∥"," ","|"," ","|"," ","|","\","|","/","|"," ","|"," ","|"," ","∥"}, {"∥","-","+","-","+","-","+","-","+","-","+","-","+","-","+","-","∥"}, {"∥"," ","|"," ","|"," ","|","/","|","\","|"," ","|"," ","|"," ","∥"}, {"∥","-","+","-","+","-","+","-","+","-","+","-","+","-","+","-","∥"}, {"∥"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","∥"}, {"∥","-","+","-","+","-","+","-","+","-","+","-","+","-","+","-","∥"}, {"∥"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","∥"}, {"∥","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","∥"}, {"∥"," "," ","楚","河"," "," "," ","  "," "," "," ","漢","界"," "," ","∥"}, {"∥","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","∥"}, {"∥"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","∥"}, {"∥","-","+","-","+","-","+","-","+","-","+","-","+","-","+","-","∥"}, {"∥"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","∥"}, {"∥","-","+","-","+","-","+","-","+","-","+","-","+","-","+","-","∥"}, {"∥"," ","|"," ","|"," ","|","\","|","/","|"," ","|"," ","|"," ","∥"}, {"∥","-","+","-","+","-","+","-","+","-","+","-","+","-","+","-","∥"}, {"∥"," ","|"," ","|"," ","|","/","|","\","|"," ","|"," ","|"," ","∥"}, {"‧","=","=","=","=","=","=","=","=","=","=","=","=","=","=","=","‧"}, {"九"," ","八"," ","七"," ","六"," ","五"," ","四"," ","三"," ","二"," ","一"} }; #endif // _CLEAR_BOARD_ #ifdef _GAME_MENU_ const string gameMenuOption[7] = { "▼===============▼", "∥     →繼續遊戲     ∥", "∥===============∥", "∥      儲存棋盤     ∥", "∥===============∥", "∥      返回主選單    ∥", "▲===============▲" }; #endif // _GAME_MENU_ #ifdef _LEFT_RIGHT_SPACE_ const string leftSpace[21] = { "∥                    ", "∥ 。------戰況顯示------。 ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ |                | ", "∥ 。----------------。 ", "∥                    " }; const string rightSpace[21] = { "                    ∥", " 。----------------。 ∥", " |                | ∥", " |                | ∥", " |                | ∥", " |                | ∥", " |                | ∥", " 。----------------。 ∥", "                    ∥", "                    ∥", " 。----------------。 ∥", " |                | ∥", " | 1P:↑↓←→ ENTER  | ∥", " | 2P:WASD SPACE  | ∥", " |                | ∥", " |   Esc  開啟選單    | ∥", " |    <   悔棋      | ∥", " |    >   暫停背景音樂  | ∥", " |                | ∥", " 。----------------。 ∥", "                    ∥" }; #endif // _LEFT_RIGHT_SPACE_ namespace { void setColor(int f = 7, int b = 0) { // 使用的常用代碼:240>>白底黑字,116>>灰底深紅字,7>>黑底白字,252>>白底紅字 // 28>>可移動位置,201>>可叫吃位置 unsigned short ForeColor = f + 16 * b; SetConsoleTextAttribute(handle, ForeColor); } // Intent:顯示/隱藏 console 的游(光)標 cursor // Pre:傳入bool,true->顯示 / false->隱藏 // Post:無 void cursorVisiable(bool flag) { GetConsoleCursorInfo(handle, &cci); cci.bVisible = flag; SetConsoleCursorInfo(handle, &cci); } // Intent:設置console游(光)標cursor 位置 // Pre:int [x]、[y],左上角為(0,0) /// (42,2)為棋盤內可移動的最左上角 // Post:無 void setConsoleCursorCoordinate(int x = 42, int y = 1) { cursorPosition.X = x; cursorPosition.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition); } // 左方空位 void printLeftSpace(int i) { // 1+20 setColor(7); cout << leftSpace[i]; } //右方空位 void printRightSpace(int i) { // 20+1 setColor(7); cout << rightSpace[i]; } void printTopBorder() { setColor(7); cout << "▼"; for (int i = 0; i < 57; i++) cout << "="; cout << "▼\n"; } void printDownBorder() { setColor(7); cout << "▲"; for (int i = 0; i < 57; i++) cout << "="; cout << "▲"; } void printChess(int i) { cout << chessChinese[i]; } void printBoard(vector<vector<int>> chessInt) { __int64 row, col; for (int i = 0; i < 21; i++) { printLeftSpace(i); for (int j = 0; j < 18; j++) { row = (__int64)(i / 2) + 1; col = (__int64)(j / 2) + 1; if (i % 2 == 1 && j % 2 == 0 && chessInt[row][col] != 0) { if (chessInt[row][col] >= 1 && chessInt[row][col] <= 7) setColor(240, 0); else if (chessInt[row][col] >= 8 && chessInt[row][col] <= 14) setColor(252, 0); printChess(chessInt[row][col]); } else { // 奇數列偶數行判斷int陣列裡面的東東 setColor(116, 0); cout << clearBoard[i][j]; } } printRightSpace(i); cout << endl; } } // 更新整個棋盤without空白 void printBoardNoSpace(vector<vector<int>> chessInt, int m = 42, int n = 1) { __int64 row, col; for (int i = 0; i < 21; i++) { setConsoleCursorCoordinate(m, n + i); for (int j = 0; j < 18; j++) { row = (__int64)(i / 2) + 1; col = (__int64)(j / 2) + 1; if (i % 2 == 1 && j % 2 == 0 && chessInt[row][col] != 0) { if (chessInt[row][col] >= 1 && chessInt[row][col] <= 7) setColor(240, 0); else if (chessInt[row][col] >= 8 && chessInt[row][col] <= 14) setColor(252, 0); printChess(chessInt[row][col]); } else { // 奇數列偶數行判斷int陣列裡面的東東 setColor(116, 0); cout << clearBoard[i][j]; } } } } // 顯示yes no對話框 bool showDialog(string msg, bool showOption = true) { setColor(132); setConsoleCursorCoordinate(42, 6); cout << "▼===============▼"; for (int i = 1; i <= 11; i++) { setConsoleCursorCoordinate(42, 6 + i); cout << "∥               ∥"; if (i == 3) { setConsoleCursorCoordinate(46, 6 + i); cout << msg; } else if (i == 8 && showOption) { setConsoleCursorCoordinate(60, 6 + i); cout << "是"; setConsoleCursorCoordinate(68, 6 + i); cout << "否"; } } setConsoleCursorCoordinate(42, 17); cout << "▲===============▲"; setConsoleCursorCoordinate(60, 14); if (!showOption) cursorVisiable(false); int commandPress = 0, x = 60; while (commandPress = _getch()) { if (showOption) { if (commandPress == KEYBOARD_LEFT || commandPress == KEYBOARD_A) { x -= 8; } else if (commandPress == KEYBOARD_RIGHT || commandPress == KEYBOARD_D) { x += 8; } else if (commandPress == KEYBOARD_ENTER || commandPress == KEYBOARD_SPACE) { if (x == 60) { return true; } else if (x == 68) { return false; } } else if (commandPress == KEYBOARD_ESCAPE) { return false; } x = (x > 68) ? 60 : x; x = (x < 60) ? 68 : x; setConsoleCursorCoordinate(x, 14); } else { cursorVisiable(true); return false; } } return false; } } Game::Game(string fileName) { // 初始化 (黑/紅) (0/1) 的回合 this->nowTurn = 0; // 初始化 棋盤檔名 this->tableFileName = fileName; //this->tableFileName = "Check.txt"; //this->tableFileName = "Test.txt"; // =====================初始化console控制元件===================== handle = GetStdHandle(STD_OUTPUT_HANDLE); cursorPosition.X = 0; cursorPosition.Y = 0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition); // =====================初始化console控制元件===================== // 初始化 [boardStatus] 、 [pointBoardStatus] for (int i = 0; i < 12; i++) { this->boardStatus.push_back(vector<int>()); this->pointBoardStatus.push_back(vector<Pieces*>()); for (int j = 0; j < 11; j++) { this->boardStatus[i].push_back(-1); this->pointBoardStatus[i].push_back(NULL); } } } Game::~Game() { // 清空vector for (int i = 0; i < this->boardStatus.size(); i++) this->boardStatus[i].erase(this->boardStatus[i].begin(), this->boardStatus[i].end()); this->boardStatus.erase(this->boardStatus.begin(), this->boardStatus.end()); for (int i = 0; i < this->pointBoardStatus.size(); i++) this->pointBoardStatus[i].erase(this->pointBoardStatus[i].begin(), this->pointBoardStatus[i].end()); this->pointBoardStatus.erase(this->pointBoardStatus.begin(), this->pointBoardStatus.end()); for (int i = 0; i < this->theLogsOfBS.size(); i++) { for (int j = 0; j < this->theLogsOfBS[i].size(); j++) { this->theLogsOfBS[i][j].erase(this->theLogsOfBS[i][j].begin(), this->theLogsOfBS[i][j].end()); } this->theLogsOfBS[i].erase(this->theLogsOfBS[i].begin(), this->theLogsOfBS[i].end()); } this->theLogsOfBS.erase(this->theLogsOfBS.begin(), this->theLogsOfBS.end()); PlaySound(NULL, NULL, 0); } void Game::showMenu() { setColor(7); // 顯示gameMenu for (int i = 0; i < (sizeof(gameMenuOption) / sizeof(gameMenuOption[0])); i++) { setConsoleCursorCoordinate(42, 5 + i); cout << gameMenuOption[i]; } // 宣告gameMenu 專屬console座標 int [y] int commandPress, y = 6; // 設定console座標位置,從(54,6)開始繪製 setConsoleCursorCoordinate(54, 6); cursorVisiable(false); while (commandPress = _getch()) { if (commandPress == KEYBOARD_UP || commandPress == KEYBOARD_W) { y -= 2; } else if (commandPress == KEYBOARD_DOWN || commandPress == KEYBOARD_S) { y += 2; } else if (commandPress == KEYBOARD_ENTER || commandPress==KEYBOARD_SPACE) { if (y == 6) { cursorVisiable(true); this->freshGameConsole(); printBoardNoSpace(this->boardStatus, 42, 1); break; } else if (y == 8) { this->saveGame(); cursorVisiable(true); this->freshGameConsole(); printBoardNoSpace(this->boardStatus, 42, 1); break; } else if (y == 10) { if (menu != NULL) { system("cls"); this->~Game(); menu->showMenu(); } } } else if (commandPress == KEYBOARD_ESCAPE) { cursorVisiable(true); this->freshGameConsole(); printBoardNoSpace(this->boardStatus, 42, 1); break; } y = (y > 10) ? 6 : y; y = (y < 6) ? 10 : y; cout << " \b\b"; setConsoleCursorCoordinate(54, y); cout << "→\b\b"; } } void Game::gameStart() { // 清空console system("cls"); // 設置視窗大小 SMALL_RECT windowSize = { 0,0,117, 22 }; SetConsoleWindowInfo(handle, TRUE, &windowSize); // 繪製遊戲畫面 setFileNameAndProcess(); printTopBorder(); printBoard(this->boardStatus); printDownBorder(); // 下背景音樂 PlaySound("Sounds/Lucid_Dreamer_2.wav", NULL, SND_FILENAME | SND_ASYNC | SND_LOOP); // 將畫面往上拉,若不將光標位置y提至0的話,console畫面將會往下一點 setConsoleCursorCoordinate(0, 0); // 顯示光標(Cursor) cursorVisiable(true); // 顯示提示,現在回合 this->showTurn(); int commandPress, x = 42, y = 20, x2 = 42, y2 = 2; if (this->nowTurn==1) setConsoleCursorCoordinate(42, 20); else setConsoleCursorCoordinate(42, 2); bool isTakingPiece = false, bkMusicStatus = true; COORDINATE virtualCoordinate = make_pair(1, 1); COORDINATE destinationCoordinate = make_pair(1, 1); vector<COORDINATE> whereCanMove; vector<COORDINATE> whereCanEat; while (commandPress = _getch()) { // 1P or 2P 控制權 if (this->nowTurn == 1) { if (commandPress == KEYBOARD_UP) { y -= 2; } else if (commandPress == KEYBOARD_DOWN) { y += 2; } else if (commandPress == KEYBOARD_LEFT) { x -= 4; } else if (commandPress == KEYBOARD_RIGHT) { x += 4; } else if (commandPress == KEYBOARD_ENTER) { if (!isTakingPiece) { // 如果現在還沒拿起棋子時: // console座標轉換為棋盤座標 virtualCoordinate.first = (y - 2) / 2 + 1; //row virtualCoordinate.second = (x - 42) / 4 + 1; //col if (this->nowTurn == 1) { // 現在回合:紅手 if (this->boardStatus[virtualCoordinate.first][virtualCoordinate.second] >= 8 && this->boardStatus[virtualCoordinate.first][virtualCoordinate.second] <= 14) { isTakingPiece = true; // 顯示提示,選取棋子 this->showChoice(this->boardStatus[virtualCoordinate.first][virtualCoordinate.second]); // 繪製可走/吃範圍 whereCanMove = this->pointBoardStatus[virtualCoordinate.first][virtualCoordinate.second]->movable(this->boardStatus); whereCanEat = this->pointBoardStatus[virtualCoordinate.first][virtualCoordinate.second]->eatable(this->boardStatus); for (int j = 0; j < whereCanMove.size(); j++) { // 棋盤座標轉換為console座標 setConsoleCursorCoordinate((whereCanMove[j].second - 1) * 4 + 42, (whereCanMove[j].first - 1) * 2 + 2); setColor(28); // row=2*y-1 col=2*x-2 cout << clearBoard[2 * whereCanMove[j].first - 1][2 * whereCanMove[j].second - 2]; } for (int j = 0; j < whereCanEat.size(); j++) { // 棋盤座標轉換為console座標 setConsoleCursorCoordinate((whereCanEat[j].second - 1) * 4 + 42, (whereCanEat[j].first - 1) * 2 + 2); setColor(201); printChess(this->boardStatus[whereCanEat[j].first][whereCanEat[j].second]); } } else { cout << "\a"; } } } else { // 如果現在拿起棋子時: // console座標轉換為棋盤座標 destinationCoordinate.first = (y - 2) / 2 + 1; //row destinationCoordinate.second = (x - 42) / 4 + 1; //col if (virtualCoordinate == destinationCoordinate) { // 如果選取原本的位置,則視為放下棋子重新選擇 isTakingPiece = false; printBoardNoSpace(this->boardStatus); // 顯示提示,現在回合,選取棋子 this->showTurn(); this->showChoice(0); } else { string chineseNotation; bool isSuccess = false; isSuccess = this->pointBoardStatus[virtualCoordinate.first] [virtualCoordinate.second] ->MoveAndEat( destinationCoordinate, this->boardStatus, this->pointBoardStatus, chineseNotation ); if (isSuccess) { this->battleStatus.push_back(chineseNotation); this->theLogsOfBS.push_back(this->boardStatus); // 下棋聲 mciSendString("play \"Sounds/下棋聲.mp3\" ", NULL, 0, 0); // 移動或吃棋成功 isTakingPiece = false; int victory = JudgeVictory(boardStatus); if (victory == BLACK) { //BLACK wins; showDialog("黑方勝利,按任意鍵回主選單", false); if (menu != NULL) { system("cls"); this->~Game(); menu->showMenu(); } } else if (victory == RED) { //RED wins; showDialog("紅方勝利,按任意鍵回主選單", false); if (menu != NULL) { system("cls"); this->~Game(); menu->showMenu(); } } this->nowTurn = (this->nowTurn == 0) ? 1 : 0; printBoardNoSpace(this->boardStatus, 42, 1); // 顯示提示,現在回合,選取棋子 this->showTurn(); this->showChoice(0); this->showBattleStatus(); } else { cout << "\a"; } } } } } else if (this->nowTurn == 0) { if (commandPress == KEYBOARD_W) { y2 -= 2; } else if (commandPress == KEYBOARD_S) { y2 += 2; } else if (commandPress == KEYBOARD_A) { x2 -= 4; } else if (commandPress == KEYBOARD_D) { x2 += 4; } else if (commandPress == KEYBOARD_SPACE) { if (!isTakingPiece) { // 如果現在還沒拿起棋子時: // console座標轉換為棋盤座標 virtualCoordinate.first = (y2 - 2) / 2 + 1; //row virtualCoordinate.second = (x2 - 42) / 4 + 1; //col if (this->nowTurn == 0) { // 現在回合:黑手 if (this->boardStatus[virtualCoordinate.first][virtualCoordinate.second] >= 1 && this->boardStatus[virtualCoordinate.first][virtualCoordinate.second] <= 7) { isTakingPiece = true; // 顯示提示,選取棋子 this->showChoice(this->boardStatus[virtualCoordinate.first][virtualCoordinate.second]); // 繪製可走/吃範圍 whereCanMove = this->pointBoardStatus[virtualCoordinate.first][virtualCoordinate.second]->movable(this->boardStatus); whereCanEat = this->pointBoardStatus[virtualCoordinate.first][virtualCoordinate.second]->eatable(this->boardStatus); for (int j = 0; j < whereCanMove.size(); j++) { // 棋盤座標轉換為console座標 setConsoleCursorCoordinate((whereCanMove[j].second - 1) * 4 + 42, (whereCanMove[j].first - 1) * 2 + 2); setColor(28); // row=2*y-1 col=2*x-2 cout << clearBoard[2 * whereCanMove[j].first - 1][2 * whereCanMove[j].second - 2]; } for (int j = 0; j < whereCanEat.size(); j++) { // 棋盤座標轉換為console座標 setConsoleCursorCoordinate((whereCanEat[j].second - 1) * 4 + 42, (whereCanEat[j].first - 1) * 2 + 2); setColor(201); printChess(this->boardStatus[whereCanEat[j].first][whereCanEat[j].second]); } } else { cout << "\a"; } } } else { // 如果現在拿起棋子時: // console座標轉換為棋盤座標 destinationCoordinate.first = (y2 - 2) / 2 + 1; //row destinationCoordinate.second = (x2 - 42) / 4 + 1; //col if (virtualCoordinate == destinationCoordinate) { // 如果選取原本的位置,則視為放下棋子重新選擇 isTakingPiece = false; printBoardNoSpace(this->boardStatus); // 顯示提示,現在回合,選取棋子 this->showTurn(); this->showChoice(0); } else { string chineseNotation; bool isSuccess = false; isSuccess = this->pointBoardStatus[virtualCoordinate.first] [virtualCoordinate.second] ->MoveAndEat( destinationCoordinate, this->boardStatus, this->pointBoardStatus, chineseNotation ); if (isSuccess) { this->battleStatus.push_back(chineseNotation); this->theLogsOfBS.push_back(this->boardStatus); // 下棋聲 mciSendString("play \"Sounds/下棋聲.mp3\" ", NULL, 0, 0); // 移動或吃棋成功 isTakingPiece = false; int victory = JudgeVictory(boardStatus); if (victory == BLACK) { //BLACK wins; showDialog("黑方勝利,按任意鍵回主選單", false); if (menu != NULL) { system("cls"); this->~Game(); menu->showMenu(); } } else if (victory == RED) { //RED wins; showDialog("紅方勝利,按任意鍵回主選單", false); if (menu != NULL) { system("cls"); this->~Game(); menu->showMenu(); } } this->nowTurn = (this->nowTurn == 0) ? 1 : 0; printBoardNoSpace(this->boardStatus, 42, 1); // 顯示提示,現在回合,選取棋子 this->showTurn(); this->showChoice(0); this->showBattleStatus(); } else { cout << "\a"; } } } } } if (commandPress == KEYBOARD_LEFT_SHIFT) { if (this->battleStatus.size() >= 2) { // 放下棋子 isTakingPiece = false; this->showChoice(0); if (showDialog("是否要悔棋呢?")) { // 刪除棋盤和戰況紀錄 this->theLogsOfBS.erase(this->theLogsOfBS.end() - 2, this->theLogsOfBS.end()); this->battleStatus.erase(this->battleStatus.end() - 2, this->battleStatus.end()); if (this->theLogsOfBS.size() == 0) setFileNameAndProcess(); else this->boardStatus = *(this->theLogsOfBS.end() - 1); boardStatusToPointBoardStatus(); setColor(7); // 全版更新 this->freshGameConsole(); } else { // 更新第二次畫面,較不會顯示錯誤 printBoardNoSpace(this->boardStatus); printBoardNoSpace(this->boardStatus); } } else { cout << "\a"; } } else if (commandPress == KEYBOARD_RIGHT_SHIFT) { if (bkMusicStatus) { PlaySound(NULL, NULL, 0); bkMusicStatus = false; } else { PlaySound("Sounds/Lucid_Dreamer_2.wav", NULL, SND_FILENAME | SND_ASYNC | SND_LOOP); bkMusicStatus = true; } } else if (commandPress == KEYBOARD_ESCAPE) { isTakingPiece = false; this->showTurn(); this->showChoice(0); this->showMenu(); } x = (x > (42 + 32)) ? 42 : x; x = (x < 42) ? (42 + 32) : x; y = (y > (2 + 18)) ? 2 : y; y = (y < 2) ? (2 + 18) : y; x2 = (x2 > (42 + 32)) ? 42 : x2; x2 = (x2 < 42) ? (42 + 32) : x2; y2 = (y2 > (2 + 18)) ? 2 : y2; y2 = (y2 < 2) ? (2 + 18) : y2; if (this->nowTurn == 1) setConsoleCursorCoordinate(x, y); else setConsoleCursorCoordinate(x2, y2); } } void Game::setFileNameAndProcess() { fstream inputStream; inputStream.open(("boardText/" + this->tableFileName)); if (!inputStream) // operator! is used here { cout << "沒有這個檔案\n"; system("pause"); exit(1); } else { bool isBlackOrRed = false; for (int i = 1; i < 11; i++) { for (int j = 1; j < 10; j++) { inputStream >> boardStatus[i][j]; isBlackOrRed = (boardStatus[i][j] >= 1 && boardStatus[i][j] <= 7) ? false : true; // 建立pointboardStatus if (boardStatus[i][j] == 1 || boardStatus[i][j]==8) { this->pointBoardStatus[i][j] = new ClassGeneral(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 2 || boardStatus[i][j]==9) { this->pointBoardStatus[i][j] = new ClassGuard(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 3 || boardStatus[i][j]==10) { this->pointBoardStatus[i][j] = new ClassMinister(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 4 || boardStatus[i][j]==11) { this->pointBoardStatus[i][j] = new ClassRook(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 5 || boardStatus[i][j]==12) { this->pointBoardStatus[i][j] = new ClassHorse(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 6 || boardStatus[i][j]==13) { this->pointBoardStatus[i][j] = new ClassCannon(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 7 || boardStatus[i][j]==14) { this->pointBoardStatus[i][j] = new ClassSoldier(i, j, isBlackOrRed); } // 結束建立pointboardStatus } } inputStream >> this->nowTurn; whoStart = nowTurn; inputStream.close(); } } void Game::showTurn() { setConsoleCursorCoordinate(86, 4); setColor(27); cout << "現在輪到 "; if (this->nowTurn == 1) { setColor(76); cout << "紅色方"; } else { setColor(128); cout << "黑色方"; } setColor(27); cout << "下棋"; } void Game::showBattleStatus() { if (battleStatus.size() <= 8) { int i = 1; for (vector<string>::iterator iter = battleStatus.begin(); iter != battleStatus.end(); iter++,i++) { setConsoleCursorCoordinate(12, 2 + 2 * i); cout << std::setw(4) << i << " ";// << *iter; if ((whoStart + i) % 2 == 1) { setColor(240); cout << "黑"; } else { setColor(252); cout << "紅"; } setColor(7); cout << ":" << *iter; } } else if (battleStatus.size() > 7) { vector<string>::reverse_iterator r_iter = battleStatus.rbegin(); for (int i = 0; i <= 7; i++) { setConsoleCursorCoordinate(12, 4 + (2 * i)); cout << std::setw(4) << battleStatus.size() - (7 - i) << " "; if ((whoStart + battleStatus.size() - (7 - i)) % 2 == 1) { setColor(240); cout << "黑"; } else { setColor(252); cout << "紅"; } setColor(7); cout << ":" << *(r_iter + (7 - i)); } } //setConsoleCursorCoordinate(12, 4); } void Game::showChoice(int choice) { setConsoleCursorCoordinate(90, 6); if (choice == 0) { setColor(7); cout << "      "; } else { setColor(27); cout << "您選擇了 "; if (this->nowTurn == 1) { setColor(76); printChess(choice); } else { setColor(128); printChess(choice); } } } int Game::JudgeVictory(const vector<vector<int>>& boardStatus) { //查找將與帥的位置 vector<int>::const_iterator iterB, iterR; int ib, ir; //ib from 1~3(將) for (ib = 1; ib <= 3; ib++) { iterB = find(boardStatus[ib].begin(), boardStatus[ib].end(), 1); if (iterB != boardStatus[ib].end() || ib == 3) break; } //ir from 8~10(帥) for (ir = 8; ir <= 10; ir++) { iterR = find(boardStatus[ir].begin(), boardStatus[ir].end(), 8); if (iterR != boardStatus[ir].end() || ir == 10) break; } if (iterB != boardStatus[ib].end() && iterR != boardStatus[ir].end()) { Pieces BG(*pointBoardStatus[ib][iterB - boardStatus[ib].begin()]); Pieces RG(*pointBoardStatus[ir][iterR - boardStatus[ir].begin()]); if (BG.FetchPosition().second == RG.FetchPosition().second) {//在同一個column上 int j = BG.FetchPosition().second; int ib = BG.FetchPosition().first; int ir = RG.FetchPosition().first; int k = 1; while (ib + k < boardBottom && (boardStatus[ib + k][j] == 0)) { k++; } ib += k; if (ib == ir) {//射箭 if (nowTurn == BLACK) {//黑方 return RED;//紅方獲勝 } else {//紅方 return BLACK;//黑方獲勝 } } } return -1; } else if (iterB == boardStatus[ib].end()) { return RED; } else if (iterR == boardStatus[ir].end()) { return BLACK; } } void Game::boardStatusToPointBoardStatus() { bool isBlackOrRed = false; for (int i = 1; i < 11; i++) { for (int j = 1; j < 10; j++) { isBlackOrRed = (this->boardStatus[i][j] >= 1 && this->boardStatus[i][j] <= 7) ? false : true; // 建立pointboardStatus if (boardStatus[i][j] == 1 || boardStatus[i][j] == 8) { this->pointBoardStatus[i][j] = new ClassGeneral(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 2 || boardStatus[i][j] == 9) { this->pointBoardStatus[i][j] = new ClassGuard(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 3 || boardStatus[i][j] == 10) { this->pointBoardStatus[i][j] = new ClassMinister(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 4 || boardStatus[i][j] == 11) { this->pointBoardStatus[i][j] = new ClassRook(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 5 || boardStatus[i][j] == 12) { this->pointBoardStatus[i][j] = new ClassHorse(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 6 || boardStatus[i][j] == 13) { this->pointBoardStatus[i][j] = new ClassCannon(i, j, isBlackOrRed); } else if (boardStatus[i][j] == 7 || boardStatus[i][j] == 14) { this->pointBoardStatus[i][j] = new ClassSoldier(i, j, isBlackOrRed); } // 結束建立pointboardStatus } } } void Game::saveGame() { setConsoleCursorCoordinate(42, 5); cout << "▼===============▼"; setConsoleCursorCoordinate(42, 6); cout << "∥               ∥"; setConsoleCursorCoordinate(42, 7); cout << "∥               ∥"; setConsoleCursorCoordinate(42, 8); cout << "∥ 輸入檔名:         ∥"; setConsoleCursorCoordinate(42, 9); cout << "∥               ∥"; setConsoleCursorCoordinate(42, 10); cout << "∥       (輸入quit返回)∥"; setConsoleCursorCoordinate(42, 11); cout << "▲===============▲"; string fileName = ""; cursorVisiable(true); setConsoleCursorCoordinate(56, 8); getline(cin, fileName); if (fileName == "quit" || fileName == "Initial" || fileName == "Check" || fileName == "Test") { cout << "\a"; } else { fstream output("boardText/" + fileName + ".txt",ios::out); if (output.is_open()) { for (int i = 1; i < 11; i++) { for (int j = 1; j < 10; j++) { if (j == 9) { output << this->boardStatus[i][j] << endl; } else { output << this->boardStatus[i][j] << " "; } } } output << this->nowTurn; output.close(); } } } void Game::freshGameConsole() { // 全版更新 setColor(7); system("cls"); setConsoleCursorCoordinate(0, 0); printTopBorder(); printBoard(this->boardStatus); printDownBorder(); this->showTurn(); this->showChoice(0); this->showBattleStatus(); }
27.896728
124
0.522413
Zhang-Yu-Bo
a5314f327ad9ee307932ed6002d2a2ae77ab8429
362
hpp
C++
addons/uh60_ui/uiConfig/turretInfo.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
14
2021-02-11T23:23:21.000Z
2021-09-08T05:36:47.000Z
addons/uh60_ui/uiConfig/turretInfo.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
130
2021-09-09T21:43:16.000Z
2022-03-30T09:00:37.000Z
addons/uh60_ui/uiConfig/turretInfo.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
11
2021-02-18T19:55:51.000Z
2021-09-01T17:08:47.000Z
class RscUnitInfo; class Rsc_vtx_MELB_Turret_UnitInfo: RscUnitInfo { idd = 300; onLoad = "uiNamespace setVariable [""vtx_uh60_flir_ui"",(_this select 0)];['onLoad',_this,'RscUnitInfo','IGUI'] call (uinamespace getvariable 'BIS_fnc_initDisplay');"; controls[] = {"MELB_GUI"}; class VScrollbar; class HScrollbar; #include "MELB_GUI.hpp" };
32.909091
171
0.709945
ZHANGTIANYAO1
a53a81743ea33f490a21605cd01d9d0f294e193e
285
cpp
C++
sum function.cpp
0ishita-jana/-dev-info-day1
e6053be728856b3a92d3137bdfd30e16700f7d06
[ "MIT" ]
null
null
null
sum function.cpp
0ishita-jana/-dev-info-day1
e6053be728856b3a92d3137bdfd30e16700f7d06
[ "MIT" ]
null
null
null
sum function.cpp
0ishita-jana/-dev-info-day1
e6053be728856b3a92d3137bdfd30e16700f7d06
[ "MIT" ]
null
null
null
#include<stdio.h> #include<conio.h> int sum(); int main() { int a; a=sum(); printf("%d",a); getch(); } int sum() { int i=1,n=5,l=0; while(i<=n) { int j=i; int s=1; while(j!=0) { s=s*j; j--; } l=l+s+i; i++; } return l; }
8.382353
18
0.403509
0ishita-jana
a53e1c0410c4143ce59c0642900ce1202c046dfb
1,830
cpp
C++
tools/paint/mymanipulatedframe.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
118
2016-11-01T06:01:44.000Z
2022-03-30T05:20:19.000Z
tools/paint/mymanipulatedframe.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
56
2016-09-30T09:29:36.000Z
2022-03-31T17:15:32.000Z
tools/paint/mymanipulatedframe.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
28
2016-07-31T23:48:51.000Z
2021-05-25T05:32:47.000Z
#include "mymanipulatedframe.h" MyManipulatedFrame::MyManipulatedFrame() { m_threshold = 20; m_keepsGrabbingMouse = false; m_onlyRotate = false; m_onlyTranslate = false; } int MyManipulatedFrame::threshold() { return m_threshold; } bool MyManipulatedFrame::onlyRotate() { return m_onlyRotate; } bool MyManipulatedFrame::onlyTranslate() { return m_onlyTranslate; } void MyManipulatedFrame::setThreshold(int t) { m_threshold = qMax(10, t); } void MyManipulatedFrame::setOnlyRotate(bool b) { m_onlyRotate = b; if (m_onlyRotate) m_onlyTranslate = false; } void MyManipulatedFrame::setOnlyTranslate(bool b) { m_onlyTranslate = b; if (m_onlyTranslate) m_onlyRotate = false; } void MyManipulatedFrame::mousePosition(int& x, int& y) { x = m_lastX; y = m_lastY; } void MyManipulatedFrame::checkIfGrabsMouse(int x, int y, const Camera* const camera) { m_lastX = x; m_lastY = y; const Vec proj = camera->projectedCoordinatesOf(position()); setGrabsMouse(m_keepsGrabbingMouse || ((fabs(x-proj.x) < m_threshold) && (fabs(y-proj.y) < m_threshold)) ); } void MyManipulatedFrame::mousePressEvent(QMouseEvent* const event, Camera* const camera) { ManipulatedFrame::mousePressEvent(event, camera); if (grabsMouse()) m_keepsGrabbingMouse = true; } void MyManipulatedFrame::mouseMoveEvent(QMouseEvent* const event, Camera* const camera) { if (m_onlyTranslate && action_ == QGLViewer::ROTATE) action_ = QGLViewer::TRANSLATE; else if (m_onlyRotate && action_ == QGLViewer::TRANSLATE) action_ = QGLViewer::ROTATE; ManipulatedFrame::mouseMoveEvent(event, camera); } void MyManipulatedFrame::mouseReleaseEvent(QMouseEvent* const event, Camera* const camera) { ManipulatedFrame::mouseReleaseEvent(event, camera); m_keepsGrabbingMouse = false; }
23.766234
68
0.730055
shouhengli
a542fba1d0b39e9c3c9f9c16078c711aac1ea7b0
11,588
cpp
C++
jblib/jreadhdr.cpp
neoflame99/jbmat
cec3102d8a1685d8cff6b83b122b895f0aaa78c7
[ "MIT" ]
null
null
null
jblib/jreadhdr.cpp
neoflame99/jbmat
cec3102d8a1685d8cff6b83b122b895f0aaa78c7
[ "MIT" ]
null
null
null
jblib/jreadhdr.cpp
neoflame99/jbmat
cec3102d8a1685d8cff6b83b122b895f0aaa78c7
[ "MIT" ]
null
null
null
#include "jreadhdr.h" #include <QByteArray> #include <stdio.h> #include <QRegExp> #include <QStringList> #include <math.h> double rgb2xyz_bt709[3][3] = { {0.4124564, 0.3575761, 0.1804375}, {0.2126729, 0.7151522, 0.0721750}, {0.0193339, 0.1191920, 0.9503041} }; double xyz2rgb_bt709[3][3] = { { 3.2404542, -1.5371385, -0.4985314}, {-0.9692660, 1.8760108, 0.0415560}, { 0.0556434, -0.2040259, 1.0572252} }; void Jreadhdr::init(){ ysize = 0; xsize = 0; rgbe_format = 0; isHdrfile = false; exposure = 1.0; hasValidData = false; rgbe = 0; // initial value is null dat64f = 0; // inital null maxval = 0.0; colorformat = 0; // 0 : rgb, 1: xyz, 2: Yxy ... } Jreadhdr::Jreadhdr() { init(); } Jreadhdr::Jreadhdr(QFile& file) { init(); read_hdr(file); } Jreadhdr::~Jreadhdr() { if( rgbe != 0) delete rgbe; if(dat64f != 0) delete dat64f; rgbe = 0; // null pointer dat64f = 0; // null pointer } int Jreadhdr::read_hdr(QFile& file){ int ypos, xpos; int t; bool isOk; QStringList strlist; if( !file.open(QIODevice::ReadOnly | QIODevice::Text) ){ fprintf(stderr, "Not open file!"); return -2; } while( !file.atEnd()) { QString line = file.readLine().trimmed(); if(line.contains(QString("#?RADIANCE"),Qt::CaseInsensitive)){ isHdrfile = true; } else if(line.contains(QString("format"),Qt::CaseInsensitive) ){ t = line.indexOf(QString("=")); if ( line.mid(t+1).compare(QString("32-bit_rle_rgbe"),Qt::CaseInsensitive) ==0){ rgbe_format = 0; colorformat = 0; }else if( line.mid(t+1).compare(QString("32-bit_rle_xyze"),Qt::CaseInsensitive)==0){ rgbe_format = 1; colorformat = 1; } } else if(line.contains(QString("exposure"),Qt::CaseInsensitive) ){ t = line.indexOf(QString("=")); exposure = line.mid(t+1).toDouble(&isOk); if( !isOk) exposure = 1.0f; } else if(line.contains(QString("pvalue"),Qt::CaseInsensitive) ){ t = line.indexOf(QString("+e")); strlist = line.mid(t).trimmed().split(QRegExp("\\s")); exposure = strlist.at(1).toDouble(&isOk); if( !isOk) exposure = 1.0f; } else if( line.isEmpty() ) { QString headfl = file.readLine().simplified(); ypos = headfl.indexOf(QString("Y"), 0 , Qt::CaseInsensitive); xpos = headfl.indexOf(QString("X"), 0 , Qt::CaseInsensitive); ysize = headfl.mid(ypos+1,xpos-ypos-2).toInt(); xsize = headfl.mid(xpos+1).toInt(); break; } } if( !isHdrfile) { fprintf(stderr,"The file is not Radiance file!\n"); return -2; } fprintf(stdout, "ysize : %zd , xsize : %zd \n ", ysize , xsize); // read binary from here file.setTextModeEnabled(false); QByteArray hdr_data = file.readAll(); size_t dlen = (ysize * xsize) << 2; rgbe = new unsigned char [dlen]; if (rgbe == 0){ fprintf(stderr,"Memory allocation error\n"); return -1; } unsigned char a,b; unsigned char c,d; unsigned char rlc; unsigned char lc, rdat; size_t xcnt = 0, cxcnt = 0; size_t ycnt = 0; unsigned char *pdata=0; bool c0, c1, c2, c3; unsigned int hbyteX, lbyteX; hbyteX = this->xsize >> 8; lbyteX = this->xsize - (hbyteX << 8); pdata = (unsigned char*)hdr_data.data(); a = pdata[0]; b = pdata[1]; c = pdata[2]; d = pdata[3]; if( dlen == hdr_data.length()) { // uncompressed for ( size_t y=0; y < dlen; y++) rgbe[y] = pdata[y]; }else if( a==2 && b==2 && c==hbyteX && d==lbyteX) { // check scanline codes for New RLE for (size_t y=0; y < ysize; y++){ ycnt = (y * xsize); a = *pdata++; b = *pdata++; c = *pdata++; d = *pdata++; c0 = a == 0x02; c1 = b == 0x02; c2 = c == hbyteX; c3 = d == lbyteX; if( c0 && c1 && c2 && c3){ // New RLE // decoding each channel for the scanline for( size_t ccnt = 0; ccnt < 4; ccnt++){ xcnt = 0; while(xcnt < xsize){ //rlc = (unsigned char)hdr_data.at(idx++); rlc = *pdata++; if(rlc <= 128){ // read literally values for(lc = 0; lc < rlc; lc++ ){ //rdat = (unsigned char)hdr_data.at(idx++); rdat = *pdata++; cxcnt = ((ycnt + xcnt+lc) << 2) + ccnt; rgbe[cxcnt] = rdat; } }else{ // read run length value rlc = rlc - 128; rdat = *pdata++; for(lc = 0; lc < rlc; lc++){ cxcnt = ((ycnt + xcnt+lc) << 2) + ccnt; rgbe[cxcnt] = rdat; } } xcnt += rlc; if(xcnt > xsize) fprintf(stdout," run length coding error : xcnt = %zd \n", xcnt); } } } } }else { // Old RLE int num=0; int consecRpt = 0; xcnt = 0; cxcnt = 0; for (size_t i=0; i < hdr_data.length(); i+=4){ a = pdata[i ]; b = pdata[i+1]; c = pdata[i+2]; d = pdata[i+3]; if( a==1 && b==1 && c==1){ num = d << (consecRpt*8); xcnt = cxcnt-4; // store the last rgbe point for( size_t k=0; k < num; k++){ rgbe[cxcnt++] = rgbe[xcnt ]; rgbe[cxcnt++] = rgbe[xcnt+1]; rgbe[cxcnt++] = rgbe[xcnt+2]; rgbe[cxcnt++] = rgbe[xcnt+3]; } consecRpt++; }else{ rgbe[cxcnt++] = a; rgbe[cxcnt++] = b; rgbe[cxcnt++] = (unsigned char)c; rgbe[cxcnt++] = (unsigned char)d; consecRpt = 0; } } } hasValidData = true; return 0; } int Jreadhdr::conv_rgbe2rgb64f(bool normalizing){ if( !hasValidData ) return -2; dat64f = new double [ysize*xsize*3]; if(dat64f ==0 ) { fprintf(stderr,"In cov_rgbe2dat64f: Memory allocation error for dat64f!\n"); return -1; } size_t xc, cxcnt; size_t ypos = 0; float rt, gt, bt, et; double max = -1; for(size_t y=0; y < ysize; y++){ ypos = y * xsize; for(size_t x=0; x < xsize; x++){ cxcnt = (ypos + x) << 2; rt = rgbe[cxcnt ]; gt = rgbe[cxcnt+1]; bt = rgbe[cxcnt+2]; et = rgbe[cxcnt+3]; if(rgbe[cxcnt+3]==0){ rt = 0.0f; gt = 0.0f; bt = 0.0f; }else{ rt = (rt+0.5) * pow(2,et-128-8) ; gt = (gt+0.5) * pow(2,et-128-8) ; bt = (bt+0.5) * pow(2,et-128-8) ; } xc = ( ypos + x ); xc = (xc << 1) + xc ; // xc = (ypos+x)*3; dat64f[xc ] = rt; dat64f[xc+1] = gt; dat64f[xc+2] = bt; max = (max < rt) ? rt : max; max = (max < gt) ? gt : max; max = (max < bt) ? bt : max; } } this->maxval = max; // normalizing if(normalizing){ for(size_t y=0; y < ysize*xsize*3; y++){ dat64f[y ] /= max; } } return 0; } int Jreadhdr::conv_rgb2xyz(){ if( colorformat != 0){ fprintf(stderr," The color format of the image is not RGB\n"); return -1; } double x, y, z; for(size_t i=0; i < xsize*ysize*3; i+=3){ x = rgb2xyz_bt709[0][0] * dat64f[i] + rgb2xyz_bt709[0][1] *dat64f[i+1] + rgb2xyz_bt709[0][2] *dat64f[i+2]; y = rgb2xyz_bt709[1][0] * dat64f[i] + rgb2xyz_bt709[1][1] *dat64f[i+1] + rgb2xyz_bt709[1][2] *dat64f[i+2]; z = rgb2xyz_bt709[2][0] * dat64f[i] + rgb2xyz_bt709[2][1] *dat64f[i+1] + rgb2xyz_bt709[2][2] *dat64f[i+2]; dat64f[i] = x; dat64f[i+1]= y; dat64f[i+2]= z; } colorformat = 1; return 0; } int Jreadhdr::conv_xyz2rgb(){ if( colorformat != 1){ fprintf(stderr," The color format of the image is not XYZ\n"); return -1; } double r, g, b; for(size_t i=0; i < xsize*ysize*3; i+=3){ r = xyz2rgb_bt709[0][0] * dat64f[i] + xyz2rgb_bt709[0][1] *dat64f[i+1] + xyz2rgb_bt709[0][2] *dat64f[i+2]; g = xyz2rgb_bt709[1][0] * dat64f[i] + xyz2rgb_bt709[1][1] *dat64f[i+1] + xyz2rgb_bt709[1][2] *dat64f[i+2]; b = xyz2rgb_bt709[2][0] * dat64f[i] + xyz2rgb_bt709[2][1] *dat64f[i+1] + xyz2rgb_bt709[2][2] *dat64f[i+2]; dat64f[i] = r; dat64f[i+1]= g; dat64f[i+2]= b; } colorformat = 0; return 0; } int Jreadhdr::conv_rgb2Yxy(){ if( colorformat != 0){ fprintf(stderr," The color format of the image is not RGB\n"); return -1; } double X, Y, Z, W, x, y; double r,g,b; for(size_t i=0; i < xsize*ysize*3; i+=3){ r = dat64f[i ]; g = dat64f[i+1]; b = dat64f[i+2]; X = rgb2xyz_bt709[0][0] * dat64f[i] + rgb2xyz_bt709[0][1] *dat64f[i+1] + rgb2xyz_bt709[0][2] *dat64f[i+2]; Y = rgb2xyz_bt709[1][0] * dat64f[i] + rgb2xyz_bt709[1][1] *dat64f[i+1] + rgb2xyz_bt709[1][2] *dat64f[i+2]; Z = rgb2xyz_bt709[2][0] * dat64f[i] + rgb2xyz_bt709[2][1] *dat64f[i+1] + rgb2xyz_bt709[2][2] *dat64f[i+2]; W = X + Y + Z; if( W <= 0.0) { x = 0.0; y = 0.0; }else{ x = X/W; y = Y/W; } dat64f[i ]= Y; dat64f[i+1]= x; dat64f[i+2]= y; } colorformat = 2; return 0; } int Jreadhdr::conv_Yxy2rgb(){ if( colorformat != 2){ fprintf(stderr," The color format of the image is not XYZ\n"); return -1; } double r, g, b; double X,Y,Z,x,y,W; for(size_t i=0; i < xsize*ysize*3; i+=3){ Y = dat64f[i ]; x = dat64f[i+1]; y = dat64f[i+2]; W = Y/y; X = x * W; Z = W-Y-X; r = xyz2rgb_bt709[0][0] *X + xyz2rgb_bt709[0][1] *Y + xyz2rgb_bt709[0][2] *Z; g = xyz2rgb_bt709[1][0] *X + xyz2rgb_bt709[1][1] *Y + xyz2rgb_bt709[1][2] *Z; b = xyz2rgb_bt709[2][0] *X + xyz2rgb_bt709[2][1] *Y + xyz2rgb_bt709[2][2] *Z; dat64f[i ]= r; dat64f[i+1]= g; dat64f[i+2]= b; } colorformat = 0; return 0; }
32.01105
115
0.437608
neoflame99
a54488a6e69fa8684cd5f54150f4b0f5c88ba363
4,095
cpp
C++
src/gui_statusbar_glues.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
50
2015-01-15T10:00:31.000Z
2022-02-04T20:45:25.000Z
src/gui_statusbar_glues.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
88
2020-03-15T17:40:04.000Z
2022-03-15T08:21:44.000Z
src/gui_statusbar_glues.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
19
2017-03-11T04:32:01.000Z
2022-01-12T22:47:12.000Z
#include "lxgui/gui_statusbar.hpp" #include "lxgui/gui_uiobject_tpl.hpp" #include "lxgui/gui_texture.hpp" #include "lxgui/gui_out.hpp" #include <sol/state.hpp> /** A @{Frame} representing a variable-length bar. * This frame has three main properties: a minimum value, a * maximum value, and a current value that must be contained * between the minimum and maximum values. The frame will * render a textured bar that will either be full, empty, or * anything in between depending on the current value. * * This can be used to display health bars, or progress bars. * * __Events.__ Hard-coded events available to all @{StatusBar}s, * in addition to those from @{Frame}: * * - `OnValueChanged`: Triggered whenever the value represented by * the status bar changes. This is triggered by @{StatusBar:set_value}. * This can also be triggered by @{StatusBar:set_min_max_values} if * the previous value would not satisfy the new constraints. * * Inherits all methods from: @{UIObject}, @{Frame}. * * Child classes: none. * @classmod StatusBar */ namespace lxgui { namespace gui { void status_bar::register_on_lua(sol::state& mLua) { auto mClass = mLua.new_usertype<status_bar>("StatusBar", sol::base_classes, sol::bases<uiobject, frame>(), sol::meta_function::index, member_function<&status_bar::get_lua_member_>(), sol::meta_function::new_index, member_function<&status_bar::set_lua_member_>()); /** @function get_min_max_values */ mClass.set_function("get_min_max_values", [](const status_bar& mSelf) { return std::make_pair(mSelf.get_min_value(), mSelf.get_max_value()); }); /** @function get_orientation */ mClass.set_function("get_orientation", [](const status_bar& mSelf) { switch (mSelf.get_orientation()) { case status_bar::orientation::VERTICAL : return "VERTICAL"; case status_bar::orientation::HORIZONTAL : return "HORIZONTAL"; default: return ""; } }); /** @function get_status_bar_color */ mClass.set_function("get_status_bar_color", [](const status_bar& mSelf) { const color& mColor = mSelf.get_bar_color(); return std::make_tuple(mColor.r, mColor.g, mColor.b, mColor.a); }); /** @function get_status_bar_texture */ mClass.set_function("get_status_bar_texture", member_function< // select the right overload for Lua static_cast<const utils::observer_ptr<texture>& (status_bar::*)()>(&status_bar::get_bar_texture)>()); /** @function get_value */ mClass.set_function("get_value", member_function<&status_bar::get_value>()); /** @function is_reversed */ mClass.set_function("is_reversed", member_function<&status_bar::is_reversed>()); /** @function set_min_max_values */ mClass.set_function("set_min_max_values", member_function<&status_bar::set_min_max_values>()); /** @function set_orientation */ mClass.set_function("set_orientation", member_function< // select the right overload for Lua static_cast<void (status_bar::*)(const std::string&)>(&status_bar::set_orientation)>()); /** @function set_status_bar_color */ mClass.set_function("set_status_bar_color", sol::overload( [](status_bar& mSelf, float fR, float fG, float fB, sol::optional<float> fA) { mSelf.set_bar_color(color(fR, fG, fB, fA.value_or(1.0f))); }, [](status_bar& mSelf, const std::string& sColor) { mSelf.set_bar_color(color(sColor)); })); /** @function set_status_bar_texture */ mClass.set_function("set_status_bar_texture", member_function<&status_bar::set_bar_texture>()); /** @function set_value */ mClass.set_function("set_value", member_function<&status_bar::set_value>()); /** @function set_reversed */ mClass.set_function("set_reversed", member_function<&status_bar::set_reversed>()); } } }
33.842975
110
0.659829
cschreib
a544e9ad39cd908fde483289df4167d2edddca6d
972
cpp
C++
src/AnalysisObjectives.cpp
ClaudeTO80/Opti_plus_plus
772bdce297f2b52455ba483b747890362d97beb4
[ "MIT" ]
4
2020-02-03T17:05:24.000Z
2022-01-25T23:02:40.000Z
src/AnalysisObjectives.cpp
ClaudeTO80/Opti_plus_plus
772bdce297f2b52455ba483b747890362d97beb4
[ "MIT" ]
null
null
null
src/AnalysisObjectives.cpp
ClaudeTO80/Opti_plus_plus
772bdce297f2b52455ba483b747890362d97beb4
[ "MIT" ]
null
null
null
#include "AnalysisObjectives.h" using namespace std; using namespace AnalysisGenerator; AnalysisObjective::AnalysisObjective(std::string name, ObjDir dir) : name_(name), dir_(dir) {} shared_ptr<AnalysisObjective> AnalysisObjectiveCreator::createObjective(const std::string& name, AnalysisObjective::ObjDir dir) { if (name.empty()) return {}; else return std::shared_ptr<AnalysisObjective>(new AnalysisObjective(name, dir)); } std::shared_ptr<AnalysisObjective> AnalysisObjectives::addObjective(shared_ptr<AnalysisObjective>& obj) { if (obj.get()) { objsVect_.push_back(obj); objs_.insert(make_pair(obj->name(), obj)); pos_.insert(make_pair(obj->name(), (int)objsVect_.size() - 1)); } return obj; } std::shared_ptr<AnalysisObjective> AnalysisObjectives::addObjective(std::string name, AnalysisObjective::ObjDir dir) { auto temp = AnalysisObjectiveCreator::createObjective(name, dir); return addObjective(temp); }
28.588235
128
0.736626
ClaudeTO80
a54951c18e2dda94bb3a5e8d8ddf2b89a10d51f3
2,481
cpp
C++
app/src/main/cpp/fire/util/data_texture_pair.cpp
Schitrus/DATX02-20-21
4f0beb6a85ce2ed71875df2277f8c4b80214ebd9
[ "MIT" ]
1
2020-02-20T11:41:43.000Z
2020-02-20T11:41:43.000Z
app/src/main/cpp/fire/util/data_texture_pair.cpp
Schitrus/DATX02-20-21
4f0beb6a85ce2ed71875df2277f8c4b80214ebd9
[ "MIT" ]
null
null
null
app/src/main/cpp/fire/util/data_texture_pair.cpp
Schitrus/DATX02-20-21
4f0beb6a85ce2ed71875df2277f8c4b80214ebd9
[ "MIT" ]
null
null
null
// // Created by kirderf1 on 2020-03-29. // #include "data_texture_pair.h" #include <GLES3/gl31.h> #include <glm/glm.hpp> #include "helper.h" #include <android/log.h> #define LOG_TAG "Texture" #define LOG_ERROR(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) using namespace glm; DataTexturePair::~DataTexturePair() { glDeleteTextures(1, &dataTexture); glDeleteTextures(1, &resultTexture); } void DataTexturePair::clearData(){ bindData(GL_TEXTURE0); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); for(int i = 0; i < size.z; i++){ bindToFramebuffer(i); glClear(GL_COLOR_BUFFER_BIT); } } void DataTexturePair::initScalarData(float scaleFactor, ivec3 size, float* data) { this->scaleFactor = scaleFactor; this->size = size; type = SCALAR; createScalar3DTexture(dataTexture, size, data); createScalar3DTexture(resultTexture, size, (float*)nullptr); } void DataTexturePair::initVectorData(float scaleFactor, ivec3 size, vec3* data) { this->scaleFactor = scaleFactor; this->size = size; type = VECTOR; createVector3DTexture(dataTexture, size, data); createVector3DTexture(resultTexture, size, (vec3*)nullptr); } void DataTexturePair::bindData(GLenum textureSlot) { glActiveTexture(textureSlot); glBindTexture(GL_TEXTURE_3D, dataTexture); } void DataTexturePair::bindToFramebuffer(int depth) { // attach result texture to framebuffer glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, resultTexture, 0, depth); } void DataTexturePair::operationFinished() { GLuint tmp = dataTexture; dataTexture = resultTexture; resultTexture = tmp; } GLuint DataTexturePair::getDataTexture() { return dataTexture; } GLuint DataTexturePair::getResultTexture() { return resultTexture; } ivec3 DataTexturePair::getSize() { return size; } float DataTexturePair::toVoxelScaleFactor() { return scaleFactor; } DataTexturePair* createScalarDataPair(float* data, ivec3 size, float scaleFactor) { DataTexturePair* texturePair = new DataTexturePair(); texturePair->initScalarData(scaleFactor, size, data); return texturePair; } DataTexturePair* createVectorDataPair(vec3* data, ivec3 size, float scaleFactor) { DataTexturePair* texturePair = new DataTexturePair(); texturePair->initVectorData(scaleFactor, size, data); return texturePair; }
25.84375
93
0.733575
Schitrus
a2228f04c89d1d6c359f7ecb71eff33d321773af
18,931
cpp
C++
libS3ORAM/ServerKaryS3ORAMO.cpp
thanghoang/libS3ORAM
7f180637902dadaf053642761dee0d891fc4d20e
[ "MIT" ]
5
2018-12-31T14:09:34.000Z
2020-02-22T17:13:10.000Z
libS3ORAM/ServerKaryS3ORAMO.cpp
thanghoang/libS3ORAM
7f180637902dadaf053642761dee0d891fc4d20e
[ "MIT" ]
null
null
null
libS3ORAM/ServerKaryS3ORAMO.cpp
thanghoang/libS3ORAM
7f180637902dadaf053642761dee0d891fc4d20e
[ "MIT" ]
null
null
null
/* * ServerKaryS3ORAMO.cpp * * Created on: Apr 7, 2017 * Author: ceyhunozkaptan, thanghoang */ #include "ServerKaryS3ORAMO.hpp" #include "Utils.hpp" #include "S3ORAM.hpp" #include "struct_socket.h" #include "struct_thread_computation.h" #include "struct_thread_loadData.h" ServerKaryS3ORAMO::ServerKaryS3ORAMO(TYPE_INDEX serverNo, int selectedThreads) : ServerBinaryS3ORAMO(serverNo, selectedThreads) { //specific for(TYPE_INDEX y = 0 ; y < H; y++) { for(TYPE_INDEX i = 0 ; i < BUCKET_SIZE; i++) { delete[] this->evictMatrix[y][i]; } delete[] this->evictMatrix[y]; } delete[] this->evictMatrix[H]; this->evictMatrix[H] = new zz_p*[BUCKET_SIZE]; for(TYPE_INDEX i = 0 ; i < BUCKET_SIZE; i++) { this->evictMatrix[H][i] = new zz_p[2*BUCKET_SIZE]; } //H+2, instead of H +1 due to auxiliary bucket at leaf nodes delete[] this->select_buffer_in; for (TYPE_INDEX k = 0 ; k < DATA_CHUNKS; k++) { delete[] this->dot_product_vector[k]; } delete[] this->evict_buffer_in; for(TYPE_INDEX y = 0 ; y < H; y++) { this->evictMatrix[y] = new zz_p*[BUCKET_SIZE]; for(TYPE_INDEX i = 0 ; i < BUCKET_SIZE; i++) { this->evictMatrix[y][i] = new zz_p[BUCKET_SIZE]; } } this->evictMatrix[H] = new zz_p*[BUCKET_SIZE]; for(TYPE_INDEX i = 0 ; i < BUCKET_SIZE; i++) { this->evictMatrix[H][i] = new zz_p[2*BUCKET_SIZE]; } //H+2, instead of H +1 due to auxiliary bucket at leaf nodes this->select_buffer_in = new unsigned char[sizeof(TYPE_INDEX)+(H+2)*BUCKET_SIZE*sizeof(TYPE_DATA)]; for (TYPE_INDEX k = 0 ; k < DATA_CHUNKS; k++) { this->dot_product_vector[k] = new zz_p[BUCKET_SIZE*(H+2)]; } this->evict_buffer_in = new unsigned char[(H+2)*evictMatSize*sizeof(TYPE_DATA) + sizeof(TYPE_INDEX)]; this->cross_product_vector_aux = new zz_p*[DATA_CHUNKS]; for (TYPE_INDEX k = 0 ; k < DATA_CHUNKS; k++) { this->cross_product_vector_aux[k] = new zz_p[2*BUCKET_SIZE]; } } ServerKaryS3ORAMO::ServerKaryS3ORAMO() { } ServerKaryS3ORAMO::~ServerKaryS3ORAMO() { } /** * Function Name: retrieve * * Description: Starts retrieve operation for a block by receiving logical access vector and path ID from the client. * According to path ID, server performs dot-product operation between its block shares on the path and logical access vector. * The result of the dot-product is send back to the client. * * @param socket: (input) ZeroMQ socket instance for communication with the client * @return 0 if successful */ int ServerKaryS3ORAMO::retrieve(zmq::socket_t& socket) { Utils::write_list_to_file(to_string(HEIGHT) + "_" + to_string(BLOCK_SIZE) + "_server" + to_string(serverNo)+ "_" + timestamp + ".txt",logDir, server_logs, 13); memset(server_logs, 0, sizeof(unsigned long int)*13); int ret = 1; auto start = time_now; socket.recv(select_buffer_in,sizeof(TYPE_INDEX)+(H+2)*BUCKET_SIZE*sizeof(TYPE_DATA),0); auto end = time_now; cout<< " [SendBlock] PathID and Logical Vector RECEIVED in " << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() << " ns" <<endl; server_logs[0] = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); TYPE_INDEX pathID; memcpy(&pathID, select_buffer_in, sizeof(pathID)); zz_p sharedVector[(H+2)*BUCKET_SIZE]; memcpy(sharedVector, &select_buffer_in[sizeof(pathID)], (H+2)*BUCKET_SIZE*sizeof(TYPE_DATA)); cout<< " [SendBlock] PathID is " << pathID <<endl; S3ORAM ORAM; TYPE_INDEX fullPathIdx[H+2]; ORAM.getFullPathIdx(fullPathIdx, pathID); //auxiliary bucket at leaf level fullPathIdx[H+1] = fullPathIdx[H] + N_leaf; //use thread to load data from files start = time_now; int step = ceil((double)DATA_CHUNKS/(double)numThreads); int endIdx; THREAD_LOADDATA loadData_args[numThreads]; for(int i = 0, startIdx = 0; i < numThreads , startIdx < DATA_CHUNKS; i ++, startIdx+=step) { if(startIdx+step > DATA_CHUNKS) endIdx = DATA_CHUNKS; else endIdx = startIdx+step; loadData_args[i] = THREAD_LOADDATA(this->serverNo, startIdx, endIdx, this->dot_product_vector, fullPathIdx,H+2); pthread_create(&thread_compute[i], NULL, &ServerS3ORAM::thread_loadRetrievalData_func, (void*)&loadData_args[i]); /*cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(i, &cpuset); pthread_setaffinity_np(thread_compute[i], sizeof(cpu_set_t), &cpuset);*/ } for(int i = 0, startIdx = 0 ; i < numThreads , startIdx < DATA_CHUNKS; i ++, startIdx+=step) { pthread_join(thread_compute[i],NULL); } end = time_now; long load_time = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); cout<< " [SendBlock] Path Nodes READ from Disk in " << load_time << " ns"<<endl; server_logs[1] = load_time; start = time_now; //Multithread for dot product computation THREAD_COMPUTATION dotProduct_args[numThreads]; endIdx = 0; step = ceil((double)DATA_CHUNKS/(double)numThreads); for(int i = 0, startIdx = 0 ; i < numThreads , startIdx < DATA_CHUNKS; i ++, startIdx+=step) { if(startIdx+step > DATA_CHUNKS) endIdx = DATA_CHUNKS; else endIdx = startIdx+step; dotProduct_args[i] = THREAD_COMPUTATION( startIdx, endIdx, this->dot_product_vector, sharedVector, (H+2)*BUCKET_SIZE, sumBlock); pthread_create(&thread_compute[i], NULL, &ServerS3ORAM::thread_dotProduct_func, (void*)&dotProduct_args[i]); /*cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(i, &cpuset); pthread_setaffinity_np(thread_compute[i], sizeof(cpu_set_t), &cpuset);*/ } for(int i = 0, startIdx = 0 ; i < numThreads , startIdx < DATA_CHUNKS; i ++, startIdx+=step) { pthread_join(thread_compute[i],NULL); } end = time_now; cout<< " [SendBlock] Block Share CALCULATED in " << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() <<endl; server_logs[2] = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); memcpy(block_buffer_out,sumBlock,sizeof(TYPE_DATA)*DATA_CHUNKS); start = time_now; cout<< " [SendBlock] Sending Block Share with ID-" << sumBlock[0] <<endl; socket.send(block_buffer_out,sizeof(TYPE_DATA)*DATA_CHUNKS); end = time_now; cout<< " [SendBlock] Block Share SENT in " << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() <<endl; server_logs[3] = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); ret = 0; return ret ; } /** * Function Name: evict * * Description: Starts eviction operation with the command of the client by receiving eviction matrix * and eviction path no from the client. According to eviction path no, the server performs * matrix multiplication with its buckets and eviction matrix to evict blocks. After eviction operation, * the degree of the sharing polynomial doubles. Thus all the servers distributes their shares and perform * degree reduction routine simultaneously. * * @param socket: (input) ZeroMQ socket instance for communication with the client * @return 0 if successful */ int ServerKaryS3ORAMO::evict(zmq::socket_t& socket) { S3ORAM ORAM; TYPE_INDEX n_evict; int ret; cout<< " [evict] Receiving Evict Matrix..." <<endl;; auto start = time_now; socket.recv(evict_buffer_in, (H+2)*evictMatSize*sizeof(TYPE_DATA) + sizeof(TYPE_INDEX), 0); auto end = time_now; cout<< " [evict] RECEIVED! in " << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() <<endl; server_logs[6] = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); TYPE_INDEX evictPath; for (TYPE_INDEX y = 0 ; y < H ; y++) { for (TYPE_INDEX i = 0 ; i < BUCKET_SIZE ; i++) { memcpy(this->evictMatrix[y][i], &evict_buffer_in[y*evictMatSize*sizeof(TYPE_DATA) + i*BUCKET_SIZE*sizeof(TYPE_DATA)], BUCKET_SIZE*sizeof(TYPE_DATA)); } } for (TYPE_INDEX i = 0 ; i < BUCKET_SIZE ; i++) { memcpy(this->evictMatrix[H][i], &evict_buffer_in[H*evictMatSize*sizeof(TYPE_DATA) + i*2*BUCKET_SIZE*sizeof(TYPE_DATA)], 2*BUCKET_SIZE*sizeof(TYPE_DATA)); } memcpy(&n_evict, &evict_buffer_in[(H+2)*evictMatSize*sizeof(TYPE_DATA)], sizeof(TYPE_INDEX)); string strEvict = ORAM.getEvictString(n_evict); TYPE_INDEX fullEvictPathIdx[H+1]; ORAM.getFullEvictPathIdx(fullEvictPathIdx,strEvict); FILE* file_out[K_ARY]; string path; for(int h = 0; h < H+1 ; h++) { cout<<endl; cout << " ==============================================================" << endl; cout<< " [evict] Starting Eviction-" << h+1 <<endl; TYPE_INDEX currBucketIdx = fullEvictPathIdx[h]; // Multithread for loading data from disk start = time_now; int step = ceil((double)DATA_CHUNKS/(double)numThreads); int endIdx; THREAD_LOADDATA loadData_args[numThreads]; for(int i = 0, startIdx = 0; i < numThreads , startIdx < DATA_CHUNKS; i ++, startIdx+=step) { if(startIdx+step > DATA_CHUNKS) endIdx = DATA_CHUNKS; else endIdx = startIdx+step; if(h<H) { loadData_args[i] = THREAD_LOADDATA(this->serverNo, startIdx, endIdx, this->cross_product_vector, currBucketIdx); } else { loadData_args[i] = THREAD_LOADDATA(this->serverNo, startIdx, endIdx, this->cross_product_vector_aux, currBucketIdx); } pthread_create(&thread_compute[i], NULL, &ServerS3ORAM::thread_loadBucket_func, (void*)&loadData_args[i]); /*cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(i, &cpuset); pthread_setaffinity_np(thread_compute[i], sizeof(cpu_set_t), &cpuset);*/ } for(int i = 0, startIdx = 0 ; i < numThreads , startIdx < DATA_CHUNKS; i ++, startIdx+=step) { pthread_join(thread_compute[i],NULL); } end = time_now; long load_time = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); cout<< " [evict] Evict Nodes READ from Disk in " << load_time <<endl; server_logs[7] += load_time; //perform matrix product cout<< " [evict] Multiplying Evict Matrix..." << endl; start = time_now; this->multEvictTriplet(h); // SERVER SIDE COMPUTATION end = time_now; cout<< " [evict] Multiplied in " << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() <<endl; server_logs[8] += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); //== THREADS FOR LISTENING ======================================================================================= struct_socket recvSocket_args[NUM_SERVERS-1]; cout<< " [evict] Creating Threads for Receiving Ports..." << endl; for(TYPE_INDEX k = 0; k < NUM_SERVERS-1; k++) { recvSocket_args[k] = struct_socket(k, NULL, 0, shares_buffer_in[k], BUCKET_SIZE*sizeof(TYPE_DATA)*DATA_CHUNKS, NULL,false); pthread_create(&thread_recv[k], NULL, &ServerS3ORAM::thread_socket_func, (void*)&recvSocket_args[k]); } cout << " [evict] CREATED!" << endl; //=============================================================================================================== // Distribution & Degree Reduction TYPE_DATA* shares = new TYPE_DATA[NUM_SERVERS]; cout<< " [evict] Creating Shares for Reduction..." << endl; //boost::progress_display show_progress2((2*H+1)*BUCKET_SIZE); int m = 0; start = time_now; TYPE_INDEX curBuffIdx; for(int u = 0 ; u <DATA_CHUNKS; u++) { for(TYPE_INDEX j = 0; j < BUCKET_SIZE; j++) { ORAM.createShares(this->BUCKET_DATA[u][ j ], shares); // EACH SERVER CALCULATES AND DISTRIBUTES SHARES curBuffIdx = (u*BUCKET_SIZE) + j; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for(TYPE_INDEX k = 0; k < NUM_SERVERS; k++) { if (k == this->serverNo) { ownShares[this->serverNo][u][j] = shares[k]; } else { memcpy(&shares_buffer_out[m][curBuffIdx*sizeof(TYPE_DATA)], &shares[k], sizeof(TYPE_DATA)); m++; } } m = 0; } } end = time_now; cout<< " [evict] Shares CREATED in " << std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count() <<endl; server_logs[9] += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); delete shares; //== THREADS FOR SENDING ============================================================================================ struct_socket sendSocket_args[NUM_SERVERS-1]; cout<< " [evict] Creating Threads for Sending Shares..."<< endl;; for (int i = 0; i < NUM_SERVERS-1; i++) { sendSocket_args[i] = struct_socket(i, shares_buffer_out[i], BUCKET_SIZE*sizeof(TYPE_DATA)*DATA_CHUNKS, NULL, 0, NULL, true); pthread_create(&thread_send[i], NULL, &ServerS3ORAM::thread_socket_func, (void*)&sendSocket_args[i]); } cout<< " [evict] CREATED!" <<endl; //================================================================================================================= cout<< " [evict] Waiting for Threads..." <<endl; for (int i = 0; i < NUM_SERVERS-1; i++) { pthread_join(thread_send[i], NULL); pthread_join(thread_recv[i], NULL); } cout<< " [evict] DONE!" <<endl; server_logs[10] += thread_max; thread_max = 0; cout << " [evict] Writing Received Shares" << endl; for(int u = 0 ; u < DATA_CHUNKS; u ++) { m = 0; for(TYPE_INDEX k = 0; k < NUM_SERVERS; k++) { if (k == this->serverNo) { } else { memcpy(ownShares[k][u], &shares_buffer_in[m][u*BUCKET_SIZE*sizeof(TYPE_DATA)], BUCKET_SIZE*sizeof(TYPE_DATA)); m++; } } } cout << " [evict] WRITTEN!" << endl; memset(bucket_buffer,0,BUCKET_SIZE*sizeof(TYPE_DATA)*DATA_CHUNKS); cout << " [evict] Calculating New Shares (Degree Reduction)" << endl; TYPE_DATA sum; start = time_now; for(int u = 0 ; u <DATA_CHUNKS; u++) { for(TYPE_INDEX j = 0; j < BUCKET_SIZE; j++) { sum = 0; for (TYPE_INDEX l = 0; l < NUM_SERVERS; l++) { sum = (sum + Utils::mulmod(vandermonde[l], ownShares[l][u][j])) % P; } memcpy(&bucket_buffer[(u*BUCKET_SIZE+ j)*sizeof(TYPE_DATA)], &sum, sizeof(TYPE_DATA)); } } end = time_now; server_logs[11] += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); //write to the deeper Bucket start = time_now; if(h < H) { int slideIdx = (strEvict[h]-'0'); for(int i = 0 ; i < K_ARY; i++) { TYPE_INDEX ChildBucketID = currBucketIdx*K_ARY + (i+1); path = rootPath + to_string(serverNo) + "/" + to_string(ChildBucketID); if((file_out[i] = fopen(path.c_str(),"r+b")) == NULL) { cout<< " [evict] File Cannot be Opened!!" <<endl; exit(0); } fseek(file_out[i], slideIdx*(BUCKET_SIZE*sizeof(TYPE_DATA)/K_ARY),SEEK_SET); } unsigned long long currBufferIdx = 0; for(int c = 0 ; c < DATA_CHUNKS; c++) { for(int i = 0 ; i < K_ARY; i++) { fwrite(&bucket_buffer[currBufferIdx],1,sizeof(TYPE_DATA)*BUCKET_SIZE/K_ARY,file_out[i]); fseek(file_out[i], (K_ARY-1)*(BUCKET_SIZE*sizeof(TYPE_DATA)/K_ARY),SEEK_CUR); currBufferIdx+=sizeof(TYPE_DATA)*BUCKET_SIZE/K_ARY; } } for(int i = 0 ; i < K_ARY; i++) fclose(file_out[i]); } else //h == H { path = rootPath + to_string(serverNo) + "/" + to_string(currBucketIdx+N_leaf); if((file_out[0] = fopen(path.c_str(),"wb+")) == NULL) { cout<< " [evict] File Cannot be Opened!!" <<endl; exit(0); } fwrite(bucket_buffer,1,sizeof(TYPE_DATA)*BUCKET_SIZE*DATA_CHUNKS,file_out[0]); fclose(file_out[0]); } /* end = time_now; server_logs[12] += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); */ cout<< " [evict] Reduction DONE in " << server_logs[11] <<endl; cout<< " [evict] Written to Disk in " << server_logs[12] <<endl; cout<< " [evict] TripletEviction-" << h+1 << " COMPLETED!"<<endl; } socket.send((unsigned char*)CMD_SUCCESS,sizeof(CMD_SUCCESS)); cout<< " [evict] ACK is SENT!" <<endl; return 0; } /** * Function Name: multEvictTriplet * * Description: Performs matrix multiplication between received eviction matrix and affected buckets * for eviction operation * * @param evictMatrix: (input) Received eviction matrix from the clietn * @return 0 if successful */ int ServerKaryS3ORAMO::multEvictTriplet(int level) { //thread implementation THREAD_COMPUTATION crossProduct_args[numThreads]; int endIdx; int step = ceil((double)DATA_CHUNKS/(double)numThreads); for(int i = 0, startIdx = 0 ; i < numThreads; i ++, startIdx+=step) { if(startIdx+step > DATA_CHUNKS) endIdx = DATA_CHUNKS; else endIdx = startIdx+step; if(level == H) { crossProduct_args[i] = THREAD_COMPUTATION(startIdx, endIdx, this->cross_product_vector_aux, BUCKET_SIZE*2, BUCKET_SIZE, evictMatrix[H], this->BUCKET_DATA ); pthread_create(&thread_compute[i], NULL, &ServerS3ORAM::thread_crossProduct_func, (void*)&crossProduct_args[i]); } else { crossProduct_args[i] = THREAD_COMPUTATION(startIdx, endIdx, this->cross_product_vector, BUCKET_SIZE, BUCKET_SIZE, evictMatrix[level], this->BUCKET_DATA ); pthread_create(&thread_compute[i], NULL, &ServerS3ORAM::thread_crossProduct_func, (void*)&crossProduct_args[i]); } /*cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(i, &cpuset); pthread_setaffinity_np(thread_compute[i], sizeof(cpu_set_t), &cpuset);*/ } for(int i = 0 ; i <numThreads ; i++) { pthread_join(thread_compute[i],NULL); } return 0; }
35.651601
169
0.597116
thanghoang
a22290fddb9ea71fa1b16c28e9e5da5f5677d9e2
369
hpp
C++
src/sn_String/repl.hpp
Airtnp/SuperNaiveCppLib
0745aa79dc5060cd0f7025658164374b991c698e
[ "MIT" ]
4
2017-04-01T08:09:09.000Z
2017-05-20T11:35:58.000Z
src/sn_String/repl.hpp
Airtnp/ACppLib
0745aa79dc5060cd0f7025658164374b991c698e
[ "MIT" ]
null
null
null
src/sn_String/repl.hpp
Airtnp/ACppLib
0745aa79dc5060cd0f7025658164374b991c698e
[ "MIT" ]
null
null
null
#ifndef SN_STRING_REPL_H #define SN_STRING_REPL_H #include "../sn_CommonHeader.h" namespace sn_String { namespace repl { using std::to_string; std::string to_string(std::string input) { return input; } std::string to_string(char* input) { return static_cast<std::string>(input); } } } #endif
17.571429
51
0.598916
Airtnp
a224e3e3f9e25e0a2cd4bf69147bc092a6f03f35
318
hpp
C++
logos/wallet_server/client/common.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
3
2020-01-17T18:05:19.000Z
2021-12-29T04:21:59.000Z
logos/wallet_server/client/common.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
null
null
null
logos/wallet_server/client/common.hpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
2
2020-12-22T05:51:53.000Z
2021-06-08T00:27:46.000Z
#pragma once #include <unordered_map> class CallbackHandler; namespace wallet_server { namespace client { namespace callback { using Handlers = std::unordered_map<uint64_t, CallbackHandler>; using Handle = uint64_t; } // namespace callback } // namespace client } // namespace wallet_server
18.705882
67
0.720126
LogosNetwork
a225ada3b7f81a0ca2a3014f00b7b50108fcb5a8
1,540
cpp
C++
linked-list/segregate-0-1-2.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/segregate-0-1-2.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/segregate-0-1-2.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; struct Node { int data; Node *next; } *head = nullptr, *last = nullptr; Node *segregate(Node *head) { Node *node = head; Node *head0 = nullptr, *tail0 = nullptr, *head1 = nullptr; Node *tail1 = nullptr, *head2 = nullptr, *tail2 = nullptr; while (node) { if (node->data == 0) { if (!head0) { head0 = node; tail0 = node; } else { tail0->next = node; tail0 = node; } } else if (node->data == 1) { if (!head1) { head1 = node; tail1 = node; } else { tail1->next = node; tail1 = node; } } else { if (!head2) { head2 = node; tail2 = node; } else { tail2->next = node; tail2 = node; } } node = node->next; } if (tail0) tail0->next = head1 ? head1 : head2; if (tail1) tail1->next = head2; if (tail2) tail2->next = nullptr; if (head0) head = head0; else if (head1) head = head1; else head = head2; return head; }
20
63
0.352597
Strider-7
a2293b8a02491edb73d52aa3ebec1bc41d29c8ed
35,830
cpp
C++
src/autowiring/test/AutoFilterTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/test/AutoFilterTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/test/AutoFilterTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "TestFixtures/Decoration.hpp" #include <autowiring/AutoPacket.h> #include <autowiring/AutoPacketFactory.h> #include <autowiring/Deferred.h> #include <autowiring/demangle.h> #include <autowiring/ObjectPool.h> #include <autowiring/SatCounter.h> #include THREAD_HEADER class AutoFilterTest: public testing::Test { public: AutoFilterTest(void) { // All decorator tests must run from an initiated context AutoCurrentContext()->Initiate(); } }; TEST_F(AutoFilterTest, GetOutstandingTest) { AutoRequired<AutoPacketFactory> factory; { auto packet = factory->NewPacket(); ASSERT_EQ(1UL, factory->GetOutstandingPacketCount()) << "Factory outstanding count mismatch"; } ASSERT_EQ(0UL, factory->GetOutstandingPacketCount()) << "Factory outstanding did not go to zero after releasing the only outstanding packet"; } TEST_F(AutoFilterTest, VerifySimpleFilter) { AutoRequired<AutoPacketFactory> factory; AutoRequired<FilterA> filterA; // Verify that the subscriber has been properly detected: bool bFound = false; std::vector<AutoFilterDescriptor> descs; factory->AppendAutoFiltersTo(descs); for(const auto& cur : descs) if(cur.GetAutoFilter() == filterA) { bFound = true; break; } ASSERT_TRUE(bFound) << "Failed to find an added subscriber"; // Obtain a packet from the factory: auto packet = factory->NewPacket(); // Decorate with one instance: packet->Decorate(Decoration<0>()); // Verify that no hit takes place with inadequate decoration: ASSERT_FALSE(filterA->m_called) << "Filter called prematurely with insufficient decoration"; // Now decorate with the other requirement of the filter: packet->Decorate(Decoration<1>()); // A hit should have taken place at this point: ASSERT_LT(0, filterA->m_called) << "Filter was not called even though it was fully satisfied"; } template<int N> class ChildDecoration : Decoration<N> {}; TEST_F(AutoFilterTest, VerifyTypeUsage) { AutoRequired<FilterA> filterA; AutoRequired<AutoPacketFactory> factory; // EXPECT: No attempt is made to cast decorations to parent types. auto packet = factory->NewPacket(); packet->Decorate(Decoration<0>()); // Fulfills first requirement ASSERT_EQ(0, filterA->m_called) << "AutoFilter called with incomplete arguments"; packet->Decorate(ChildDecoration<1>()); // Does not fulfill second requirement ASSERT_EQ(0, filterA->m_called) << "AutoFilter using derived type"; ASSERT_NO_THROW(packet->Decorate(Decoration<1>(2))) << "Decoration with parent type conflicts with derived type"; ASSERT_EQ(1, filterA->m_called) << "AutoFilter was not called when all arguments were available"; ASSERT_EQ(2, filterA->m_one.i) << "AutoFilter was called using derived type instead of parent"; } int DoTheThingAndStuff(void) { return 999; } TEST_F(AutoFilterTest, VerifyAutoOut) { AutoRequired<AutoPacketFactory> factory; *factory += [](auto_out<Decoration<0>> out) { *out = Decoration<0>(1); }; std::shared_ptr<AutoPacket> packet = factory->NewPacket(); const Decoration<0>* result0 = nullptr; ASSERT_TRUE(packet->Get(result0)) << "Output missing"; ASSERT_EQ(result0->i, 1) << "Output incorrect"; } TEST_F(AutoFilterTest, VerifyAutoOutPooled) { AutoRequired<AutoPacketFactory> factory; ObjectPool<Decoration<0>> pool; *factory += [&](auto_out<Decoration<0>> out) { auto p = pool(); p->i = 1; *out = p; }; std::shared_ptr<AutoPacket> packet = factory->NewPacket(); const Decoration<0>* result0 = nullptr; ASSERT_TRUE(packet->Get(result0)) << "Output missing"; ASSERT_EQ(result0->i, 1) << "Output incorrect"; } TEST_F(AutoFilterTest, VerifyNoMultiDecorate) { AutoRequired<FilterA> filterA; AutoRequired<AutoPacketFactory> factory; // Obtain a packet and attempt redundant introduction: auto packet = factory->NewPacket(); packet->Decorate(Decoration<0>()); ASSERT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Redundant decoration did not throw an exception as expected"; // Verify that a call has not yet been made ASSERT_FALSE(filterA->m_called) << "A call made on an idempotent packet decoration"; // Now finish saturating the filter and ensure we get a call: packet->Decorate(Decoration<1>()); ASSERT_LT(0, filterA->m_called) << "Filter was not called after being fully satisfied"; //NOTE: A typedef will throw an exception typedef Decoration<0> isDeco0type; ASSERT_ANY_THROW(packet->Decorate(isDeco0type())) << "Typedef failed to throw exception"; //NOTE: A shared_ptr to an existing type will throw an exception auto sharedDeco0 = std::make_shared<Decoration<0>>(); ASSERT_ANY_THROW(packet->Decorate(sharedDeco0)) << "Reduction of shared_ptr to base type failed"; //NOTE: Inheritance will not throw an exception class ofDeco0alias: public Decoration<0> {}; try { packet->Decorate(ofDeco0alias()); } catch (...) { FAIL() << "Class with inheritance from existing decoration reinterpreted as child type"; } // Verify that DecorateImmedaite also yields an exception Decoration<0> localDeco0; ASSERT_ANY_THROW(packet->DecorateImmediate(localDeco0)) << "Redundant immediate decoration did not throw an exception as expected"; ASSERT_ANY_THROW(packet->DecorateImmediate(Decoration<2>(), Decoration<2>())) << "Repeated type in immediate decoration was not identified as an error"; } TEST_F(AutoFilterTest, VerifyInterThreadDecoration) { AutoRequired<FilterB> filterB; AutoRequired<AutoPacketFactory> factory; AutoCurrentContext ctxt; // Obtain a packet for processing and decorate it: auto packet = factory->NewPacket(); packet->Decorate(Decoration<0>()); packet->Decorate(Decoration<1>()); // Verify that the recipient has NOT yet received the message: ASSERT_FALSE(filterB->m_called) << "A call was made to a thread which should not have been able to process it"; // Wake up the barrier and post a quit message: filterB->Continue(); *filterB += [&filterB] { filterB->Stop(); }; filterB->Wait(); // Verify that the filter method has been called ASSERT_LT(0, filterB->m_called) << "A deferred filter method was not called as expected"; } TEST_F(AutoFilterTest, VerifyTeardownArrangement) { AutoRequired<AutoPacketFactory> factory; std::weak_ptr<FilterA> filterAWeak; { std::shared_ptr<AutoPacket> packet; { // Create the filter and subscribe it auto filterA = std::make_shared<FilterA>(); filterAWeak = filterA; factory->AddSubscriber(filterA); // Create the packet--this should lock in references to all subscribers: packet = factory->NewPacket(); } // Verify that the subscription has not expired: ASSERT_FALSE(filterAWeak.expired()) << "A subscriber while it was still registered"; { std::shared_ptr<FilterA> filterA = filterAWeak.lock(); // Unsubscribe the filter: factory->RemoveSubscriber(filterA); } // Verify that unsubscription STILL does not result in expiration: ASSERT_FALSE(filterAWeak.expired()) << "A subscriber expired before all packets on that subscriber were satisfied"; //Create a new packet after having removed the only filter on it. auto packet2 = factory->NewPacket(); ASSERT_FALSE(packet2->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed."; // Satisfy the packet: packet->Decorate(Decoration<0>()); packet->Decorate(Decoration<1>()); auto packet3 = factory->NewPacket(); ASSERT_FALSE(packet3->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed."; } // Filter should be expired now: ASSERT_TRUE(filterAWeak.expired()) << "Subscriber was still left outstanding even though all references should be gone"; } TEST_F(AutoFilterTest, VerifyAntiDecorate) { AutoRequired<FilterA> filterA; AutoRequired<AutoPacketFactory> factory; { // Obtain a new packet and mark an unsatisfiable decoration: auto packet = factory->NewPacket(); packet->MarkUnsatisfiable<Decoration<0>>(); ASSERT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Incorrectly allowed a decoration to be added to a packet when that decoration was unsatisfiable"; } { // Obtain a new packet and try to make a satisfied decoration unsatisfiable. auto packet = factory->NewPacket(); packet->Decorate(Decoration<0>()); ASSERT_NO_THROW(packet->MarkUnsatisfiable<Decoration<0>>()) << "Failed to expunge a decoration from a packet"; } } /// <summary> /// Replicate the static_assert in has_autofilter /// </summary> template<typename T> struct good_autofilter { // Evaluates to false when T does not include an AutoFilter method with at least one argument. static const bool value = has_unambiguous_autofilter<T>::value; // This class has at least one AutoFilter method struct detect_ambiguous_autofilter : T, test_valid_autofilter {}; // Ensures a compiler error when the identification of T::AutoFilter is ambiguous. // This cannot be in has_unambiguous_autofilter, since that would be recursive. static const bool test = value || has_unambiguous_autofilter<detect_ambiguous_autofilter>::value; }; TEST_F(AutoFilterTest, VerifyReflexiveReciept) { AutoRequired<FilterA> filterA; AutoRequired<FilterC> filterC; AutoRequired<FilterD> filterD; AutoRequired<FilterE> filterE; //DEBUG: Expect compiler warning ASSERT_FALSE(good_autofilter<BadFilterA>::test) << "Failed to identify AutoFilter(void)"; ASSERT_FALSE(good_autofilter<BadFilterB>::test) << "Failed to identify multiple definitions of AutoFilter"; AutoRequired<AutoPacketFactory> factory; // Obtain a packet first: auto packet = factory->NewPacket(); // The mere act of obtaining a packet should have triggered filterD to be fired: ASSERT_LT(0, filterD->m_called) << "Trivial filter with AutoPacket argument was not called as expected"; ASSERT_NO_THROW(packet->Get<Decoration<2>>()) << "Decoration on creation failed"; // The mere act of obtaining a packet should have triggered filterD to be fired: ASSERT_LT(0, filterE->m_called) << "Trivial filter with no arguments was not called as expected"; // The mere act of obtaining a packet should have triggered filterD to be fired: ASSERT_LT(0, filterD->m_called) << "Trivial filter was not called as expected"; // Decorate--should satisfy filterC packet->Decorate(Decoration<0>()); ASSERT_LT(0, filterC->m_called) << "FilterC should have been satisfied with one decoration"; // FilterC should have also satisfied filterA: ASSERT_LT(0, filterA->m_called) << "FilterA should have been satisfied by FilterC"; } TEST_F(AutoFilterTest, VerifyReferenceBasedInput) { std::shared_ptr<AutoPacket> packet; { AutoCreateContext sub; CurrentContextPusher pshr(sub); sub->Initiate(); AutoRequired<AutoPacketFactory> factory; AutoRequired<FilterGen<Decoration<0>, Decoration<1>&>> makesDec1; // Create a packet and put decoration 0 on it: packet = factory->NewPacket(); // No early call ASSERT_FALSE(makesDec1->m_called) << "Single-input autofilter was invoked prematurely"; // Now we decorate, after ensuring an early call did not happen packet->Decorate(Decoration<0>()); // Verify that our filter got called when its sole input was satisfied ASSERT_LT(0, makesDec1->m_called) << "Single-input autofilter was not called as expected"; // Now make sure that the packet has the expected decoration: ASSERT_TRUE(packet->Has<Decoration<1>>()); sub->SignalShutdown(false); } } TEST_F(AutoFilterTest, ZeroArgumentAutoFilter) { AutoRequired<AutoPacketFactory> factory; int called1 = 0; *factory += [&] { called1++; }; factory->NewPacket(); ASSERT_EQ(1, called1) << "Zero-argument AutoFilter method was not invoked as expected"; } TEST_F(AutoFilterTest, ByValueDecoration) { AutoRequired<AutoPacketFactory> factory; int called0 = 0; int value = 101; *factory += [&called0, value](Decoration<0>) { // Check to ensure that the value was transferred in correctly ASSERT_EQ(101, value) << "AutoFilter entry base offset incorrectly computed"; ++called0; }; auto packet = factory->NewPacket(); packet->Decorate(Decoration<0>()); ASSERT_EQ(1, called0) << "Root AutoFilter method was not invoked as expected"; } class SimpleIntegerFilter { public: void AutoFilter(int val) { hit = true; } bool hit = false; }; class DeferredIntegerFilter: public CoreThread { public: DeferredIntegerFilter(void) : CoreThread("DeferredIntegerFilter") {} Deferred AutoFilter(int val) { hit = true; return Deferred(this); } bool hit = false; }; TEST_F(AutoFilterTest, SingleImmediate) { // Add a few filter entities AutoRequired<SimpleIntegerFilter> sif; AutoRequired<DeferredIntegerFilter> dif; AutoRequired<AutoPacketFactory> factory; { auto packet = factory->NewPacket(); // Create an immediate-mode satisfaction int val = 101; packet->DecorateImmediate(val); // Verify we can't decorate this value a second time: ASSERT_ANY_THROW(packet->DecorateImmediate(val)) << "Expected an exception when a second attempt was made to attach a decoration"; } ASSERT_EQ(0, factory->GetOutstandingPacketCount()) << "Destroyed packet remains outstanding"; static const int pattern = 1365; //1365 ~ 10101010101 AutoRequired<FilterGen<Decoration<pattern>>> fgp; ASSERT_EQ(0, factory->GetOutstandingPacketCount()) << "Outstanding packet count is correct after incrementing m_poolVersion due to AutoFilter addition"; { auto packet = factory->NewPacket(); Decoration<pattern> dec; packet->DecorateImmediate(dec); ASSERT_EQ(1, fgp->m_called) << "Filter should called " << fgp->m_called << " times, expected 1"; ASSERT_EQ(pattern, autowiring::get<0>(fgp->m_args).i) << "Filter argument yielded " << autowiring::get<0>(fgp->m_args).i << "expected " << pattern; } ASSERT_EQ(0, factory->GetOutstandingPacketCount()) << "Destroyed packet remains outstanding"; // Terminate enclosing context AutoCurrentContext()->SignalShutdown(true); ASSERT_TRUE(sif->hit) << "Simple filter was not invoked by immediate-mode decoration"; ASSERT_FALSE(dif->hit) << "Deferred filter incorrectly invoked in an immediate mode decoration"; } class DoesNothingWithSharedPointer: public CoreThread { public: DoesNothingWithSharedPointer(void): CoreThread("DoesNothingWithSharedPointer") {} size_t callCount = 0; Deferred AutoFilter(std::shared_ptr<const int>) { callCount++; return Deferred(this); } }; TEST_F(AutoFilterTest, NoImplicitDecorationCaching) { AutoRequired<AutoPacketFactory> factory; auto ptr = std::make_shared<int>(1012); auto doesNothing = AutoRequired<DoesNothingWithSharedPointer>(); // Generate a bunch of packets, all with the same shared pointer decoration: for(size_t i = 0; i < 100; i++) { // Decorate the packet, forget about it: auto packet = factory->NewPacket(); packet->Decorate(ptr); } // Final lambda terminates the thread: *doesNothing += [doesNothing] { doesNothing->Stop(); }; // Block for the thread to stop ASSERT_TRUE(doesNothing->WaitFor(std::chrono::seconds(10))) << "Thread did not finish processing packets in a timely fashion"; // Ensure nothing got cached unexpectedly, and that the call count is precisely what we want ASSERT_EQ(100UL, doesNothing->callCount) << "The expected number of calls to AutoFilter were not made"; ASSERT_TRUE(ptr.unique()) << "Cached packets (or some other cause) incorrectly held a reference to a shared pointer that should have expired"; } TEST_F(AutoFilterTest, MultiImmediate) { AutoRequired<AutoPacketFactory> factory; AutoRequired<FilterGen<Decoration<0>, Decoration<1>>> fg; { auto packet = factory->NewPacket(); packet->DecorateImmediate( Decoration<0>(), Decoration<1>() ); // Verify the recipient got called ASSERT_EQ(1, fg->m_called) << "Filter not called during multisimultaneous immediate-mode decoration"; } ASSERT_EQ(1, fg->m_called) << "Filter called repeatedly"; } TEST_F(AutoFilterTest, ImmediateWithPrior) { AutoRequired<AutoPacketFactory> factory; // The filter which should get an immediate hit AutoRequired<FilterGen<Decoration<0>, Decoration<1>, Decoration<2>>> secondChanceImmed; { // Add a pre-decoration: auto packet = factory->NewPacket(); packet->Decorate(Decoration<0>()); // Now add immediate decorations to the remainder: packet->DecorateImmediate(Decoration<1>(), Decoration<2>()); ASSERT_EQ(1, secondChanceImmed->m_called) << "Filter should have been saturated by an immediate call, but was not called as expected"; } ASSERT_EQ(1, secondChanceImmed->m_called) << "Filter was called repeatedly"; } TEST_F(AutoFilterTest, MultiImmediateComplex) { AutoRequired<AutoPacketFactory> factory; // All of the filters that we're adding AutoRequired<FilterGen<Decoration<0>>> fg1; AutoRequired<FilterGen<Decoration<0>, Decoration<1>>> fg3; AutoRequired<FilterGen<Decoration<0>, Decoration<2>>> fg4; { // The single immediate-mode decoration call, which should satisfy all but fg4 auto packet = factory->NewPacket(); packet->DecorateImmediate( Decoration<0>(), Decoration<1>() ); // Validate expected behaviors: ASSERT_EQ(1, fg1->m_called) << "Trivial filter was not called as expected, even though Decoration<0> should have been available"; ASSERT_EQ(1, fg3->m_called) << "Saturated filter was not called as expected"; ASSERT_EQ(0, fg4->m_called) << "Undersaturated filter was called even though it should not have been"; } // Validate expected behaviors: ASSERT_EQ(1, fg1->m_called) << "Trivial filter was called repeatedly"; ASSERT_EQ(1, fg3->m_called) << "Saturated filter was not called as expected was called repeatedly"; ASSERT_EQ(0, fg4->m_called) << "Undersaturated filter was called"; } TEST_F(AutoFilterTest, PostHocSatisfactionAttempt) { AutoRequired<AutoPacketFactory> factory; // Filter that accepts two types, but one of the two will be DecorateImmediate'd too early AutoRequired<FilterGen<Decoration<0>, Decoration<1>>> fg1; AutoRequired<FilterGen<Decoration<2>, Decoration<1>>> fg2; auto packet1 = factory->NewPacket(); packet1->DecorateImmediate(Decoration<0>()); packet1->Decorate(Decoration<1>()); ASSERT_FALSE(fg1->m_called) << "An AutoFilter was called when all of its inputs should not have been simultaneously available"; packet1->DecorateImmediate(Decoration<2>()); ASSERT_LT(0, fg2->m_called) << "An AutoFilter was not called when all of its inputs were simultaneously available"; } TEST_F(AutoFilterTest, AutoOutTest) { AutoRequired<AutoPacketFactory> factory; AutoRequired<FilterOutA> foA; AutoRequired<FilterOutB> foB; { auto packet = factory->NewPacket(); ASSERT_TRUE(foA->m_called == 1) << "An AutoFilter applied to one new packet with argument AutoPacket& was called " << foA->m_called << " times"; ASSERT_TRUE(packet->Get<Decoration<0>>().i == 1) << "Decoration data was not initialized by AutoFilter call"; ASSERT_TRUE(packet->Get<Decoration<1>>().i == 1) << "Decoration data was not appended by AutoFilter call"; ASSERT_TRUE(foB->m_called == 1) << "An AutoFilter applied to one new packet without argument AutoPacket& reference was called " << foB->m_called << " times"; const Decoration<2>* pDec2; ASSERT_TRUE(packet->Get(pDec2)) << "Decoration<2> was not present on the packet"; ASSERT_TRUE(pDec2->i == 2) << "Decoration data was not appended by AutoFilter call"; } } class WaitsForInternalLock: public CoreThread { public: std::mutex m_continueLock; Deferred AutoFilter(const Decoration<0>& dec) { return Deferred(this); } void Run(void) override { (std::lock_guard<std::mutex>)m_continueLock; CoreThread::Run(); } }; TEST_F(AutoFilterTest, NoDeferredImmediateSatisfaction) { // Create a waiter, then obtain its lock before sending it off: AutoRequired<WaitsForInternalLock> wfil; std::lock_guard<std::mutex> lk(wfil->m_continueLock); // Now create a packet that we will DecorateImmediate with our decoration: AutoRequired<AutoPacketFactory> factory; auto packet = factory->NewPacket(); packet->DecorateImmediate(Decoration<0>()); // Verify that the thread did not receive anything: ASSERT_EQ(0UL, wfil->GetDispatchQueueLength()) << "Deferred AutoFilter incorrectly received an immediate-mode decoration"; } TEST_F(AutoFilterTest, WaitWhilePacketOutstanding) { AutoRequired<AutoPacketFactory> factory; auto packet = factory->NewPacket(); AutoCurrentContext ctxt; ctxt->SignalShutdown(); ASSERT_FALSE(ctxt->Wait(std::chrono::milliseconds(1))) << "Wait incorrectly returned while packets were outstanding"; packet.reset(); ASSERT_TRUE(ctxt->Wait(std::chrono::milliseconds(1))) << "Wait incorrectly timed out when nothing should have been running"; } class DecoratesAndAcceptsNothing: public CoreThread { public: Deferred AutoFilter(Decoration<0>& dec) { dec.i = 105; return Deferred(this); } }; TEST_F(AutoFilterTest, DeferredDecorateOnly) { AutoCurrentContext ctxt; AutoRequired<DecoratesAndAcceptsNothing> daan; AutoRequired<AutoPacketFactory> factory; auto packet = factory->NewPacket(); ctxt->SignalShutdown(); ASSERT_TRUE(daan->WaitFor(std::chrono::seconds(5))); const Decoration<0>* dec; ASSERT_TRUE(packet->Get(dec)) << "Deferred decorator didn't attach a decoration to an issued packet"; ASSERT_EQ(105, dec->i) << "Deferred decorate-only AutoFilter did not properly attach before context termination"; } class DQueueSharedPointer: public DispatchQueue { public: size_t callCount = 0; Deferred AutoFilter(std::shared_ptr<const int>) { callCount++; return Deferred(this); } }; TEST_F(AutoFilterTest, DQueueAutoFilterTest) { AutoRequired<AutoPacketFactory> factory; auto ptr = std::make_shared<int>(1012); AutoRequired<DQueueSharedPointer> dQueueSharedPtr; // Generate a bunch of packets, all with the same shared pointer decoration: for(size_t i = 0; i < 100; i++) { // Decorate the packet, forget about it: auto packet = factory->NewPacket(); packet->Decorate(ptr); } ASSERT_EQ(0UL, dQueueSharedPtr->callCount); dQueueSharedPtr->DispatchAllEvents(); // Ensure nothing got cached unexpectedly, and that the call count is precisely what we want ASSERT_EQ(100UL, dQueueSharedPtr->callCount) << "The expected number of calls to AutoFilter were not made"; } class MyInheritingAutoFilter: public FilterGen<std::vector<int>> {}; TEST_F(AutoFilterTest, AutoFilterInBaseClass) { AutoRequired<MyInheritingAutoFilter> d; AutoRequired<AutoPacketFactory> f; // Packet decoration shouldn't cause problems by itself auto packet = f->NewPacket(); packet->Decorate(std::vector<int>{0, 1, 2}); // Trivial validation that we got something back ASSERT_EQ(1UL, d->m_called) << "Filter defined in base class was not called the expected number of times"; } class MyInheritingAutoFilterNoAlias: public ContextMember, public FilterGen<std::vector<int>> {}; TEST_F(AutoFilterTest, AutoFilterInBaseClassNoAlias) { AutoRequired<MyInheritingAutoFilterNoAlias> d; AutoRequired<AutoPacketFactory> f; // Packet decoration shouldn't cause problems by itself auto packet = f->NewPacket(); packet->Decorate(std::vector<int>{0, 1, 2}); // Trivial validation that we got something back ASSERT_EQ(1UL, d->m_called) << "Filter defined in base class in an Object-inheriting type was not called the expected number of times"; } TEST_F(AutoFilterTest, PacketTeardownNotificationCheck) { AutoRequired<AutoPacketFactory> factory; auto called = std::make_shared<bool>(false); { auto packet = factory->NewPacket(); packet->AddTeardownListener([called] { *called = true; }); ASSERT_FALSE(*called) << "Teardown listener called before packet was destroyed"; } ASSERT_TRUE(*called) << "Teardown listener was not called after packet destruction"; ASSERT_TRUE(called.unique()) << "Teardown listener lambda function was leaked"; } struct ContextChecker: ContextMember { void AutoFilter(int i) { ++m_called; ASSERT_EQ(AutoCurrentContext(), GetContext()) << "AutoFilter not called with the current context set to packet's context"; } int m_called = 0; }; TEST_F(AutoFilterTest, CurrentContextCheck) { AutoRequired<AutoPacketFactory> factory; AutoRequired<ContextChecker> filter; { CurrentContextPusher pshr((AutoCreateContext())); auto packet = factory->NewPacket(); packet->Decorate(42); } ASSERT_EQ(1, filter->m_called) << "AutoFilter called incorrect number of times"; } TEST_F(AutoFilterTest, AutoOut0) { AutoRequired<AutoPacketFactory> factory; { auto packet = factory->NewPacket(); packet->Decorate(123.45); ASSERT_EQ(1, packet->GetDecorationTypeCount()) << "Did not get the expected number of decorations."; ASSERT_EQ(123.45, packet->Get<double>()); *packet += [](const double &x, auto_out<int> y) { *y = static_cast<int>(x); }; ASSERT_EQ(2, packet->GetDecorationTypeCount()) << "Did not get the expected number of decorations."; ASSERT_EQ(123, packet->Get<int>()); } } TEST_F(AutoFilterTest, AutoOut1) { AutoRequired<AutoPacketFactory> factory; { auto packet = factory->NewPacket(); // Same as AutoOut0 but add the filter first. *packet += [](const double &x, auto_out<int> y) { *y = static_cast<int>(x); }; packet->Decorate(123.45); ASSERT_EQ(2, packet->GetDecorationTypeCount()) << "Did not get the expected number of decorations."; ASSERT_EQ(123.45, packet->Get<double>()); ASSERT_EQ(123, packet->Get<int>()); } } #include <iostream> std::string decoration_status_string(DispositionState s) { switch (s) { case DispositionState::Unsatisfied: return "Unsatisfied"; case DispositionState::PartlySatisfied: return "PartlySatisfied"; case DispositionState::Complete: return "Complete"; } return ""; } void print_decorations(const std::string &label, const AutoPacket::t_decorationMap &d) { std::cout << label << " {\n"; for (auto it : d) { std::cout << " " << autowiring::demangle(it.first.id.block->ti) << " : " << decoration_status_string(it.second.m_state) << '\n'; } std::cout << "}\n"; } TEST_F(AutoFilterTest, AutoOut2) { // NOTE: this test uses implementation details of DecorationDisposition, which is not part of the public API, // and should be refactored once that part is cleaned up (in particular, AutoPacket::GetDecorations is // what is exposing that, and should be moved into autowiring::dbg, out of the public API for AutoPacket). AutoRequired<AutoPacketFactory> factory; { auto packet = factory->NewPacket(); auto d = packet->GetDecorations(); ASSERT_EQ(0, d.size()) << "Unexpected number of AutoFilter parameters."; packet->Decorate(123.45); d = packet->GetDecorations(); ASSERT_EQ(1, d.size()) << "Unexpected number of AutoFilter parameters."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<double>())].m_state) << "Incorrect `double` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<double>())].m_decorations.size()) << "Incorrect `double` decoration disposition."; bool filter_0_called = false; auto filter_0 = [&filter_0_called](const double &x, auto_out<int> y) { filter_0_called = true; }; bool filter_1_called = false; auto filter_1 = [&filter_1_called](int y) { filter_1_called = true; }; ASSERT_FALSE(filter_0_called) << "We expected filter_0 to not have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_1 to not have been called by now."; *packet += filter_0; ASSERT_TRUE(filter_0_called) << "We expected filter_0 to have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_0 to not have been called by now."; d = packet->GetDecorations(); ASSERT_EQ(2, d.size()) << "Unexpected number of AutoFilter parameters."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<double>())].m_state) << "Incorrect `double` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<double>())].m_decorations.size()) << "Incorrect `double` decoration disposition."; // Being Complete and having no decorations indicates that it has been MarkUnsatisfiable()'d. ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<int>())].m_state) << "Incorrect `int` decoration disposition."; ASSERT_EQ(0, d[DecorationKey(auto_id_t<int>())].m_decorations.size()) << "Incorrect `int` decoration disposition."; // Because the auto_out<int> was never assigned to, it went unsatisfiable, so this filter should never be called. *packet += filter_1; ASSERT_TRUE(filter_0_called) << "We expected filter_0 to have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_0 to not have been called by now."; } } TEST_F(AutoFilterTest, AutoOut3) { // NOTE: this test uses implementation details of DecorationDisposition, which is not part of the public API, // and should be refactored once that part is cleaned up (in particular, AutoPacket::GetDecorations is // what is exposing that, and should be moved into autowiring::dbg, out of the public API for AutoPacket). AutoRequired<AutoPacketFactory> factory; { auto packet = factory->NewPacket(); auto d = packet->GetDecorations(); ASSERT_EQ(0, d.size()) << "Unexpected number of AutoFilter parameters."; bool filter_1_called = false; auto filter_1 = [&filter_1_called](int y) { filter_1_called = true; }; *packet += filter_1; packet->Decorate(123.45); d = packet->GetDecorations(); ASSERT_EQ(2, d.size()) << "Unexpected number of AutoFilter parameters."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<double>())].m_state) << "Incorrect `double` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<double>())].m_decorations.size()) << "Incorrect `double` decoration disposition."; ASSERT_EQ(DispositionState::Unsatisfied, d[DecorationKey(auto_id_t<int>())].m_state) << "Incorrect `int` decoration disposition."; ASSERT_EQ(0, d[DecorationKey(auto_id_t<int>())].m_decorations.size()) << "Incorrect `int` decoration disposition."; bool filter_0_called = false; auto filter_0 = [&filter_0_called](const double &x, auto_out<int> y) { filter_0_called = true; }; ASSERT_FALSE(filter_0_called) << "We expected filter_0 to not have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_1 to not have been called by now."; *packet += filter_0; ASSERT_TRUE(filter_0_called) << "We expected filter_0 to have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_0 to not have been called by now."; d = packet->GetDecorations(); ASSERT_EQ(2, d.size()) << "Unexpected number of AutoFilter parameters."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<double>())].m_state) << "Incorrect `double` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<double>())].m_decorations.size()) << "Incorrect `double` decoration disposition."; // Being Complete and having no decorations indicates that it has been MarkUnsatisfiable()'d. ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<int>())].m_state) << "Incorrect `int` decoration disposition."; ASSERT_EQ(0, d[DecorationKey(auto_id_t<int>())].m_decorations.size()) << "Incorrect `int` decoration disposition."; // Because the auto_out<int> was never assigned to, it went unsatisfiable, so this filter should never be called. ASSERT_TRUE(filter_0_called) << "We expected filter_0 to have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_0 to not have been called by now."; } } TEST_F(AutoFilterTest, AutoOut4) { // NOTE: this test uses implementation details of DecorationDisposition, which is not part of the public API, // and should be refactored once that part is cleaned up (in particular, AutoPacket::GetDecorations is // what is exposing that, and should be moved into autowiring::dbg, out of the public API for AutoPacket). AutoRequired<AutoPacketFactory> factory; { auto packet = factory->NewPacket(); auto d = packet->GetDecorations(); ASSERT_EQ(0, d.size()) << "Unexpected number of AutoFilter parameters."; bool filter_1_called = false; auto filter_1 = [&filter_1_called](int y) { filter_1_called = true; }; *packet += filter_1; packet->Decorate(123.45); d = packet->GetDecorations(); ASSERT_EQ(2, d.size()) << "Unexpected number of AutoFilter parameters."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<double>())].m_state) << "Incorrect `double` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<double>())].m_decorations.size()) << "Incorrect `double` decoration disposition."; ASSERT_EQ(DispositionState::Unsatisfied, d[DecorationKey(auto_id_t<int>())].m_state) << "Incorrect `int` decoration disposition."; ASSERT_EQ(0, d[DecorationKey(auto_id_t<int>())].m_decorations.size()) << "Incorrect `int` decoration disposition."; bool filter_0_called = false; auto_out<int> ao; auto filter_0 = [&ao, &filter_0_called](const double &x, auto_out<int> y) { ao = std::move(y); filter_0_called = true; }; ASSERT_FALSE(filter_0_called) << "We expected filter_0 to not have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_1 to not have been called by now."; *packet += filter_0; ASSERT_TRUE(filter_0_called) << "We expected filter_0 to have been called by now."; ASSERT_FALSE(filter_1_called) << "We expected filter_0 to not have been called by now."; d = packet->GetDecorations(); ASSERT_EQ(2, d.size()) << "Unexpected number of AutoFilter parameters."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<double>())].m_state) << "Incorrect `double` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<double>())].m_decorations.size()) << "Incorrect `double` decoration disposition."; // Being Complete and having no decorations indicates that it has been MarkUnsatisfiable()'d. ASSERT_EQ(DispositionState::Unsatisfied, d[DecorationKey(auto_id_t<int>())].m_state) << "Incorrect `int` decoration disposition."; ASSERT_EQ(0, d[DecorationKey(auto_id_t<int>())].m_decorations.size()) << "Incorrect `int` decoration disposition."; // Assign to ao, thereby decorating the packet with int. *ao = 42; ao.reset(); ASSERT_TRUE(filter_0_called) << "We expected filter_0 to have been called by now."; ASSERT_TRUE(filter_1_called) << "We expected filter_0 to have been called by now."; d = packet->GetDecorations(); ASSERT_EQ(2, d.size()) << "Unexpected number of AutoFilter parameters."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<double>())].m_state) << "Incorrect `double` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<double>())].m_decorations.size()) << "Incorrect `double` decoration disposition."; ASSERT_EQ(DispositionState::Complete, d[DecorationKey(auto_id_t<int>())].m_state) << "Incorrect `int` decoration disposition."; ASSERT_EQ(1, d[DecorationKey(auto_id_t<int>())].m_decorations.size()) << "Incorrect `int` decoration disposition."; } }
38.279915
161
0.722774
CaseyCarter
a2339e6b518f5c9cf9a29c9434bcd9c43151743d
670
cpp
C++
3750/6647062_AC_0MS_168K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
3750/6647062_AC_0MS_168K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
3750/6647062_AC_0MS_168K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<cstdio> const int CHILD_NUM_MAX=64,NAME_LEN_MAX=15; int main(){ int childNum; scanf("%d",&childNum); char names[CHILD_NUM_MAX][NAME_LEN_MAX+1]; for(int childID=0;childID<childNum;childID++) scanf("%s",names+childID); int begin,outCount; scanf("%d,%d",&begin,&outCount); begin--; bool out[CHILD_NUM_MAX]={false}; int remainNum=childNum; while(remainNum){ for(int childID=begin,count=0;;childID=(childID+1)%childNum){ if(out[childID]) continue; count++; if(count==outCount){ printf("%s\n",names[childID]); out[childID]=true; remainNum--; begin=childID; break; } } } return 0; }
21.612903
64
0.634328
vandreas19
a2425b5bb8a1b03880727c0d4860d0d345dac0c2
9,842
cpp
C++
src/TankController.cpp
jgfoster/Open_Acidification_pH-stat_arduino
b4d880e0f02c659af4ef2963c1ec11a7885e301e
[ "MIT" ]
4
2019-11-07T17:51:20.000Z
2020-08-27T05:00:43.000Z
src/TankController.cpp
jgfoster/Open_Acidification_pH-stat_arduino
b4d880e0f02c659af4ef2963c1ec11a7885e301e
[ "MIT" ]
34
2020-04-23T16:48:12.000Z
2020-09-13T19:48:56.000Z
src/TankController.cpp
jgfoster/Open_Acidification_pH-stat_arduino
b4d880e0f02c659af4ef2963c1ec11a7885e301e
[ "MIT" ]
12
2019-11-07T17:51:14.000Z
2020-09-21T16:06:15.000Z
#include "TankController.h" #include <avr/wdt.h> #include <stdlib.h> #include "Devices/DateTime_TC.h" #include "Devices/EEPROM_TC.h" #include "Devices/EthernetServer_TC.h" #include "Devices/Ethernet_TC.h" #include "Devices/Keypad_TC.h" #include "Devices/LiquidCrystal_TC.h" #include "Devices/PHControl.h" #include "Devices/PHProbe.h" #include "Devices/PID_TC.h" #include "Devices/PushingBox.h" #include "Devices/SD_TC.h" #include "Devices/Serial_TC.h" #include "Devices/TempProbe_TC.h" #include "Devices/TemperatureControl.h" #include "TC_util.h" #include "UIState/MainMenu.h" #include "UIState/UIState.h" const char TANK_CONTROLLER_VERSION[] = "22.04.1"; // ------------ Class Methods ------------ /** * static variable to hold singleton */ TankController *TankController::_instance = nullptr; /** * static function to return singleton */ TankController *TankController::instance(const char *pushingBoxID) { if (!_instance) { _instance = new TankController; PushingBox::instance(pushingBoxID); } return _instance; } // ------------ Instance Methods ------------ /** * Constructor */ TankController::TankController() { serial(F("\r\n#################\r\nTankController::TankController() - version %s"), TANK_CONTROLLER_VERSION); assert(!_instance); // ensure we have instances SD_TC::instance(); EEPROM_TC::instance(); Keypad_TC::instance(); LiquidCrystal_TC::instance(TANK_CONTROLLER_VERSION); DateTime_TC::rtc(); Ethernet_TC::instance(); TempProbe_TC::instance(); TemperatureControl::instance(); PHProbe::instance(); PHControl::instance(); state = new MainMenu(this); pinMode(LED_BUILTIN, OUTPUT); } /** * Destructor */ TankController::~TankController() { if (state) { delete state; state = nullptr; } if (nextState) { delete nextState; nextState = nullptr; } } /** * Blink the on-board LED to let us know that loop() is being called * */ void TankController::blink() { if (millis() / 1000 % 2) { digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW } else { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) } } // https://github.com/maniacbug/MemoryFree/blob/master/MemoryFree.cpp int TankController::freeMemory() { #ifdef MOCK_PINS_COUNT return 1024; #else extern char *__brkval; int topOfStack; return (int)((size_t)&topOfStack) - ((size_t)__brkval); #endif } /** * Is the current UIState one that should disable controls? * We don't want to turn on the heat/chill if the temperature probe is out of the tank! */ bool TankController::isInCalibration() { return state->isInCalibration(); } /** * Private member function called by loop * Handles keypresses */ void TankController::handleUI() { COUT("TankController::handleUI() - " << state->name()); // Get server key, otherwise check for Keypad key char key = nextKey ? nextKey : Keypad_TC::instance()->getKey(); nextKey = 0; if (key == NO_KEY) { if (!lastKeypadTime) { // we have already reached an idle state, so don't do other checks } else if (isInCalibration()) { // we are in calibration, so don't return to main menu } else if (nextState) { // we already have a next state teed-up, do don't try to return to main menu } else if (millis() - lastKeypadTime > IDLE_TIMEOUT) { // time since last keypress exceeds the idle timeout, so return to main menu setNextState((UIState *)new MainMenu(this)); lastKeypadTime = 0; // so we don't do this until another keypress! } } else { serial(F("Keypad input: %c"), key); COUT("TankController::handleUI() - " << state->name() << "::handleKey(" << key << ")"); state->handleKey(key); lastKeypadTime = millis(); } updateState(); COUT("TankController::handleUI() - " << state->name() << "::loop()"); state->loop(); } /** * This is one of two public instance functions. * It is called repeatedly while the board is on. * (loop() appears to finish in 2-4 ms idling at main menu.) */ void TankController::loop() { wdt_reset(); blink(); // blink the on-board LED to show that we are running handleUI(); // look at keypad, update LCD updateControls(); // turn CO2 and temperature controls on or off writeDataToSD(); // record current state to data log writeDataToSerial(); // record current pH and temperature to serial PushingBox::instance()->loop(); // write data to Google Sheets Ethernet_TC::instance()->loop(); // renew DHCP lease EthernetServer_TC::instance()->loop(); // handle any HTTP requests } /** * This public instance function is called when there is data on the serial port(0). */ void TankController::serialEvent() { } /** * This public instance function is called when there is data on the serial port(1). * This the Atlas EZO pH circuit probe. */ void TankController::serialEvent1() { PHProbe::instance()->serialEvent1(); } /** * Set the next state */ void TankController::setNextState(UIState *newState, bool update) { COUT("TankController::setNextState() from " << (nextState ? nextState->name() : "nullptr") << " to " << newState->name()); assert(nextState == nullptr); nextState = newState; if (update) { this->updateState(); } } /** * This is one of two public instance functions. * Here we do any one-time startup initialization. */ void TankController::setup() { serial(F("TankController::setup()")); serial(F("Free memory = %i"), freeMemory()); wdt_enable(WDTO_8S); } /** * Public member function used to get the current state name. * This is primarily used by testing. */ const __FlashStringHelper *TankController::stateName() { return state->name(); } /** * Private member function called by loop to update solonoids */ void TankController::updateControls() { // update TemperatureControl TemperatureControl::instance()->updateControl(TempProbe_TC::instance()->getRunningAverage()); // update PHControl PHControl::instance()->updateControl(PHProbe::instance()->getPh()); } /** * Private member function called by UIState subclasses * Only updates if a new state is available to switch to */ void TankController::updateState() { if (nextState) { COUT("TankController::updateState() to " << nextState->name()); assert(state != nextState); delete state; state = nextState; nextState = nullptr; state->start(); } } /** * What is the current version? */ const char *TankController::version() { serial(F("TankController::version() = %s"), TANK_CONTROLLER_VERSION); return TANK_CONTROLLER_VERSION; } /** * once per second write the current data to the SD card */ void TankController::writeDataToSD() { static uint32_t nextWriteTime = 0; uint32_t msNow = millis(); COUT("nextWriteTime: " << nextWriteTime << "; now = " << msNow); if (nextWriteTime > msNow) { return; } char currentTemp[10]; char currentPh[10]; if (isInCalibration()) { snprintf_P(currentTemp, sizeof(currentTemp), (PGM_P)F("C")); snprintf_P(currentPh, sizeof(currentPh), (PGM_P)F("C")); } else { dtostrf((float)TempProbe_TC::instance()->getRunningAverage(), 4, 2, currentTemp); dtostrf((float)PHProbe::instance()->getPh(), 5, 3, currentPh); } char targetTemp[10]; char targetPh[10]; dtostrf(TemperatureControl::instance()->getTargetTemperature(), 4, 2, targetTemp); dtostrf(PHControl::instance()->getTargetPh(), 5, 3, targetPh); static const char header[] = "time,tankid,temp,temp setpoint,pH,pH setpoint,onTime,Kp,Ki,Kd"; static const char format[] PROGMEM = "%02i/%02i/%4i %02i:%02i:%02i, %3i, %s, %s, %s, %s, %4lu"; char buffer[128]; DateTime_TC dtNow = DateTime_TC::now(); PID_TC *pPID = PID_TC::instance(); uint16_t tankId = EEPROM_TC::instance()->getTankID(); snprintf_P(buffer, sizeof(buffer), (PGM_P)format, (uint16_t)dtNow.month(), (uint16_t)dtNow.day(), (uint16_t)dtNow.year(), (uint16_t)dtNow.hour(), (uint16_t)dtNow.minute(), (uint16_t)dtNow.second(), (uint16_t)tankId, currentTemp, targetTemp, currentPh, targetPh, (unsigned long)(millis() / 1000)); strcpy_P(buffer + strnlen(buffer, sizeof(buffer)), (PGM_P)F(", ")); dtostrf(pPID->getKp(), 8, 1, buffer + strnlen(buffer, sizeof(buffer))); strcpy_P(buffer + strnlen(buffer, sizeof(buffer)), (PGM_P)F(", ")); dtostrf(pPID->getKi(), 8, 1, buffer + strnlen(buffer, sizeof(buffer))); strcpy_P(buffer + strnlen(buffer, sizeof(buffer)), (PGM_P)F(", ")); dtostrf(pPID->getKd(), 8, 1, buffer + strnlen(buffer, sizeof(buffer))); SD_TC::instance()->appendData(header, buffer); nextWriteTime = msNow / 1000 * 1000 + 1000; // round up to next second COUT(buffer); } /** * once per minute write the current data to the serial port */ void TankController::writeDataToSerial() { static uint32_t nextWriteTime = 0; uint32_t msNow = millis(); if (nextWriteTime <= msNow) { DateTime_TC dtNow = DateTime_TC::now(); char buffer[30]; snprintf_P(buffer, sizeof(buffer), (PGM_P)F("%02d:%02d pH="), (uint16_t)dtNow.hour(), (uint16_t)dtNow.minute()); dtostrf((float)PHProbe::instance()->getPh(), 5, 3, buffer + strnlen(buffer, sizeof(buffer))); strcpy_P(buffer + strnlen(buffer, sizeof(buffer)), (PGM_P)F(" temp=")); dtostrf((float)TempProbe_TC::instance()->getRunningAverage(), 5, 2, buffer + strnlen(buffer, sizeof(buffer))); serial(buffer); nextWriteTime = msNow / 60000 * 60000 + 60000; // round up to next minute COUT(buffer); } } #if defined(__CYGWIN__) size_t strnlen(const char *s, size_t n) { void *found = memchr(s, '\0', n); return found ? (size_t)((char *)found - s) : n; } #endif
32.268852
116
0.663585
jgfoster
a2462875ea82351ccbadd2ad9f9c0f02f6cc1def
15
cpp
C++
Minecraft/src/MC.cpp
Zubairch/Minecraft
70a8449778560b0280b97e45d5e3d317846e0d6c
[ "MIT" ]
null
null
null
Minecraft/src/MC.cpp
Zubairch/Minecraft
70a8449778560b0280b97e45d5e3d317846e0d6c
[ "MIT" ]
null
null
null
Minecraft/src/MC.cpp
Zubairch/Minecraft
70a8449778560b0280b97e45d5e3d317846e0d6c
[ "MIT" ]
null
null
null
#include "MC.h"
15
15
0.666667
Zubairch
a2484585c07b25a364033c6bed33f319678298fb
1,298
cpp
C++
smtp/src/SmtpConfig.cpp
webOS-ports/mojomail
49358ac2878e010f5c6e3bd962f047c476c11fc3
[ "Apache-2.0" ]
6
2015-01-09T02:20:27.000Z
2021-01-02T08:14:23.000Z
mojomail/smtp/src/SmtpConfig.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
3
2019-05-11T19:17:56.000Z
2021-11-24T16:04:36.000Z
mojomail/smtp/src/SmtpConfig.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
6
2015-01-09T02:21:13.000Z
2021-01-02T02:37:10.000Z
// @@@LICENSE // // Copyright (c) 2010-2013 LG Electronics, 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. // // LICENSE@@@ #include "SmtpConfig.h" #include "SmtpCommon.h" SmtpConfig SmtpConfig::s_instance; SmtpConfig::SmtpConfig() : m_inactivityTimeout(30) // 30 seconds { } SmtpConfig::~SmtpConfig() { } void SmtpConfig::GetOptionalInt(const MojObject& obj, const char* prop, int& value, int minValue, int maxValue) { bool hasProp = false; int temp = value; MojErr err = obj.get(prop, temp, hasProp); ErrorToException(err); if(hasProp) { value = std::max(minValue, std::min(temp, maxValue)); } } MojErr SmtpConfig::ParseConfig(const MojObject& conf) { GetOptionalInt(conf, "inactivityTimeoutSeconds", m_inactivityTimeout, 0, MojInt32Max); return MojErrNone; }
24.961538
111
0.728043
webOS-ports
a2495a14ab5492495833a225fd1f9a7f33faa546
304
cpp
C++
aoj/ITP1/ITP1D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
aoj/ITP1/ITP1D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
aoj/ITP1/ITP1D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int S; cin >> S; int h, m, s; s = S % 60; S /= 60; m = S % 60; S /= 60; h = S; cout << h << ":" << m << ":" << s << endl; return 0; }
14.47619
46
0.430921
xirc
a24d937339866c2f4df4ae1c7cc203f62b82ceac
3,137
cpp
C++
test/test_com/testTableInfo.cpp
yiliangwu880/CppDbProxy
05015730b9877003ef22f281a30cb80bed8dbf27
[ "BSD-3-Clause" ]
null
null
null
test/test_com/testTableInfo.cpp
yiliangwu880/CppDbProxy
05015730b9877003ef22f281a30cb80bed8dbf27
[ "BSD-3-Clause" ]
null
null
null
test/test_com/testTableInfo.cpp
yiliangwu880/CppDbProxy
05015730b9877003ef22f281a30cb80bed8dbf27
[ "BSD-3-Clause" ]
null
null
null
/* brief: use example and test code */ #include "../com/unit_test.h" #include <functional> #include <limits> #include <queue> #include <string> #include <vector> #include <map> #include <unordered_map> #include "function_traits.h" #include "db_driver/include/db_driver.h" #include "external/svr_util/include/easy_code.h" #include "external/svr_util/include/str_util.h" #include "dbProto/dbStructPack.h" using namespace std; using namespace lc; using namespace su; using namespace db; using namespace proto; UNITTEST(testTableInfo) { UNIT_ASSERT(TableCfg::Ins().GetTable(3) != nullptr); //check Player2 { const Table &table = *(TableCfg::Ins().GetTable(2)); UNIT_ASSERT(table.m_vecField.size() == 7); const Field f = table.m_vecField[0]; UNIT_ASSERT(f.name == "id2"); UNIT_ASSERT(f.type == FieldType::t_uint64_t); UNIT_ASSERT(f.keyType == KeyType::MAIN); UNIT_ASSERT(f.pOffset == sizeof(BaseTable)); UNIT_ASSERT(f.fieldSize == sizeof(Player2::id2)); UNIT_ASSERT(f.packFun == (db::PackFun)db::Pack<uint64_t>); UNIT_ASSERT(f.unpackFun == (db::UnpackFun)db::Unpack<uint64_t>); } //check Player3 { const Table &table = *(TableCfg::Ins().GetTable(3)); UNIT_ASSERT(table.m_vecField.size() == 8); { const Field f = table.m_vecField[0]; UNIT_ASSERT(f.name == "id"); UNIT_ASSERT(f.type == FieldType::t_uint64_t); UNIT_ASSERT(f.keyType == KeyType::MAIN); UNIT_ASSERT(f.pOffset == sizeof(BaseTable)); UNIT_ASSERT(f.fieldSize == sizeof(Player3::id)); } { const Field f = table.m_vecField[1]; UNIT_ASSERT(f.name == "id1"); UNIT_ASSERT(f.type == FieldType::t_uint32_t); UNIT_ASSERT(f.keyType == KeyType::NONE); UNIT_ASSERT(f.pOffset == sizeof(BaseTable) + sizeof(uint64_t)); UNIT_ASSERT(f.fieldSize == sizeof(Player3::id1)); } { struct A { uint64_t i;uint32_t i2; }; const Field f = table.m_vecField[2]; UNIT_ASSERT(f.name == "id2"); UNIT_ASSERT(f.type == FieldType::t_uint64_t); UNIT_ASSERT(f.keyType == KeyType::INDEX); UNIT_ASSERT(f.pOffset == sizeof(BaseTable) + sizeof(A)); UNIT_ASSERT(f.fieldSize == sizeof(Player3::id2)); } { const Field f = table.m_vecField[3]; UNIT_ASSERT(f.name == "myblob1"); UNIT_ASSERT(f.type == FieldType::t_bytes); UNIT_ASSERT(f.keyType == KeyType::NONE); UNIT_ASSERT(f.fieldSize == 0); UNIT_ASSERT(f.packFun == (db::PackFun)db::Pack<Bytes>); UNIT_ASSERT(f.unpackFun == (db::UnpackFun)db::Unpack<Bytes>); } { const Field f = table.m_vecField[4]; UNIT_ASSERT(f.name == "id3"); UNIT_ASSERT(f.type == FieldType::t_uint32_t); UNIT_ASSERT(f.keyType == KeyType::NONE); UNIT_ASSERT(f.fieldSize == sizeof(Player3::id3)); UNIT_ASSERT(f.packFun == (db::PackFun)db::Pack<uint32_t>); UNIT_ASSERT(f.unpackFun == (db::UnpackFun)db::Unpack<uint32_t>); } { const Field f = table.m_vecField[5]; UNIT_ASSERT(f.name == "myblob2"); UNIT_ASSERT(f.type == FieldType::t_string); UNIT_ASSERT(f.keyType == KeyType::NONE); UNIT_ASSERT(f.fieldSize == 0); } } }
29.87619
68
0.656678
yiliangwu880
a2504912123affb210563bd4316776dc63887f0a
1,355
cpp
C++
Tests/base/test_ThreadPool.cpp
dingjiefeng/selfServer
b1d496c855aaa3758034167dc4477595ae789f85
[ "MIT" ]
null
null
null
Tests/base/test_ThreadPool.cpp
dingjiefeng/selfServer
b1d496c855aaa3758034167dc4477595ae789f85
[ "MIT" ]
null
null
null
Tests/base/test_ThreadPool.cpp
dingjiefeng/selfServer
b1d496c855aaa3758034167dc4477595ae789f85
[ "MIT" ]
null
null
null
// // Created by jeff on 18-6-6. // #include "gtest/gtest.h" #include "gmock/gmock.h" #include "../../server/base/ThreadPool.h" using namespace selfServer; using testing::Eq; class TestThreadPool : public testing::Test { public: TestThreadPool() = default; }; TEST_F(TestThreadPool, demo) { std::mutex mtx; try { ThreadPool tp; std::vector<std::future<int>> v; std::vector<std::future<void>> v1; for (int i = 0; i <= 10; ++i) { auto ans = tp.add([](int answer) { return answer; }, i); v.push_back(std::move(ans)); } for (int i = 0; i <= 5; ++i) { auto ans = tp.add([&mtx](const std::string& str1, const std::string& str2) { std::lock_guard<std::mutex> lg(mtx); std::cout << (str1 + str2) << std::endl; return; }, "hello ", "world"); v1.push_back(std::move(ans)); } for (auto &i : v) { std::lock_guard<std::mutex> lg(mtx); std::cout << i.get() << std::endl; } for (auto &i : v1) { i.get(); } } catch (std::exception& e) { std::cout << e.what() << std::endl; } }
25.092593
86
0.44059
dingjiefeng
a2549af421338315ea530fab11cc1be7829ddbd1
8,243
cpp
C++
src/Providers/UNIXProviders/NFS/UNIX_NFSProvider.cpp
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/NFS/UNIX_NFSProvider.cpp
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/NFS/UNIX_NFSProvider.cpp
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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 "UNIX_NFSProvider.h" UNIX_NFSProvider::UNIX_NFSProvider() { } UNIX_NFSProvider::~UNIX_NFSProvider() { } CIMInstance UNIX_NFSProvider::constructInstance( const CIMName &className, const CIMNamespaceName &nameSpace, const UNIX_NFS &_p) const { CIMProperty p; CIMInstance inst(className); // Set path inst.setPath(CIMObjectPath(String(""), // hostname nameSpace, CIMName("UNIX_NFS"), constructKeyBindings(_p))); //CIM_ManagedElement Properties if (_p.getInstanceID(p)) inst.addProperty(p); if (_p.getCaption(p)) inst.addProperty(p); if (_p.getDescription(p)) inst.addProperty(p); if (_p.getElementName(p)) inst.addProperty(p); //CIM_ManagedSystemElement Properties if (_p.getInstallDate(p)) inst.addProperty(p); if (_p.getName(p)) inst.addProperty(p); if (_p.getOperationalStatus(p)) inst.addProperty(p); if (_p.getStatusDescriptions(p)) inst.addProperty(p); if (_p.getStatus(p)) inst.addProperty(p); if (_p.getHealthState(p)) inst.addProperty(p); if (_p.getCommunicationStatus(p)) inst.addProperty(p); if (_p.getDetailedStatus(p)) inst.addProperty(p); if (_p.getOperatingStatus(p)) inst.addProperty(p); if (_p.getPrimaryStatus(p)) inst.addProperty(p); //CIM_LogicalElement Properties //CIM_EnabledLogicalElement Properties if (_p.getEnabledState(p)) inst.addProperty(p); if (_p.getOtherEnabledState(p)) inst.addProperty(p); if (_p.getRequestedState(p)) inst.addProperty(p); if (_p.getEnabledDefault(p)) inst.addProperty(p); if (_p.getTimeOfLastStateChange(p)) inst.addProperty(p); if (_p.getAvailableRequestedStates(p)) inst.addProperty(p); if (_p.getTransitioningToState(p)) inst.addProperty(p); //UNIX_FileSystem Properties if (_p.getCSCreationClassName(p)) inst.addProperty(p); if (_p.getCSName(p)) inst.addProperty(p); if (_p.getCreationClassName(p)) inst.addProperty(p); if (_p.getRoot(p)) inst.addProperty(p); if (_p.getBlockSize(p)) inst.addProperty(p); if (_p.getFileSystemSize(p)) inst.addProperty(p); if (_p.getAvailableSpace(p)) inst.addProperty(p); if (_p.getReadOnly(p)) inst.addProperty(p); if (_p.getEncryptionMethod(p)) inst.addProperty(p); if (_p.getCompressionMethod(p)) inst.addProperty(p); if (_p.getCaseSensitive(p)) inst.addProperty(p); if (_p.getCasePreserved(p)) inst.addProperty(p); if (_p.getCodeSet(p)) inst.addProperty(p); if (_p.getMaxFileNameLength(p)) inst.addProperty(p); if (_p.getClusterSize(p)) inst.addProperty(p); if (_p.getFileSystemType(p)) inst.addProperty(p); if (_p.getPersistenceType(p)) inst.addProperty(p); if (_p.getOtherPersistenceType(p)) inst.addProperty(p); if (_p.getNumberOfFiles(p)) inst.addProperty(p); //CIM_RemoteFileSystem Properties //CIM_NFS Properties if (_p.getHardMount(p)) inst.addProperty(p); if (_p.getForegroundMount(p)) inst.addProperty(p); if (_p.getInterrupt(p)) inst.addProperty(p); if (_p.getMountFailureRetries(p)) inst.addProperty(p); if (_p.getRetransmissionAttempts(p)) inst.addProperty(p); if (_p.getRetransmissionTimeout(p)) inst.addProperty(p); if (_p.getReadBufferSize(p)) inst.addProperty(p); if (_p.getWriteBufferSize(p)) inst.addProperty(p); if (_p.getServerCommunicationPort(p)) inst.addProperty(p); if (_p.getAttributeCaching(p)) inst.addProperty(p); if (_p.getAttributeCachingForRegularFilesMin(p)) inst.addProperty(p); if (_p.getAttributeCachingForRegularFilesMax(p)) inst.addProperty(p); if (_p.getAttributeCachingForDirectoriesMin(p)) inst.addProperty(p); if (_p.getAttributeCachingForDirectoriesMax(p)) inst.addProperty(p); return inst; } Array<CIMKeyBinding> UNIX_NFSProvider::constructKeyBindings(const UNIX_NFS& _p) const { Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding( PROPERTY_CS_CREATION_CLASS_NAME, _p.getCSCreationClassName(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding( PROPERTY_CS_NAME, _p.getCSName(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding( PROPERTY_CREATION_CLASS_NAME, _p.getCreationClassName(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding( PROPERTY_NAME, _p.getName(), CIMKeyBinding::STRING)); return keys; } #define __createInstance_H void UNIX_NFSProvider::createInstance( const OperationContext& context, const CIMObjectPath& ref, const CIMInstance& instanceObject, ObjectPathResponseHandler& handler ) { handler.processing(); CIMName className = ref.getClassName(); if (String::equal(className.getString(), String("UNIX_NFS"))) { Array<CIMKeyBinding> bindings = ref.getKeyBindings(); for(Uint32 i = 0; i < bindings.size(); i++) { String name = bindings[i].getName().getString(); if (String::equal(name, "Name")) { String source = bindings[i].getValue(); Uint32 rootIndex = instanceObject.findProperty(String("Root")); if (rootIndex != PEG_NOT_FOUND) { CIMConstProperty rootProperty = instanceObject.getProperty(rootIndex); CIMValue rootValue = rootProperty.getValue(); if (!rootValue.isNull()) { String target; rootValue.get(target); String cmd("mount -t nfs "); cmd.append(source); cmd.append(" "); cmd.append(target); system(cmd.getCString()); } } break; } } } handler.complete(); } #define __deleteInstance_H // ============================================================================= // NAME : createInstance // DESCRIPTION : Create a UnixProcess instance. // ASSUMPTIONS : None // PRE-CONDITIONS : // POST-CONDITIONS : // NOTES : Currently not supported. // PARAMETERS : // ============================================================================= void UNIX_NFSProvider::deleteInstance( const OperationContext& context, const CIMObjectPath& ref, ResponseHandler& handler) { handler.processing(); CIMName className = ref.getClassName(); if (String::equal(className.getString(), String("UNIX_NFS"))) { Array<CIMKeyBinding> bindings = ref.getKeyBindings(); for(Uint32 i = 0; i < bindings.size(); i++) { String name = bindings[i].getName().getString(); if (String::equal(name, "Name")) { String target = bindings[i].getValue(); String cmd("umount "); cmd.append(target); system(cmd.getCString()); break; } } } handler.complete(); } #define UNIX_PROVIDER UNIX_NFSProvider #define UNIX_PROVIDER_NAME "UNIX_NFSProvider" #define CLASS_IMPLEMENTATION UNIX_NFS #define CLASS_IMPLEMENTATION_NAME "UNIX_NFS" #define BASE_CLASS_NAME "CIM_NFS" #define NUMKEYS_CLASS_IMPLEMENTATION 4 #include "UNIXProviderBase.hpp"
32.840637
85
0.70023
brunolauze
a25887dcc9aab4ba6bd50a9afca7765d6a6049d3
18,102
cpp
C++
src/cpp/jail/resonanceDecay/functions.cpp
dereksoeder/iS3D
27fed56d697f8e4a0e08fa9cb261436f4a7c7f8c
[ "MIT" ]
1
2022-02-08T21:26:12.000Z
2022-02-08T21:26:12.000Z
src/cpp/jail/resonanceDecay/functions.cpp
dereksoeder/iS3D
27fed56d697f8e4a0e08fa9cb261436f4a7c7f8c
[ "MIT" ]
13
2018-06-13T19:29:07.000Z
2021-02-07T04:29:10.000Z
src/cpp/jail/resonanceDecay/functions.cpp
dereksoeder/iS3D
27fed56d697f8e4a0e08fa9cb261436f4a7c7f8c
[ "MIT" ]
7
2018-04-11T01:56:22.000Z
2021-07-09T23:00:21.000Z
/* functions.c functions for reso.c main program calculations * Josef Sollfrank Nov. .98 */ // Commented and adjusted by Evan Frodermann, Aug 2005 #include <string.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <iostream> #include "Table.h" #include "functions.h" #include "tools.h" // SB code !!! #define NUMDECAY 1700 /* size of array for storage of the decays */ #define NUMPARTICLE 400 /* size of array for storage of the particles */ #define MAXINTV 20000000 /* size of arry for Montecarlo numbers */ #define MHALF (MAXINTV/2) #define NY 200 #define NPT 50 /* size of arry for storage of the pt-spectrum */ #define NPHI 120 /* size of arry for storage of the y-spectrum */ #define NPHI1 NPHI + 1 #define PI 3.14159265358979323 /* any question? */ #define ALPHA 0.00729735308 /* fine structure constant 1/137.035...*/ #define HBARC 0.197327054 /* = plank constant times speed of light */ #define HBARC3 (HBARC*HBARC*HBARC) #define FILEDIM 140 extern struct par { long int mcID; /* Montecarlo number according PDG */ char name[26]; double mass; double width; int gspin; /* spin degeneracy */ int baryon; int strange; int charm; int bottom; int gisospin; /* isospin degeneracy */ int charge; int decays; /* amount of decays listed for this resonance */ int stable; /* defines whether this particle is considered as stable */ int npT; int nphi; int ny; double phimin; double phimax; double ymax; double deltaY; double dNdypTdpTdphi[NY][NPT][NPHI]; double mt[NPT]; /* mt values for spectrum */ double pt[NPT]; /* pt values for spectrum */ double y[NY]; // y values for spectrum double phi[NPHI]; double slope[NPHI1]; /* assymtotic slope of mt-spectrum */ }particle[NUMPARTICLE]; extern double PHI[NPHI]; /* Array for phi-storage */ /* decay array for each decay listed */ extern struct de { int reso; /* Montecarlo number of decaying resonance */ int numpart; /* number of daughter particles after decay */ double branch; /* branching ratio */ int part[5]; /* array of daughter particels Montecarlo number */ }particleDecay[NUMDECAY]; /* array for converting Montecarlo numbers in internal numbering of the resonances */ extern int partid[MAXINTV]; //******************************************************************************* // The following arrays are set for specific integration routines and point with // weights for those routines static double gaus2x[] = { 0.577350269189626 }; static double gaus4x[] = { 0.8611363115, 0.3399810435 }; static double gaus8x[] = { 0.9602898564, 0.7966664774, 0.3137066458, 0.3626837833 }; static double gaus10x[] = { 0.1488743389, 0.4333953941, 0.6794095682, 0.8650633666, 0.97390652 }; static double gaus12x[] = { 0.9815606342, 0.9041172563, 0.7699026741, 0.5873179542, 0.3678314989, 0.1252334085 }; static double gaus16x[] = { 0.989400934991650, 0.944575023073233, 0.865631202387832, 0.755404408355003, 0.617876244402644, 0.458016777657227, 0.281603550779259, 0.095012509837637 }; static double gaus20x[] = { 0.993128599185094, 0.963971927277913, 0.912234428251325, 0.839116971822218, 0.746331906460150, 0.636053680726515, 0.510867001950827, 0.373706088715419, 0.227785851141645, 0.076526521133497 }; static double gaus48x[] = { 0.998771007252426118601, 0.993530172266350757548, 0.984124583722826857745, 0.970591592546247250461, 0.952987703160430860723, 0.931386690706554333114, 0.905879136715569672822, 0.876572020274247885906, 0.843588261624393530711, 0.807066204029442627083, 0.767159032515740339254, 0.724034130923814654674, 0.677872379632663905212, 0.628867396776513623995, 0.577224726083972703818, 0.523160974722233033678, 0.466902904750958404545, 0.408686481990716729916, 0.348755886292160738160, 0.287362487355455576736, 0.224763790394689061225, 0.161222356068891718056, 0.097004699209462698930, 0.032380170962869362033 }; static double gala4x[] = { 0.322547689619, 1.745761101158, 4.536620296921, 9.395070912301 }; static double gala8x[] = { 0.170279632305, 0.903701776799, 2.251086629866, 4.266700170288, 7.045905402393, 10.758516010181, 15.740678641278, 22.863131736889 }; static double gala12x[] = { 0.115722117358, 0.611757484515, 1.512610269776, 2.833751337744, 4.599227639418, 6.844525453115, 9.621316842457, 13.006054993306, 17.116855187462, 22.151090379397, 28.487967250984, 37.099121044467 }; static double gala15x[] = { 0.093307812017, 0.492691740302, 1.215595412071, 2.269949526204, 3.667622721751, 5.425336627414, 7.565916226613, 10.120228568019, 13.130282482176, 16.654407708330, 20.776478899449, 25.623894226729, 31.407519169754, 38.530683306486, 48.026085572686 }; static double gala48x[] = { 2.9811235829960e-02, 0.15710799061788, 0.38626503757646, 0.71757469411697, 1.1513938340264, 1.6881858234190, 2.3285270066532, 3.0731108616526, 3.9227524130465, 4.8783933559213, 5.9411080546246, 7.1121105358907, 8.3927625990912, 9.7845831846873, 11.289259168010, 12.908657778286, 14.644840883210, 16.500081428965, 18.476882386874, 20.577998634022, 22.806462290521, 25.165612156439, 27.659128044481, 30.291071001009, 33.065930662499, 35.988681327479, 39.064848764198, 42.300590362903, 45.702792038511, 49.279186382837, 53.038498087817, 56.990624814804, 61.146864786140, 65.520206929019, 70.125706236113, 74.980977518911, 80.106857350324, 85.528311116034, 91.275707993668, 97.386667713582, 103.908833357176, 110.90422088498, 118.45642504628, 126.68342576889, 135.76258957786, 145.98643270946, 157.91561202298, 172.99632814856 }; //********************************************************************************* /************************************************************************** * * * readParticleData() * * * * reads in the particle data file and stores the datas in the arrays * * particle.* and decay.* and fills up the rest of data (antibaryons) * *********************************************************************** * **************************************************************************/ void readParticleData(char filename[FILEDIM], int* particlemax, int* decaymax) { int i = 0, j = 0, k, h; FILE *dat; double dummy1; for (k = 0; k < MAXINTV; k++) partid[k] = -1; dat = fopen(filename,"r"); if (dat == NULL) { printf(" NO file: %s available ! \n", filename); printf(" GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } // Read in the particle data from the specified resonance table // Save the data is the structure particle[pn] while(fscanf(dat,"%li%s%lf%lf%i%i%i%i%i%i%i%i", &particle[i].mcID, particle[i].name, &particle[i].mass, &particle[i].width, &particle[i].gspin, &particle[i].baryon, &particle[i].strange, &particle[i].charm, &particle[i].bottom, &particle[i].gisospin, &particle[i].charge, &particle[i].decays)==12) { partid[MHALF + particle[i].mcID] = i; particle[i].stable = 0; /* read in the decays */ // These decays are saved in a seperate data set, decay[i]. for (k = 0; k < particle[i].decays; k++) { h = fscanf(dat,"%i%i%lf%i%i%i%i%i", &particleDecay[j].reso, &particleDecay[j].numpart, &particleDecay[j].branch, &particleDecay[j].part[0], &particleDecay[j].part[1], &particleDecay[j].part[2], &particleDecay[j].part[3], &particleDecay[j].part[4]); if (h != 8) { printf("Error in scanf decay \n"); printf(" GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } if (particleDecay[j].numpart == 1) particle[i].stable = 1; j++; // Add one to the decay counting variable "j" } /* setting of additional parameters */ if (particle[i].baryon == 1) { i++;// If the particle is a baryon, add a particle for the anti-baryon // Add one to the counting variable "i" for the number of particles for the anti-baryon particle[i].mcID = -particle[i-1].mcID; strcpy(particle[i].name, " Anti-"); strncat(particle[i].name, particle[i-1].name, 18); particle[i].mass = particle[i-1].mass; particle[i].width = particle[i-1].width; particle[i].gspin = particle[i-1].gspin; particle[i].baryon = -particle[i-1].baryon; particle[i].strange = -particle[i-1].strange; particle[i].charm = -particle[i-1].charm; particle[i].bottom = -particle[i-1].bottom; particle[i].gisospin = particle[i-1].gisospin; particle[i].charge = -particle[i-1].charge; particle[i].decays = particle[i-1].decays; partid[MHALF + particle[i].mcID] = i; particle[i].stable = particle[i-1].stable; } i++; // Add one to the counting variable "i" for the meson/baryon } fclose(dat); *particlemax = i; // Set the maxparticle variable to be the value of "i" *decaymax = j; // Set the maxdecays variable to be the value of "j" if( (*particlemax) > NUMPARTICLE ) { printf("Array for particles too small! \n"); printf("GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } } //********************************************************************************* // This function reads in the EdN/d3p spectra calculated by spectra via the HYDRO output. // Set the pt points with the gaussian values given above. These are the same values // given to the spectra in the azspectra0p0 program. The default filename is phipspectra.dat void readSpectra(char specfile[FILEDIM], int *particlemax, int *decaymax) { char resofile[FILEDIM] = "EOS/pdg.dat"; int npa = 0; double dum, dum1, dum2; FILE *spec = fopen(specfile,"r"); if(spec == NULL) { printf(" NO file: %s available ! \n", specfile); printf(" GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } readParticleData(resofile, particlemax, decaymax); Table pT_tab("tables/pT_gauss_table.dat"); Table phi_tab("tables/phi_gauss_table.dat"); Table y_tab("tables/y_riemann_table_11pt.dat"); int npT = pT_tab.getNumberOfRows(); int nphi = phi_tab.getNumberOfRows(); int ny = y_tab.getNumberOfRows(); int WarningCounter = 0; for (int n = 0; n < *particlemax; n++) { npa++; int pn = n; if (pn == -1) { printf(" particle %i not in reso table ! \n"); printf(" GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } if (npT > NPT) { printf(" NPT = %i array to small !\n", npT); printf(" GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } if (nphi > NPHI) { printf(" NPHI = %i array to small !\n", nphi); printf(" GOOD BYE AND HAVE A NICE DAY! \n"); exit(0); } for (int ipT = 0; ipT < npT; ipT++) particle[pn].pt[ipT] = pT_tab.get(1,ipT + 1); for (int iy = 0; iy < ny; iy++) particle[pn].y[iy] = y_tab.get(1,iy + 1); for (int iphi = 0; iphi < nphi; iphi++) particle[pn].phi[iphi] = phi_tab.get(1,iphi + 1); particle[pn].slope[npT] = 1; particle[pn].nphi = nphi; particle[pn].npT = npT; for (int iy = 0; iy < ny; iy++) { for (int ipT = 0; ipT < npT; ipT++) { for (int iphi = 0; iphi < nphi; iphi++) { fscanf(spec,"%lf",&dum); particle[pn].dNdypTdpTdphi[iy][ipT][iphi] = dum; } } } } fclose(spec); if (npa > 0) printf(" Successful read in of %5i spectra !\n",npa); } //********************************************************************************************* // After calculating the spectra in the decay routines, this routine writes that data to file. // The spectra is written to spec_###.dat in block format for the pt/phi dependence. // The pt values for each point are saved to specPT_###.dat. The ### corresponds to the // monte carlo value number assigned the resonance table. The phi data was already stored in // angle.dat. (by default) void writeSpectra(int particlemax, char outdir[FILEDIM]) { FILE *out, *out2; char filename[FILEDIM]; char filename2[FILEDIM]; char p[SSL]; int i, j, k; for(i=1;i<particlemax;i++)// Cycle through the particles { if(particle[i].stable == 1) //Only print out the stable particles { strcpy(filename,outdir); strcpy(filename2,outdir); strcat(filename, "/spec_"); strcat(filename2, "/PT_"); if(particle[i].mcID < 0) { strcat(filename,"A"); strcat(filename2, "A"); } convei(abs(particle[i].mcID),p); strcat(filename,p); strcat(filename2,p); strcat(filename,".dat"); strcat(filename2, ".dat"); printf(" Produce %s \n", filename); printf(" Produce %s \n", filename2); out = fopen(filename,"w"); out2 = fopen(filename2, "w"); for(k=0;k<particle[i].nphi;k++) //Print out the desired data. { for(j=0;j<particle[i].npT;j++) { fprintf(out," %11.4lE", particle[i].dNdypTdpTdphi[j][k]); } fprintf(out,"\n"); } for(j=0;j<particle[i].npT;j++) { fprintf(out2," %11.4lE", particle[i].pt[j]); } fprintf(out2,"\n"); fclose(out); fclose(out2); } } } /************************************************* * * Edndp3 * **************************************************/ // This function interpolates the needed spectra for a given y, pt and phi. double Edndp3(double yr, double ptr, double phirin, int res_num) // double yr; /* y of resonance */ // double ptr; /* pt of resonance */ // double phirin; /* phi angle of resonance */ // int res_num; /* Montecarlo number of resonance */ { // if pseudofreeze flag is set, yr is the *pseudorapidity* of the resonance if (phirin < 0.0) { printf("ERROR: phir %15.8le < 0 !!! \n", phirin); exit(0); } if (phirin > 2.0*PI) { printf("ERROR: phir %15.8le > 2PI !!! \n", phirin); exit(0); } double phir = phirin; int pn = partid[MHALF + res_num]; if (ptr > particle[pn].pt[particle[pn].npT - 1]) return 0.; if (fabs(yr) > particle[pn].ymax && !BOOST_INV) return 0.; int nphi = 1; while ( (phir > PHI[nphi]) && ( nphi < (particle[pn].nphi-1) ) ) nphi++; int npT = 1; while (ptr > particle[pn].pt[npT] && npT<(particle[pn].npT - 1)) npT++; int ny = 1; while ( yr > particle[pn].y[ny] && ny < (particle[pn].ny - 1) ) ny++; /* phi interpolation */ double f1 = lin_int(PHI[nphi-1], PHI[nphi], particle[pn].dNdypTdpTdphi[ny-1][npT-1][nphi-1], particle[pn].dNdypTdpTdphi[ny-1][npT-1][nphi], phir); double f2 = lin_int(PHI[nphi-1], PHI[nphi], particle[pn].dNdypTdpTdphi[ny-1][npT][nphi-1], particle[pn].dNdypTdpTdphi[ny-1][npT][nphi], phir); // security: if for some reason we got a negative number of particles // (happened in the viscous code at large eta sometimes) if (f1 < 0.) f1 = 1e-30; if (f2 < 0.) f2 = 1e-30; double f1s = f1; double f2s = f2; /* if (ptr > PTCHANGE && f1s > 0 && f2s > 0) { f1 = log(f1); f2 = log(f2); } */ double val1 = lin_int(particle[pn].pt[npT-1], particle[pn].pt[npT], f1, f2, ptr); //if (ptr > PTCHANGE && f1s > 0 && f2s > 0) val1 = exp(val1); f1 = lin_int(PHI[nphi-1], PHI[nphi], particle[pn].dNdypTdpTdphi[ny][npT-1][nphi-1], particle[pn].dNdypTdpTdphi[ny][npT-1][nphi], phir); f2 = lin_int(PHI[nphi-1], PHI[nphi], particle[pn].dNdypTdpTdphi[ny][npT][nphi-1], particle[pn].dNdypTdpTdphi[ny][npT][nphi], phir); // security: if for some reason we got a negative number of particles // (happened in the viscous code at large eta sometimes) if (f1 < 0.) f1 = 1e-30; if (f2 < 0.) f2 = 1e-30; f1s = f1; f2s = f2; /* if (ptr > PTCHANGE && f1s > 0 && f2s > 0) { f1 = log(f1); f2 = log(f2); } */ double val2 = lin_int(particle[pn].pt[npT-1], particle[pn].pt[npT], f1, f2, ptr); //if (ptr > PTCHANGE && f1s > 0 && f2s > 0) val2 = exp(val2); double val = lin_int(particle[pn].y[ny-1], particle[pn].y[ny], val1, val2, yr); return val; }
39.266811
149
0.547011
dereksoeder
a25ac13369dbdab79dee4c7dd3e0c174b7850163
133
cpp
C++
src/ambient_light.cpp
movhex/raytracer
7ce364f5dcc829ac54c81edeee520dabc916c6d8
[ "BSD-2-Clause" ]
2
2021-11-29T10:59:06.000Z
2021-11-29T21:26:21.000Z
src/ambient_light.cpp
movhex/raytracer
7ce364f5dcc829ac54c81edeee520dabc916c6d8
[ "BSD-2-Clause" ]
null
null
null
src/ambient_light.cpp
movhex/raytracer
7ce364f5dcc829ac54c81edeee520dabc916c6d8
[ "BSD-2-Clause" ]
null
null
null
#if !defined(HAVE_CUDA) #include "ambient_light.h" #define INCLUDE_IMPLEMENTATION_FILE #include "ambient_light_cpu_impl.h" #endif
14.777778
35
0.804511
movhex
a2612b17054fc8a74bdfb93224a4b8338badb8de
688
cpp
C++
Source/SimpleShooter/BTTask_Shoot.cpp
scarriere/udemy-simple-shooter
04cf7217ae2f3b48daef391622fa0ab86a5f7f33
[ "MIT" ]
null
null
null
Source/SimpleShooter/BTTask_Shoot.cpp
scarriere/udemy-simple-shooter
04cf7217ae2f3b48daef391622fa0ab86a5f7f33
[ "MIT" ]
null
null
null
Source/SimpleShooter/BTTask_Shoot.cpp
scarriere/udemy-simple-shooter
04cf7217ae2f3b48daef391622fa0ab86a5f7f33
[ "MIT" ]
null
null
null
// // Copyright Samuel Carriere 2020 #include "BTTask_Shoot.h" #include "ShooterCharacter.h" #include "AIController.h" #include "BehaviorTree/BehaviorTreeComponent.h" UBTTask_Shoot::UBTTask_Shoot() { NodeName = TEXT("Shoot"); } EBTNodeResult::Type UBTTask_Shoot::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { Super::ExecuteTask(OwnerComp, NodeMemory); if (OwnerComp.GetAIOwner() == nullptr) return EBTNodeResult::Failed; AShooterCharacter* ShooterCharacter = Cast<AShooterCharacter>(OwnerComp.GetAIOwner()->GetPawn()); if (ShooterCharacter == nullptr) return EBTNodeResult::Failed; ShooterCharacter->PullTrigger(); return EBTNodeResult::Succeeded; }
25.481481
100
0.777616
scarriere
a2638e9d4a3b0f639c6cea0cc8c39cb32502f8b6
2,667
cpp
C++
src/GUI_Alert.cpp
paracelso93/GiocoDeiPianeti
271d108d4516f1cc545f846c87808bb698f5c3bd
[ "MIT" ]
null
null
null
src/GUI_Alert.cpp
paracelso93/GiocoDeiPianeti
271d108d4516f1cc545f846c87808bb698f5c3bd
[ "MIT" ]
null
null
null
src/GUI_Alert.cpp
paracelso93/GiocoDeiPianeti
271d108d4516f1cc545f846c87808bb698f5c3bd
[ "MIT" ]
null
null
null
#include "GUI_Alert.h" bool GUI_Alert::mVisible = false; GUI_Panel GUI_Alert::mBackground = GUI_Panel(); GUI_Label GUI_Alert::mTitleLabel = GUI_Label(); GUI_Label GUI_Alert::mTextLabel = GUI_Label(); sf::Font GUI_Alert::mFont = sf::Font(); int GUI_Alert::mButtonNumber = 0; std::vector<GUI_Button *> GUI_Alert::mButtons = std::vector<GUI_Button *>(); void GUI_Alert::setup(sf::Color bgcolor, std::string title, std::string text, sf::Color textColor, int bNumber, sf::Color *buttonColors, std::string *buttonStrings, sf::Font f, void (*buttonFunctions[])()) { mFont = f; mBackground.setup({710, 390}, {500, 300}, bgcolor, sf::Color::Yellow, mFont, close); mTitleLabel.setup(title, textColor, mFont, 50, {static_cast<float>(710 + 250 - (title.length() / 2 - 1) * 50), 400}); int len = 0; while(text[len] != '\n') { len++; } mTextLabel.setup(text, textColor, mFont, 20, {static_cast<float>(710 + 250 - (len / 2) * 15), 460}); mVisible = false; mButtonNumber = bNumber; mButtons.clear(); for(int i = 0; i < mButtonNumber; i++) { sf::RectangleShape s; GUI_Button* button = new GUI_Button(); if(mButtonNumber % 2 == 0) { if(i < mButtonNumber / 2) { s.setPosition(710 + 250 - (mButtonNumber / 2 - i) * 100, 600); } else { s.setPosition(710 + 250 + (mButtonNumber / 2 - i) * 100, 600); } } else { if(i < (mButtonNumber - 1) / 2) { s.setPosition(710 + 250 - (mButtonNumber / 2 - i) * 100 - 40, 600); } else if(i > (mButtonNumber - 1) / 2) { s.setPosition(710 + 250 + (mButtonNumber / 2 - i) * 100 + 40, 600); } else { s.setPosition(710 + 250 - 40, 600); } } s.setSize({80, 50}); button->setup(mFont, s, buttonColors[i], buttonColors[i], buttonStrings[i], 20); button->setFunction(buttonFunctions[i]); mButtons.push_back(button); } } void GUI_Alert::render(sf::RenderWindow& window) { if(mVisible) { mBackground.render(window); mTitleLabel.render(window); mTextLabel.render(window); for(auto b : mButtons) { b->render(window); } } } void GUI_Alert::getInput(sf::Vector2i mousePos) { mBackground.getExit(mousePos); for(int i = 0; i < mButtonNumber; i++) { if(mButtons[i]->checkForClick(mousePos)) { //std::cout << "click!" << std::endl; mButtons[i]->click(); //std::cout << ((openTab == Tabs::none) ? "none" : "oops!") << std::endl; } } }
37.041667
207
0.55943
paracelso93
a26ac8f52cb6242b7cb68ca27beae236bd78d3bd
3,377
cpp
C++
sources/rotationToSliderNode.cpp
jpasserin/harbieNodes
a78823869dd79b9f465f14fe07bfc91ca1850a7b
[ "MIT" ]
5
2021-12-15T08:50:57.000Z
2022-01-26T16:01:08.000Z
sources/rotationToSliderNode.cpp
jpasserin/harbieNodes
a78823869dd79b9f465f14fe07bfc91ca1850a7b
[ "MIT" ]
null
null
null
sources/rotationToSliderNode.cpp
jpasserin/harbieNodes
a78823869dd79b9f465f14fe07bfc91ca1850a7b
[ "MIT" ]
null
null
null
#include "../headers/_Utils.h" #include "../headers/rotationToSliderNode.h" #include <maya/MPlug.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MFnUnitAttribute.h> #include <maya/MGlobal.h> // Static Members MTypeId RotationToSlider::id(0x001226CB); MObject RotationToSlider::angle; MObject RotationToSlider::rotMin; MObject RotationToSlider::rotMax; MObject RotationToSlider::sliderMin; MObject RotationToSlider::sliderMax; MObject RotationToSlider::output; //--------------------------------------------------- RotationToSlider::RotationToSlider(){} RotationToSlider::~RotationToSlider(){} void* RotationToSlider::creator() { return new RotationToSlider(); } MStatus RotationToSlider::initialize() { MStatus stat; MFnNumericAttribute fnNum; MFnUnitAttribute fnUnit; angle = fnNum.create("angle", "a", MFnNumericData::kDouble, 0.0, &stat); CHECK_MSTATUS(stat); fnNum.setKeyable(true); stat = RotationToSlider::addAttribute(angle); CHECK_MSTATUS(stat); rotMin = fnNum.create("rotMin", "rmin", MFnNumericData::kDouble, -90.0, &stat); CHECK_MSTATUS(stat); fnNum.setKeyable(true); fnNum.setMin(-360); fnNum.setMax(-0.0001); stat = RotationToSlider::addAttribute(rotMin); CHECK_MSTATUS(stat); rotMax = fnNum.create("rotMax", "rmax", MFnNumericData::kDouble, 90.0, &stat); CHECK_MSTATUS(stat); fnNum.setKeyable(true); fnNum.setMin(0.0001); fnNum.setMax(360); stat = RotationToSlider::addAttribute(rotMax); CHECK_MSTATUS(stat); sliderMin = fnUnit.create("sliderMin", "smin", MFnUnitAttribute::kDistance, -1.0, &stat); CHECK_MSTATUS(stat); fnUnit.setKeyable(true); stat = RotationToSlider::addAttribute(sliderMin); CHECK_MSTATUS(stat); sliderMax = fnUnit.create("sliderMax", "smax", MFnUnitAttribute::kDistance, 1.0, &stat); CHECK_MSTATUS(stat); fnUnit.setKeyable(true); stat = RotationToSlider::addAttribute(sliderMax); CHECK_MSTATUS(stat); output = fnUnit.create("output", "out", MFnUnitAttribute::kDistance, 0.0, &stat); CHECK_MSTATUS(stat); fnUnit.setWritable(false); fnUnit.setStorable(true); stat = RotationToSlider::addAttribute(output); CHECK_MSTATUS(stat); RotationToSlider::attributeAffects(angle, output); RotationToSlider::attributeAffects(rotMin, output); RotationToSlider::attributeAffects(rotMax, output); RotationToSlider::attributeAffects(sliderMin, output); RotationToSlider::attributeAffects(sliderMax, output); return MS::kSuccess; } MStatus RotationToSlider::compute(const MPlug &plug, MDataBlock &data) { if (plug != RotationToSlider::output) return MS::kUnknownParameter; double angle = data.inputValue(RotationToSlider::angle).asDouble(); //Process double outValue = 0.0; if (angle > 0.0){ double rotMax = data.inputValue(RotationToSlider::rotMax).asDouble(); double sliderMax = data.inputValue(RotationToSlider::sliderMax).asDouble(); outValue = sliderMax * min(1.0, angle / rotMax); } else{ double rotMin = data.inputValue(RotationToSlider::rotMin).asDouble(); double sliderMin = data.inputValue(RotationToSlider::sliderMin).asDouble(); outValue = sliderMin * min(1.0, angle / rotMin); } // division by zero is bad. if (std::isnan(outValue)) outValue = 0.0; // set the output handle data.outputValue(RotationToSlider::output).setDouble(outValue); // set the plug clean data.setClean(plug); return MS::kSuccess; }
25.778626
90
0.737933
jpasserin
a26d62739e8b26e1ef5303eb6c14742b2550b76f
2,996
cpp
C++
newsimplifythesquareroot.cpp
sagar-sam/codechef-solutions
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
[ "MIT" ]
null
null
null
newsimplifythesquareroot.cpp
sagar-sam/codechef-solutions
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
[ "MIT" ]
null
null
null
newsimplifythesquareroot.cpp
sagar-sam/codechef-solutions
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> #include <math.h> #include <algorithm> #include <iterator> using namespace std; vector<int> sieve(30000001); void calculate_sieve() { for(int i=0;i<30000001;i++) { sieve[i]=-1; } for(int i=4;i<30000001;i+=2) { sieve[i]=2; } for(int i=3;i*i<30000001;i+=2) { if(sieve[i]==-1) { for(int j=i*i;j<30000001;j+=i) { if(sieve[j]==-1) { sieve[j]=i; } } } } } int maina() { calculate_sieve(); long long int n; scanf("%lld",&n); long long int m=3*n; long long int x=sqrt(m); map<long long int,int> mp; vector<long long int> vec; for(long long int i=4;i<=m;i=i+4) { vec.push_back(i); mp[i]++; } vector<int> consider; for(int i=3;i<=x;i=i+2) { if(sieve[i]==-1) { consider.push_back(i); } } for(int i=0;i<consider.size();i++) { long long int sa=consider[i]*consider[i]; for(long long int j=sa;j<=m;j=j+sa) { if(mp[j]==0) { mp[j]++; // s.insert(j); vec.push_back(j); // printf(" %d ",j); } // s.insert(j); } } sort(vec.begin(),vec.end()); printf("%lld\n",vec[n-1]); } int main() { calculate_sieve(); long long int n; scanf("%lld",&n); long long int start=2*n; long long int end=4*n; long long int x=sqrt(end); while(start<=end) { long long int mid=start+(end-start)/2; long long int count=0; for(long long int i=2;i<=x;i++) { if(sieve[i]==-1) { long long int cal=mid/(i*i); count+=cal; } else { int flag=0; long long int j=i; map<long long int,int> mp; mp[sieve[j]]++; while(sieve[j]!=-1) { j=j/sieve[j]; if(sieve[j]==-1) { mp[j]++; // if(mp[j]==1) // { // flag=1; // } // else mp[j]++; } else { mp[sieve[j]]++; // if(mp[sieve[j]]==1) // { // flag=1; // } // else mp[sieve[j]]++; } } for(map<long long int,int>::iterator it=mp.begin();it!=mp.end();it++) { if(it->second>1) { flag=1; } } if(flag==0) { long long int cal=mid/(i*i); long long int terms=mp.size(); // terms--; // cal=cal*terms; if(terms%2==0) count=count-cal; else count=count+cal; } } } if(count==n) { long long int te=mid; int flag=0; for(long long int i=2;i*i<=te;i++) { long long int j=i*i; if(te%j==0) { flag=1; break; } } // map<long long int,int> ne; // ne[sieve[te]]++; // int flag=0; // while(sieve[te]!=-1) // { // te=te/sieve[te]; // if(sieve[te]==-1) // { // if(ne[te]==1) // { // flag=1; // break; // } // } // else // { // if(ne[sieve[te]]==1) // { // flag=1; // break; // } // else ne[sieve[te]]++; // } // } if(flag==1) { printf("%lld\n",mid); break; } else { end=mid-1; } } else if(count>n) { end=mid-1; } else start=mid+1; } }
14.831683
73
0.470961
sagar-sam
a273cd568aa090be306621cf15e4ee55e1178497
9,255
cpp
C++
common/ScratchpadDatapath.cpp
httsai/NTHU_Aladdin
4140fcdade512b89647608b9b724690c5d3b2ba4
[ "BSL-1.0" ]
null
null
null
common/ScratchpadDatapath.cpp
httsai/NTHU_Aladdin
4140fcdade512b89647608b9b724690c5d3b2ba4
[ "BSL-1.0" ]
null
null
null
common/ScratchpadDatapath.cpp
httsai/NTHU_Aladdin
4140fcdade512b89647608b9b724690c5d3b2ba4
[ "BSL-1.0" ]
null
null
null
/* Implementation of an accelerator datapath that uses a private scratchpad for * local memory. */ #include <string> #include "ScratchpadDatapath.h" ScratchpadDatapath::ScratchpadDatapath( std::string bench, std::string trace_file, std::string config_file, float cycle_t) : BaseDatapath(bench, trace_file, config_file, cycle_t) {} ScratchpadDatapath::~ScratchpadDatapath() {} void ScratchpadDatapath::setScratchpad(Scratchpad *spad) { std::cerr << "-------------------------------" << std::endl; std::cerr << " Setting ScratchPad " << std::endl; std::cerr << "-------------------------------" << std::endl; scratchpad = spad; } void ScratchpadDatapath::globalOptimizationPass() { // Node removals must come first. removeInductionDependence(); removePhiNodes(); // Base address must be initialized next. initBaseAddress(); completePartition(); scratchpadPartition(); loopFlatten(); loopUnrolling(); memoryAmbiguation(); removeSharedLoads(); storeBuffer(); removeRepeatedStores(); treeHeightReduction(); // Must do loop pipelining last; after all the data/control dependences are fixed loopPipelining(); } /* * Read: graph, getElementPtr.gz, completePartitionConfig, PartitionConfig * Modify: baseAddress */ void ScratchpadDatapath::initBaseAddress() { std::cerr << "-------------------------------" << std::endl; std::cerr << " Init Base Address " << std::endl; std::cerr << "-------------------------------" << std::endl; std::unordered_map<std::string, unsigned> comp_part_config; readCompletePartitionConfig(comp_part_config); std::unordered_map<std::string, partitionEntry> part_config; readPartitionConfig(part_config); std::unordered_map<unsigned, pair<std::string, long long int> > getElementPtr; initGetElementPtr(getElementPtr); edgeToParid = get(boost::edge_name, graph_); vertex_iter vi, vi_end; for (tie(vi, vi_end) = vertices(graph_); vi != vi_end; ++vi) { if (boost::degree(*vi, graph_) == 0) continue; Vertex curr_node = *vi; unsigned node_id = vertexToName[curr_node]; int node_microop = microop.at(node_id); if (!is_memory_op(node_microop)) continue; bool modified = 0; //iterate its parents, until it finds the root parent while (true) { bool found_parent = 0; in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(curr_node , graph_); in_edge_it != in_edge_end; ++in_edge_it) { int edge_parid = edgeToParid[*in_edge_it]; if ( ( node_microop == LLVM_IR_Load && edge_parid != 1 ) || ( node_microop == LLVM_IR_GetElementPtr && edge_parid != 1 ) || ( node_microop == LLVM_IR_Store && edge_parid != 2) ) continue; unsigned parent_id = vertexToName[source(*in_edge_it, graph_)]; int parent_microop = microop.at(parent_id); if (parent_microop == LLVM_IR_GetElementPtr || parent_microop == LLVM_IR_Load) { //remove address calculation directly baseAddress[node_id] = getElementPtr[parent_id]; curr_node = source(*in_edge_it, graph_); node_microop = parent_microop; found_parent = 1; modified = 1; break; } else if (parent_microop == LLVM_IR_Alloca) { std::string part_name = getElementPtr[parent_id].first; baseAddress[node_id] = getElementPtr[parent_id]; modified = 1; break; } } if (!found_parent) break; } if (!modified) baseAddress[node_id] = getElementPtr[node_id]; std::string part_name = baseAddress[node_id].first; if (part_config.find(part_name) == part_config.end() && comp_part_config.find(part_name) == comp_part_config.end() ) { std::cerr << "Unknown partition : " << part_name << "@inst: " << node_id << std::endl; exit(-1); } } writeBaseAddress(); } /* * Modify scratchpad */ void ScratchpadDatapath::completePartition() { std::unordered_map<std::string, unsigned> comp_part_config; if (!readCompletePartitionConfig(comp_part_config)) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Mem to Reg Conv " << std::endl; std::cerr << "-------------------------------" << std::endl; for (auto it = comp_part_config.begin(); it != comp_part_config.end(); ++it) { std::string base_addr = it->first; unsigned size = it->second; registers.createRegister(base_addr, size, cycleTime); } } /* * Modify: baseAddress */ void ScratchpadDatapath::scratchpadPartition() { //read the partition config file to get the address range // <base addr, <type, part_factor> > std::unordered_map<std::string, partitionEntry> part_config; if (!readPartitionConfig(part_config)) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " ScratchPad Partition " << std::endl; std::cerr << "-------------------------------" << std::endl; std::string bn(benchName); std::unordered_map<unsigned, pair<long long int, unsigned> > address; initAddressAndSize(address); //set scratchpad for(auto it = part_config.begin(); it!= part_config.end(); ++it) { std::string base_addr = it->first; unsigned size = it->second.array_size; //num of bytes unsigned p_factor = it->second.part_factor; unsigned wordsize = it->second.wordsize; //in bytes unsigned per_size = ceil( ((float)size) / p_factor); for ( unsigned i = 0; i < p_factor ; i++) { ostringstream oss; oss << base_addr << "-" << i; scratchpad->setScratchpad(oss.str(), per_size, wordsize); } } for(unsigned node_id = 0; node_id < numTotalNodes; node_id++) { if (!is_memory_op(microop.at(node_id))) continue; if (baseAddress.find(node_id) == baseAddress.end()) continue; std::string base_label = baseAddress[node_id].first; long long int base_addr = baseAddress[node_id].second; auto part_it = part_config.find(base_label); if (part_it != part_config.end()) { std::string p_type = part_it->second.type; assert((!p_type.compare("block")) || (!p_type.compare("cyclic"))); unsigned num_of_elements = part_it->second.array_size; unsigned p_factor = part_it->second.part_factor; long long int abs_addr = address[node_id].first; unsigned data_size = address[node_id].second / 8; //in bytes unsigned rel_addr = (abs_addr - base_addr ) / data_size; if (!p_type.compare("block")) //block partition { ostringstream oss; unsigned num_of_elements_in_2 = next_power_of_two(num_of_elements); oss << base_label << "-" << (int) (rel_addr / ceil (num_of_elements_in_2 / p_factor)); baseAddress[node_id].first = oss.str(); } else // cyclic partition { ostringstream oss; oss << base_label << "-" << (rel_addr) % p_factor; baseAddress[node_id].first = oss.str(); } } } writeBaseAddress(); } bool ScratchpadDatapath::step() { return BaseDatapath::step(); } void ScratchpadDatapath::stepExecutingQueue() { auto it = executingQueue.begin(); int index = 0; while (it != executingQueue.end()) { unsigned node_id = *it; if (is_memory_op(microop.at(node_id))) { std::string node_part = baseAddress[node_id].first; if (registers.has(node_part) || scratchpad->canServicePartition(node_part)) { if (registers.has(node_part)) { if (is_load_op(microop.at(node_id))) registers.getRegister(node_part)->increment_loads(); else registers.getRegister(node_part)->increment_stores(); } else { assert(scratchpad->addressRequest(node_part)); if (is_load_op(microop.at(node_id))) scratchpad->increment_loads(node_part); else scratchpad->increment_stores(node_part); } executedNodes++; newLevel.at(node_id) = num_cycles; executingQueue.erase(it); updateChildren(node_id); it = executingQueue.begin(); std::advance(it, index); } else { ++it; ++index; } } else { executedNodes++; newLevel.at(node_id) = num_cycles; executingQueue.erase(it); updateChildren(node_id); it = executingQueue.begin(); std::advance(it, index); } } } void ScratchpadDatapath::dumpStats() { BaseDatapath::dumpStats(); BaseDatapath::writePerCycleActivity(); } double ScratchpadDatapath::getTotalMemArea() { return scratchpad->getTotalArea(); } unsigned ScratchpadDatapath::getTotalMemSize() { return scratchpad->getTotalSize(); } void ScratchpadDatapath::getMemoryBlocks(std::vector<std::string> &names) { scratchpad->getMemoryBlocks(names); } void ScratchpadDatapath::getAverageMemPower( unsigned int cycles, float *avg_power, float *avg_dynamic, float *avg_leak) { scratchpad->getAveragePower(cycles, avg_power, avg_dynamic, avg_leak); }
30.747508
83
0.622474
httsai
a2791a38b47f60706529c48fba4ae2723268d152
2,880
cpp
C++
binary_tree_right_side_view.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
binary_tree_right_side_view.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
binary_tree_right_side_view.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
// Problem: https://leetcode.com/problems/binary-tree-right-side-view/ #include <vector> #include <deque> #include "utils.h" namespace binary_tree_right_side_view { struct TreeNode { int val; TreeNode* left; TreeNode* right; }; class Solution { public: // Time: O(n), Space: O(w + h) // n - number of nodes, w - maximum number of nodes in the tree level, h - height of the tree // std::vector<int> run(TreeNode* root) { if (!root) return {}; std::vector<int> result; std::deque<const TreeNode*> nodes = {root}; while (nodes.size()) { const TreeNode* rightmost_node = nodes.back(); result.push_back(rightmost_node->val); const int level_size = nodes.size(); for (int i = 0; i < level_size; i++) { const TreeNode* node = nodes.front(); if (node->left) nodes.push_back(node->left); if (node->right) nodes.push_back(node->right); nodes.pop_front(); } } return result; } }; int main() { typedef std::vector<int> Result; ASSERT(( Solution().run(nullptr) == Result{} )); ASSERT(( Solution().run(TemporaryTree<TreeNode>(new TreeNode{1})) == Result{1} )); ASSERT(( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{2}, nullptr } )) == Result{1, 2} )); ASSERT(( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, nullptr, new TreeNode{2} } )) == Result{1, 2} )); ASSERT(( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{2}, new TreeNode{3} } )) == Result{1, 3} )); ASSERT(( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{2, new TreeNode{4}, nullptr }, new TreeNode{3, nullptr, new TreeNode{5} } } )) == Result{1, 3, 5} )); ASSERT(( Solution().run( TemporaryTree<TreeNode>( new TreeNode{1, new TreeNode{2, nullptr, new TreeNode{4, nullptr, new TreeNode{6, new TreeNode{7}, nullptr } } }, new TreeNode{3, new TreeNode{5}, nullptr} } )) == Result{1, 3, 5, 6, 7} )); return 0; } }
24.615385
97
0.434028
artureganyan
a27948b65d480bd042d677db26191b507ef9bb6b
1,308
cpp
C++
erts/emulator/asmjit/x86/x86builder.cpp
williamthome/otp
c4f24d6718ac56c431f0fccf240c5b15482792ed
[ "Apache-2.0" ]
null
null
null
erts/emulator/asmjit/x86/x86builder.cpp
williamthome/otp
c4f24d6718ac56c431f0fccf240c5b15482792ed
[ "Apache-2.0" ]
null
null
null
erts/emulator/asmjit/x86/x86builder.cpp
williamthome/otp
c4f24d6718ac56c431f0fccf240c5b15482792ed
[ "Apache-2.0" ]
2
2015-10-18T22:36:46.000Z
2022-01-26T14:01:57.000Z
// This file is part of AsmJit project <https://asmjit.com> // // See asmjit.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #include "../core/api-build_p.h" #if !defined(ASMJIT_NO_X86) && !defined(ASMJIT_NO_BUILDER) #include "../x86/x86assembler.h" #include "../x86/x86builder.h" #include "../x86/x86emithelper_p.h" ASMJIT_BEGIN_SUB_NAMESPACE(x86) // x86::Builder - Construction & Destruction // ========================================= Builder::Builder(CodeHolder* code) noexcept : BaseBuilder() { _archMask = (uint64_t(1) << uint32_t(Arch::kX86)) | (uint64_t(1) << uint32_t(Arch::kX64)) ; assignEmitterFuncs(this); if (code) code->attach(this); } Builder::~Builder() noexcept {} // x86::Builder - Events // ===================== Error Builder::onAttach(CodeHolder* code) noexcept { return Base::onAttach(code); } Error Builder::onDetach(CodeHolder* code) noexcept { return Base::onDetach(code); } // x86::Builder - Finalize // ======================= Error Builder::finalize() { ASMJIT_PROPAGATE(runPasses()); Assembler a(_code); a.addEncodingOptions(encodingOptions()); a.addDiagnosticOptions(diagnosticOptions()); return serializeTo(&a); } ASMJIT_END_SUB_NAMESPACE #endif // !ASMJIT_NO_X86 && !ASMJIT_NO_BUILDER
24.679245
67
0.659786
williamthome
a27d1fc265d6090e6acac6a08b94bd1149b9b3c0
4,760
cpp
C++
src/fixie_lib/desktop_gl_impl/texture.cpp
vonture/fixie
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
[ "MIT" ]
7
2015-01-09T22:08:17.000Z
2021-10-12T10:32:58.000Z
src/fixie_lib/desktop_gl_impl/texture.cpp
vonture/fixie
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
[ "MIT" ]
1
2015-08-19T07:51:53.000Z
2015-08-19T07:51:53.000Z
src/fixie_lib/desktop_gl_impl/texture.cpp
vonture/fixie
7fa1a6787ae26ee141a906fe39fb85c2e3cf4dfc
[ "MIT" ]
5
2015-08-20T07:10:23.000Z
2022-03-24T07:09:10.000Z
#include "fixie_lib/desktop_gl_impl/texture.hpp" #include "fixie_lib/desktop_gl_impl/framebuffer.hpp" #include "fixie_lib/debug.hpp" #include "fixie/fixie_gl_es.h" namespace fixie { namespace desktop_gl_impl { #define GL_FRAMEBUFFER 0x8D40 texture::texture(std::shared_ptr<const gl_functions> functions) : _functions(functions) { gl_call(_functions, gen_textures, 1, &_id); } texture::~texture() { gl_call_nothrow(_functions, delete_textures, 1, &_id); } GLuint texture::id() const { return _id; } void texture::set_data(const pixel_store_state& store_state, GLint level, GLenum internal_format, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels) { gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, pixel_store_i, GL_UNPACK_ALIGNMENT, store_state.unpack_alignment()); gl_call(_functions, tex_image_2d, GL_TEXTURE_2D, level, internal_format, width, height, 0, format, type, pixels); } void texture::set_sub_data(const pixel_store_state& store_state, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels) { gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, pixel_store_i, GL_UNPACK_ALIGNMENT, store_state.unpack_alignment()); gl_call(_functions, tex_sub_image_2d, GL_TEXTURE_2D, level, xoffset, yoffset, width, height, format, type, pixels); } void texture::set_compressed_data(const pixel_store_state& store_state, GLint level, GLenum internal_format, GLsizei width, GLsizei height, GLsizei image_size, const GLvoid *data) { gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, pixel_store_i, GL_UNPACK_ALIGNMENT, store_state.unpack_alignment()); gl_call(_functions, compressed_tex_image_2d, GL_TEXTURE_2D, level, internal_format, width, height, 0, image_size, data); } void texture::set_compressed_sub_data(const pixel_store_state& store_state, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei image_size, const GLvoid *data) { gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, pixel_store_i, GL_UNPACK_ALIGNMENT, store_state.unpack_alignment()); gl_call(_functions, tex_sub_image_2d, GL_TEXTURE_2D, level, xoffset, yoffset, width, height, format, image_size, data); } void texture::set_storage(GLsizei levels, GLenum internal_format, GLsizei width, GLsizei height) { gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, tex_storage_2d, GL_TEXTURE_2D, levels, internal_format, width, height); } void texture::copy_data(GLint level, GLenum internal_format, GLint x, GLint y, GLsizei width, GLsizei height, std::weak_ptr<const framebuffer_impl> source) { std::shared_ptr<const framebuffer_impl> source_locked = source.lock(); std::shared_ptr<const desktop_gl_impl::framebuffer> desktop_framebuffer = std::dynamic_pointer_cast<const desktop_gl_impl::framebuffer>(source_locked); assert(desktop_framebuffer != nullptr); gl_call(_functions, bind_framebuffer, GL_FRAMEBUFFER, desktop_framebuffer->id()); gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, copy_tex_image_2d, GL_TEXTURE_2D, level, internal_format, x, y, width, height, 0); } void texture::copy_sub_data(GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, std::weak_ptr<const framebuffer_impl> source) { std::shared_ptr<const framebuffer_impl> source_locked = source.lock(); std::shared_ptr<const desktop_gl_impl::framebuffer> desktop_framebuffer = std::dynamic_pointer_cast<const desktop_gl_impl::framebuffer>(source_locked); assert(desktop_framebuffer != nullptr); gl_call(_functions, bind_framebuffer, GL_FRAMEBUFFER, desktop_framebuffer->id()); gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, copy_tex_sub_image_2d, GL_TEXTURE_2D, level, xoffset, yoffset, x, y, width, height); } void texture::generate_mipmaps() { gl_call(_functions, bind_texture, GL_TEXTURE_2D, _id); gl_call(_functions, generate_mipmap, GL_TEXTURE_2D); } } }
51.73913
212
0.693487
vonture
a2828a2f6fe36c63fd11c455d1b6bf51c2fb1c07
1,666
cpp
C++
src/anfibio_nativo.cpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
null
null
null
src/anfibio_nativo.cpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
null
null
null
src/anfibio_nativo.cpp
fernandocunhapereira/petfera
6c1a3661df2561f53691abc548b1ce4202a3ba1e
[ "MIT" ]
1
2020-11-18T21:06:29.000Z
2020-11-18T21:06:29.000Z
#include "anfibio_nativo.hpp" /** *@brief Construtor que instancia um objeto do tipo AnfibioNativo *@param Caracteristicas inerentes aos anfibios nativos */ AnfibioNativo::AnfibioNativo(string identificacao, double preco, string descricao, double peso, tipoSexo sexo, Venenosos tipoVen, string estado, bool ameacado,string licencaIBAMA) :Anfibio(identificacao, preco, descricao, peso, sexo, tipoVen), Nativo(estado, ameacado,licencaIBAMA){ this-> tipoAnimal = anfibioNativo; } /** *@brief Destrutor da classe AnfibioNativo */ AnfibioNativo::~AnfibioNativo(){} /** *@brief Método que imprime os dados do anfibio nativo *@return atributos a serem impressos */ ostream& AnfibioNativo::print(ostream& o) const{ string strVet; if(getVeterinario()==nullptr){ strVet="Sem veterinario"; }else{ strVet=getVeterinario()->getNome(); } std::string strTra; if(getTratador()==nullptr){ strTra="Sem tratador"; }else{ strTra=getTratador()->getNome(); } string strAme=(this-> ameacado ==0)?"Não":"Sim"; string strSexo = (this-> sexo == 0) ? "Macho" : "Fêmea"; string strTipoVen = (this-> tipoVen == 0) ? "Não Venenoso" : "Venenoso"; o<<"ID = " << this-> identificacao <<" | Preço = R$ "<< fixed << setprecision(2) << this-> preco <<" | Ameaçado = "<< strAme <<" | Peso = " << this -> peso <<"Kg" <<" | Sexo = " << strSexo <<" | Descricao = " << this-> descricao <<" | Periculosidade = "<< strTipoVen <<" | Estado de origem = " << this-> estado <<" | Licença IBAMA = " << this -> licencaIBAMA <<" | Veterinario = "<<strVet <<" | Tratador = "<<strTra << endl; return o; }
32.038462
118
0.638655
fernandocunhapereira
a28a2cf03db9388114f8b44a46ee81f7adece6ff
157
hpp
C++
src/libv/serial/types/std_vector.hpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
2
2018-04-11T03:07:03.000Z
2019-03-29T15:24:12.000Z
src/libv/serial/types/std_vector.hpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
null
null
null
src/libv/serial/types/std_vector.hpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
1
2021-06-13T06:39:06.000Z
2021-06-13T06:39:06.000Z
// Project: libv.serial, File: src/libv/serial/types/std_vector.hpp, Author: Császár Mátyás [Vader] #pragma once // ext #include <cereal/types/vector.hpp>
22.428571
99
0.738854
cpplibv
a28eda70bdeb0d602dbab24654e28e6e4de0b34e
1,579
cpp
C++
graph/mst/loj/F1059/Solution.cpp
MdAman02/problem_solving
0cc1e3b8c74eca5a0ec9d02125cf5b8ee0aa7da5
[ "MIT" ]
17
2020-11-12T17:41:41.000Z
2021-10-01T13:19:42.000Z
graph/mst/loj/F1059/Solution.cpp
MdAman02/problem_solving
0cc1e3b8c74eca5a0ec9d02125cf5b8ee0aa7da5
[ "MIT" ]
15
2019-09-23T06:33:47.000Z
2020-06-04T18:55:45.000Z
graph/mst/loj/F1059/Solution.cpp
MdAman02/problem_solving
0cc1e3b8c74eca5a0ec9d02125cf5b8ee0aa7da5
[ "MIT" ]
16
2019-09-21T23:19:58.000Z
2020-06-18T07:26:39.000Z
// problem name: Air Ports // problem link: http://lightoj.com/volume_showproblem.php?problem=1059 // contest link: (?) // time: (?) // author: aman // other_tags: (?) #include<iostream> #include<vector> #include<queue> #include<cstring> using namespace std; #define mx 10010 #define f first #define s second typedef pair<int,int> pii; int visited[mx]; class compare { public: bool operator() (pii a,pii b) { return a.s > b.s; } }; //return cost of MST int prims(int node,vector<pii > (&adjList)[mx]) { int min_cost = 0; priority_queue< pii, vector<pii >, compare> pr; pr.push(make_pair(node,0) ); while(!pr.empty()) { pii tp = pr.top(); int curr = tp.f; pr.pop(); if(visited[curr] != -1) continue; min_cost += tp.s; visited[curr] = 1; for(int i=0 ; i<adjList[curr].size() ; i++) { if(visited[adjList[curr][i].f] == -1) pr.push(adjList[curr][i]); } } return min_cost; } int main() { //freopen("input.txt","r",stdin); int n,m,A; int t; cin>>t; for (int k=1 ; k<=t ; k++) { memset(visited,-1,sizeof(visited)); vector<pii > graph[mx]; int totCost=0,ports=0; cin>>n>>m>>A; for (int i=0 ; i<m ; i++) { int x,y,c; cin>>x>>y>>c; if(c<A) { //Eliminate edge >= aiport cost graph[x].push_back(make_pair(y,c)); graph[y].push_back(make_pair(x,c)); } } //Run MST on each disjoint graph for (int i=1 ; i<=n ; i++) { if(visited[i]==-1) { int res = prims(i,graph); totCost += res+A; ports++; } } cout<<"Case "<<k<<": "<<totCost<<" "<<ports<<endl; } return 0; }
16.278351
71
0.576314
MdAman02
a29123ee9f2e2887d9bcda6ae8e4caa476c9130a
2,584
cpp
C++
Backtracking-Recursion/0079-Word-Search/main.cpp
FeiZhao0531/PlayLeetCode
ed23477fd6086d5139bda3d93feeabc09b06854d
[ "MIT" ]
5
2019-05-11T18:33:32.000Z
2019-12-13T09:13:02.000Z
Backtracking-Recursion/0079-Word-Search/main.cpp
FeiZhao0531/PlayLeetCode
ed23477fd6086d5139bda3d93feeabc09b06854d
[ "MIT" ]
null
null
null
Backtracking-Recursion/0079-Word-Search/main.cpp
FeiZhao0531/PlayLeetCode
ed23477fd6086d5139bda3d93feeabc09b06854d
[ "MIT" ]
null
null
null
/// Source : https://leetcode.com/problems/word-search/description/ /// Author : Fei /// Time : Jul-01-2019 #include <iostream> #include <vector> #include <cassert> using namespace std; // Backtrack // Time Complexity: O(m*n*length(word)) // Space Complexity: O(m*n) class Solution { public: bool exist(vector<vector<char>>& board, string word) { if( board.size() == 0 || board[0].size() == 0) return false; if( word.size() == 0) return true; xUp = board.size(); yUp = board[0].size(); visited = vector< vector<bool> >( xUp, vector<bool>( yUp, false)); // false : Non-visited for( int y=0; y < yUp; ++y) for( int x=0; x < xUp; ++x) if( planeDFS( board, word, 0, x, y)) return true; return false; } private: int xUp, yUp; int nextStep[4][2] = { { 0, 1}, { 1, 0}, { -1, 0}, { 0, -1}}; vector< vector<bool> > visited; bool planeDFS( const vector< vector<char> >& board, const string& word, int strIndex, int x, int y) { if( strIndex == word.size()-1) return word[strIndex] == board[x][y]; if( word[strIndex] != board[x][y]) return false; visited[x][y] = true; for( int i=0; i<4; ++i) { int newX = x + nextStep[i][0]; int newY = y + nextStep[i][1]; if( inAera( newX, newY) && !visited[newX][newY]) if( planeDFS( board, word, strIndex+1, newX, newY)) return true; } visited[x][y] = false; return false; } bool inAera( int x, int y) { return ( x >= 0 && x < xUp) && ( y >= 0 && y < yUp); } }; int main() { char b1[3][4] = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; vector<vector<char>> board1; for( int i = 0 ; i < 3 ; i ++ ) board1.push_back(vector<char>(b1[i], b1[i] + sizeof(b1[i]) / sizeof(char))); int cases = 3; string words[3] = {"ABCCED" , "SEE" , "ABCB" }; for( int i = 0 ; i < cases ; i ++ ) if(Solution().exist(board1,words[i])) cout<<"found "<<words[i]<<endl; else cout<<"can not found "<<words[i]<<endl; // --- char b2[1][1] = {{'A'}}; vector<vector<char>> board2; for(int i = 0 ; i < 3 ; i ++) board2.push_back(vector<char>(b2[i],b2[i]+sizeof(b2[i])/sizeof(char))); if(Solution().exist(board2,"AB")) cout<<"found AB"<<endl; else cout<<"can not found AB"<<endl; return 0; }
27.2
97
0.485681
FeiZhao0531
a29425f4fed01f571ce839d1c863888917bc8b39
426
cpp
C++
Input/Source/XWindowsGamePadInput.cpp
jordanlittlefair/Foundation
ab737b933ea5bbe2be76133ed78c8e882f072fd0
[ "BSL-1.0" ]
null
null
null
Input/Source/XWindowsGamePadInput.cpp
jordanlittlefair/Foundation
ab737b933ea5bbe2be76133ed78c8e882f072fd0
[ "BSL-1.0" ]
null
null
null
Input/Source/XWindowsGamePadInput.cpp
jordanlittlefair/Foundation
ab737b933ea5bbe2be76133ed78c8e882f072fd0
[ "BSL-1.0" ]
null
null
null
#include "../Include/XWindowsGamePadInput.hpp" #include <cstring> using namespace Fnd::Input; XWindowsGamePadInput::XWindowsGamePadInput() { } bool XWindowsGamePadInput::Initialise() { return true; } GamePadInputBase::GamePadState XWindowsGamePadInput::GetNextState() { GamePadState state; memset( &state, 0, sizeof(GamePadState) ); return state; } XWindowsGamePadInput::~XWindowsGamePadInput() { }
15.777778
67
0.739437
jordanlittlefair
a294e9b9cde94552aadcee03ad3ec94e9c6c03ec
726
cpp
C++
data_structure/sparse_table.cpp
lincolncpp/competitive-programming
ee5a3762eb41825b13d3aa607f8dc3f4b0ad21f3
[ "MIT" ]
6
2020-04-08T00:25:44.000Z
2021-09-04T20:39:15.000Z
data_structure/sparse_table.cpp
lincolncpp/competitive-programming
ee5a3762eb41825b13d3aa607f8dc3f4b0ad21f3
[ "MIT" ]
2
2020-04-09T06:59:12.000Z
2020-04-09T14:56:32.000Z
data_structure/sparse_table.cpp
lincolncpp/competitive-programming
ee5a3762eb41825b13d3aa607f8dc3f4b0ad21f3
[ "MIT" ]
6
2020-04-16T03:47:06.000Z
2021-09-07T10:21:32.000Z
#include <bits/stdc++.h> using namespace std; /* Build: O(nlogn) Query: O(1) */ #define lg2(x) 31-__builtin_clz(x) const int maxn = 1e5; const int logmaxn = lg2(maxn); int st[maxn+7][logmaxn+3] = {}; void build(const vector<int>&v){ int n = (int)v.size(); for(int i = 0;i < n;i++) st[i][0] = v[i]; for(int j = 1;j <= logmaxn;j++){ for(int i = 0;i+(1<<j) <= maxn+1;i++){ st[i][j] = max(st[i][j-1], st[i+(1<<(j-1))][j-1]); } } } // Range maximum query int query(int l, int r){ int j = lg2(r-l+1); return max(st[l][j], st[r-(1<<j)+1][j]); } int main(){ vector<int>v = {10, 2, 3, 4, 5, 6}; build(v); cout << query(1, 4) << endl; return 0; }
16.5
62
0.487603
lincolncpp