hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
56b2bc669d91a122c84bea08820dd50197ea6bf0 | 921 | cpp | C++ | PAT/PAT-B/CPP/1018.锤子剪刀布.cpp | hao14293/2021-Postgraduate-408 | 70e1c40e6bcf0c5afe4a4638a7c168069d9c8319 | [
"MIT"
] | 950 | 2020-02-21T02:39:18.000Z | 2022-03-31T07:27:36.000Z | PAT/PAT-B/CPP/1018.锤子剪刀布.cpp | RestmeF/2021-Postgraduate-408 | 70e1c40e6bcf0c5afe4a4638a7c168069d9c8319 | [
"MIT"
] | 6 | 2020-04-03T13:08:47.000Z | 2022-03-07T08:54:56.000Z | PAT/PAT-B/CPP/1018.锤子剪刀布.cpp | RestmeF/2021-Postgraduate-408 | 70e1c40e6bcf0c5afe4a4638a7c168069d9c8319 | [
"MIT"
] | 131 | 2020-02-22T15:35:59.000Z | 2022-03-21T04:23:57.000Z | #include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
int jiawin = 0, yiwin = 0;
int jia[3] = {0}, yi[3] = {0};
for(int i = 0; i < n; i++ ){
char s, t;
cin >> s >> t;
if(s == 'B' && t == 'C'){
jiawin++;
jia[0]++;
}else if(s == 'B' && t == 'J'){
yiwin++;
yi[2]++;
}else if(s == 'C' && t == 'B'){
yiwin++;
yi[0]++;
}else if(s == 'C' && t == 'J'){
jiawin++;
jia[1]++;
}else if(s == 'J' && t == 'B'){
jiawin++;
jia[2]++;
}else if(s == 'J' && t == 'C'){
yiwin++;
yi[1]++;
}
}
cout << jiawin << " " << n - jiawin - yiwin << " " << yiwin << endl << yiwin << " " << n - yiwin - jiawin << " "<< jiawin << endl;
int maxjia = jia[0] >= jia[1] ? 0: 1;
maxjia = jia[maxjia] >= jia[2] ? maxjia : 2;
int maxyi = yi[0] >= yi[1] ? 0: 1;
maxyi = yi[maxyi] >= yi[2] ? maxyi : 2;
char str[4] = {"BCJ"};
cout << str[maxjia] << " " << str[maxyi];
return 0;
}
| 23.025 | 131 | 0.41911 | hao14293 |
56b4562ba33037a991b47c5762bdae6abfc75b3c | 3,988 | cpp | C++ | src/libraries/dynamicMesh/dynamicMesh/fvMeshAdder/fvMeshAdder.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/dynamicMesh/fvMeshAdder/fvMeshAdder.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/dynamicMesh/fvMeshAdder/fvMeshAdder.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2016 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "fvMesh.hpp"
#include "fvMeshAdder.hpp"
#include "faceCoupleInfo.hpp"
#include "fvMesh.hpp"
/* * * * * * * * * * * * * * * Static Member Data * * * * * * * * * * * * * */
namespace CML
{
defineTypeNameAndDebug(fvMeshAdder, 0);
}
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
//- Calculate map from new patch faces to old patch faces. -1 where
// could not map.
CML::labelList CML::fvMeshAdder::calcPatchMap
(
const label oldStart,
const label oldSize,
const labelList& oldToNew,
const polyPatch& newPatch,
const label unmappedValue
)
{
labelList newToOld(newPatch.size(), unmappedValue);
label newStart = newPatch.start();
label newSize = newPatch.size();
for (label i = 0; i < oldSize; i++)
{
label newFacei = oldToNew[oldStart+i];
if (newFacei >= newStart && newFacei < newStart+newSize)
{
newToOld[newFacei-newStart] = i;
}
}
return newToOld;
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
// Inplace add mesh1 to mesh0
CML::autoPtr<CML::mapAddedPolyMesh> CML::fvMeshAdder::add
(
fvMesh& mesh0,
const fvMesh& mesh1,
const faceCoupleInfo& coupleInfo,
const bool validBoundary
)
{
mesh0.clearOut();
// Resulting merged mesh (polyMesh only!)
autoPtr<mapAddedPolyMesh> mapPtr
(
polyMeshAdder::add
(
mesh0,
mesh1,
coupleInfo,
validBoundary
)
);
// Adjust the fvMesh part.
const polyBoundaryMesh& patches = mesh0.boundaryMesh();
fvBoundaryMesh& fvPatches = const_cast<fvBoundaryMesh&>(mesh0.boundary());
fvPatches.setSize(patches.size());
forAll(patches, patchi)
{
fvPatches.set(patchi, fvPatch::New(patches[patchi], fvPatches));
}
// Do the mapping of the stored fields
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
fvMeshAdder::MapVolFields<scalar>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapVolFields<vector>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapVolFields<sphericalTensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapVolFields<symmTensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapVolFields<tensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapSurfaceFields<scalar>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapSurfaceFields<vector>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapSurfaceFields<sphericalTensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapSurfaceFields<symmTensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapSurfaceFields<tensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapDimFields<scalar>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapDimFields<vector>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapDimFields<sphericalTensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapDimFields<symmTensor>(mapPtr, mesh0, mesh1);
fvMeshAdder::MapDimFields<tensor>(mapPtr, mesh0, mesh1);
return mapPtr;
}
// ************************************************************************* //
| 31.650794 | 79 | 0.601053 | MrAwesomeRocks |
56b62e1763a4f5e43ae82a84346cf85b52005e93 | 6,284 | cpp | C++ | Acorn/src/Acorn/gui/ImGuiLayer.cpp | IcyTv/Acorn | 3068d9fd54401b310d42ef81277aab3d0ade0a0a | [
"Apache-2.0"
] | null | null | null | Acorn/src/Acorn/gui/ImGuiLayer.cpp | IcyTv/Acorn | 3068d9fd54401b310d42ef81277aab3d0ade0a0a | [
"Apache-2.0"
] | null | null | null | Acorn/src/Acorn/gui/ImGuiLayer.cpp | IcyTv/Acorn | 3068d9fd54401b310d42ef81277aab3d0ade0a0a | [
"Apache-2.0"
] | null | null | null | #include "gui/ImGuiLayer.h"
#include "acpch.h"
#include "core/Application.h"
#include "input/KeyCodes.h"
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "Acorn/utils/FileUtils.h"
#include "renderer/RenderCommand.h"
#include "utils/fonts/IconsFontAwesome4.h"
#include <ImGuizmo.h>
// #include <implot.h>
// Temporary
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <filesystem>
#ifdef AC_PLATFORM_WINDOWS
#include <windows.h>
#else
#include <unistd.h>
#include <cstring>
#include <cerrno>
#endif
namespace Acorn
{
// Stores the ImGUI ini filepath, so it never goes out of scope
static std::string s_ImGuiINIFilePath;
/**
* @brief Get the ImGui Ini file path
*
* Thanks, https://stackoverflow.com/a/70052837
*
* @return std::filesystem::path The path to the ImGui Ini file
*/
static std::filesystem::path GetIniPath()
{
#ifdef AC_PLATFORM_WINDOWS
wchar_t path[MAX_PATH];
if (!GetModuleFileNameW(nullptr, path, MAX_PATH))
{
DWORD error = GetLastError();
AC_CORE_ASSERT(false, "Failed to get the executable path: {0}", error);
return {};
}
#else
char path[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", path, sizeof(path) - 1);
if (len < 0 || len >= MAX_PATH)
{
AC_CORE_ASSERT(false, "Could not get executable path: {}!", strerror(errno));
return {};
}
path[len] = '\0';
#endif
std::filesystem::path p(path);
p.replace_filename("imgui.ini");
return p;
}
ImGuiLayer::ImGuiLayer()
: Layer("ImGuiLayer")
{
}
ImGuiLayer::~ImGuiLayer()
{
}
void ImGuiLayer::OnAttach()
{
AC_PROFILE_FUNCTION();
IMGUI_CHECKVERSION();
ImGui::CreateContext();
// ImPlot::CreateContext();
ImGuiIO& io = ImGui::GetIO();
s_ImGuiINIFilePath = GetIniPath().string();
AC_CORE_INFO("Loading ImGui INI file: {0}", s_ImGuiINIFilePath);
io.IniFilename = s_ImGuiINIFilePath.c_str();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
// io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
// TODO bundle fonts into engine?
ImFontConfig font_config;
font_config.MergeMode = false;
io.Fonts->AddFontFromFileTTF(Acorn::Utils::File::ResolveResPath("res/fonts/Inconsolata-Bold.ttf").c_str(), 16.0f, &font_config);
ImFontConfig config;
config.MergeMode = true;
config.GlyphMinAdvanceX = 16.0f; // Use if you want to make the icon monospaced
static const ImWchar icon_ranges[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
io.Fonts->AddFontFromFileTTF(Acorn::Utils::File::ResolveResPath("res/fonts/Inconsolata-Regular.ttf").c_str(), 16.0f, &font_config);
io.Fonts->AddFontFromFileTTF(Acorn::Utils::File::ResolveResPath(FONT_ICON_FILE_NAME_FA).c_str(), 16.0f, &config, icon_ranges);
io.Fonts->Build();
io.FontDefault = io.Fonts->Fonts[1];
ImGui::StyleColorsDark();
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 5.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
SetDarkThemeColors();
Application& app = Application::Get();
GLFWwindow* window = static_cast<GLFWwindow*>(app.GetWindow().GetNativeWindow());
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 410");
}
void ImGuiLayer::OnDetach()
{
AC_PROFILE_FUNCTION();
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
// ImPlot::DestroyContext();
ImGui::DestroyContext();
}
void ImGuiLayer::Begin()
{
AC_PROFILE_FUNCTION();
const static std::string imguiGroup = "ImGui Render";
#ifdef AC_DEBUG
glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 1, (int)imguiGroup.size(), imguiGroup.c_str());
#endif
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGuizmo::BeginFrame();
}
void ImGuiLayer::End()
{
AC_PROFILE_FUNCTION();
ImGuiIO& io = ImGui::GetIO();
Application& app = Application::Get();
io.DisplaySize = ImVec2((float)app.GetWindow().GetWidth(), (float)app.GetWindow().GetHeight());
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
GLFWwindow* backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context);
}
#ifdef AC_DEBUG
glPopDebugGroup();
#endif
}
void ImGuiLayer::SetDarkThemeColors()
{
auto& colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_WindowBg] = ImVec4(0.1f, 0.105f, 0.11f, 1.0f);
// Headers
colors[ImGuiCol_Header] = ImVec4(0.2f, 0.205f, 0.21f, 1.0f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.3f, 0.305f, 0.31f, 1.0f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.1f, 0.1505f, 0.151f, 1.0f);
// Buttons
colors[ImGuiCol_Button] = ImVec4(0.2f, 0.205f, 0.21f, 1.0f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.3f, 0.305f, 0.31f, 1.0f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.15f, 0.1505f, 0.151f, 1.0f);
// Frame BG
colors[ImGuiCol_FrameBg] = ImVec4(0.2f, 0.205f, 0.21f, 1.0f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.3f, 0.305f, 0.31f, 1.0f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.1f, 0.1505f, 0.151f, 1.0f);
// Tabs
colors[ImGuiCol_Tab] = ImVec4(0.15f, 0.105f, 0.151f, 1.0f);
colors[ImGuiCol_TabHovered] = ImVec4(0.38f, 0.3805f, 0.381f, 1.0f);
colors[ImGuiCol_TabActive] = ImVec4(0.28f, 0.2805f, 0.281f, 1.0f);
colors[ImGuiCol_TabUnfocused] = ImVec4(0.15f, 0.1505f, 0.151f, 1.0f);
colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.2f, 0.205f, 0.21f, 1.0f);
// Title
colors[ImGuiCol_TitleBg] = ImVec4(0.15f, 0.1505f, 0.151f, 1.0f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.15f, 0.1505f, 0.151f, 1.0f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.15f, 0.1505f, 0.151f, 1.0f);
auto& styles = ImGui::GetStyle();
styles.WindowBorderSize = 0.0f;
styles.WindowRounding = 5.0f;
}
void ImGuiLayer::OnImGuiRender(Timestep)
{
}
void ImGuiLayer::OnEvent(Event& e)
{
if (m_BlockEvents)
{
ImGuiIO& io = ImGui::GetIO();
e.Handled |= e.IsInCategory(EventCategoryMouse) & io.WantCaptureMouse;
e.Handled |= e.IsInCategory(EventCategoryKeyboard) & io.WantCaptureKeyboard;
}
}
} | 26.854701 | 133 | 0.70958 | IcyTv |
56b72c30a89a25778718b0884eb43aa18dcb125f | 1,939 | cpp | C++ | fastjoin/FastJoinCmd.cpp | TsinghuaDatabaseGroup/Similarity-Search-and-Join | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | 14 | 2018-01-29T06:54:06.000Z | 2021-07-09T18:18:51.000Z | fastjoin/FastJoinCmd.cpp | TsinghuaDatabaseGroup/similarity | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | null | null | null | fastjoin/FastJoinCmd.cpp | TsinghuaDatabaseGroup/similarity | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | 11 | 2018-04-11T04:56:40.000Z | 2021-12-17T04:00:22.000Z | #include "FastJoin.h"
#include "TokenSigScheme/TokenSigSchemeFactory.h"
#include "TokenSigScheme/TokenSigScheme.h"
#include "TokenSetSigScheme/JaccardTokenSetSigScheme.h"
#include "TokenSetSigScheme/DiceTokenSetSigScheme.h"
#include "TokenSetSigScheme/CosinTokenSetSigScheme.h"
#include "Tokenizer/StandardTokenizer.h"
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void usage()
{
cerr << "Usage:" << "./FastJoin [FJACCARD | FCOSINE | FDICE] delta tau file1 [file2]" << endl << endl;
cerr << "Example: ./FastJoin FJaccard 0.85 0.8 querylog.txt" << endl;
cerr << "Output: All pairs <s1, s2> in \"querylog.txt\" s.t. FJACCARD_{0.85} (s1, s2) >= 0.8" << endl;
}
int main(int argc, char* argv[])
{
if (argc != 5 && argc != 6)
{
usage();
exit(0);
}
string simFunc(argv[1]);
toLowerString(simFunc);
TokenSetSigScheme<int>* setScheme;
TokenSigScheme* partitionNEDScheme = TokenSigSchemeFactory::getTokenSigScheme(PartitionNED);
if (simFunc == "fjaccard") setScheme = new JaccardTokenSetSigScheme<int>(partitionNEDScheme);
else if (simFunc == "fcosine") setScheme = new CosinTokenSetSigScheme<int>(partitionNEDScheme);
else if (simFunc == "fdice") setScheme = new DiceTokenSetSigScheme<int>(partitionNEDScheme);
else { usage(); exit(0); }
double delta = atof(argv[2]);
double tau = atof(argv[3]);
char* filename1 = argv[4];
char* filename2;
vector<string> stringSet1, stringSet2;
Tokenizer* tokenizer = new StandardTokenizer();
FastJoin<int> fastjoinInt(setScheme, tokenizer);
vector<Result> results;
if (argc == 5)
{
loadStringSet(filename1, stringSet1);
fastjoinInt.join(stringSet1, delta, tau, results);
}
if (argc == 6)
{
filename2 = argv[5];
loadStringSet(filename1, stringSet1);
loadStringSet(filename2, stringSet2);
fastjoinInt.join(stringSet1, stringSet2, delta, tau, results);
}
delete partitionNEDScheme;
delete setScheme;
delete tokenizer;
return 0;
}
| 31.786885 | 103 | 0.726663 | TsinghuaDatabaseGroup |
56b952fa74e4edebe7258994257dcacf14ab957d | 8,494 | cc | C++ | RecoTracker/DeDx/plugins/HLTDeDxFilter.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoTracker/DeDx/plugins/HLTDeDxFilter.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoTracker/DeDx/plugins/HLTDeDxFilter.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /** \class HLTDeDxFilter
*
*
* \author Claude Nuttens
*
*/
#include "RecoTracker/DeDx/plugins/HLTDeDxFilter.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/HLTReco/interface/TriggerFilterObjectWithRefs.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
//#include "DataFormats/JetReco/interface/CaloJetCollection.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "DataFormats/TrackReco/interface/DeDxData.h"
//#include "DataFormats/Math/interface/deltaPhi.h"
#include "DataFormats/Math/interface/deltaR.h"
#include "DataFormats/Common/interface/ValueMap.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include <vector>
#include "DataFormats/RecoCandidate/interface/RecoChargedCandidate.h"
#include "DataFormats/RecoCandidate/interface/RecoChargedCandidateFwd.h"
//
// constructors and destructor
//
HLTDeDxFilter::HLTDeDxFilter(const edm::ParameterSet& iConfig) : HLTFilter(iConfig)
{
minDEDx_ = iConfig.getParameter<double> ("minDEDx");
minPT_ = iConfig.getParameter<double> ("minPT");
minNOM_ = iConfig.getParameter<double> ("minNOM");
maxETA_ = iConfig.getParameter<double> ("maxETA");
minNumValidHits_ = iConfig.getParameter<double> ("minNumValidHits");
maxNHitMissIn_ = iConfig.getParameter<double> ("maxNHitMissIn");
maxNHitMissMid_ = iConfig.getParameter<double> ("maxNHitMissMid");
maxRelTrkIsoDeltaRp3_ = iConfig.getParameter<double> ("maxRelTrkIsoDeltaRp3");
relTrkIsoDeltaRSize_ = iConfig.getParameter<double> ("relTrkIsoDeltaRSize");
maxAssocCaloE_ = iConfig.getParameter<double> ("maxAssocCaloE");
maxAssocCaloEDeltaRSize_ = iConfig.getParameter<double> ("maxAssocCaloEDeltaRSize");
inputTracksTag_ = iConfig.getParameter< edm::InputTag > ("inputTracksTag");
inputdedxTag_ = iConfig.getParameter< edm::InputTag > ("inputDeDxTag");
caloTowersTag_ = iConfig.getParameter<edm::InputTag>("caloTowersTag");
if(maxAssocCaloE_ >= 0) caloTowersToken_ = consumes<CaloTowerCollection> (iConfig.getParameter<edm::InputTag>("caloTowersTag"));
inputTracksToken_ = consumes<reco::TrackCollection>(iConfig.getParameter< edm::InputTag > ("inputTracksTag"));
inputdedxToken_ = consumes<edm::ValueMap<reco::DeDxData> >(iConfig.getParameter< edm::InputTag > ("inputDeDxTag"));
thisModuleTag_ = edm::InputTag(iConfig.getParameter<std::string>("@module_label"));
//register your products
produces<reco::RecoChargedCandidateCollection>();
}
HLTDeDxFilter::~HLTDeDxFilter(){}
void HLTDeDxFilter::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.add<bool>("saveTags",false);
desc.add<double>("minDEDx",0.0);
desc.add<double>("minPT",0.0);
desc.add<double>("minNOM",0.0);
desc.add<double>("maxETA",5.5);
desc.add<double>("minNumValidHits",0);
desc.add<double>("maxNHitMissIn",99);
desc.add<double>("maxNHitMissMid",99);
desc.add<double>("maxRelTrkIsoDeltaRp3", -1);
desc.add<double>("relTrkIsoDeltaRSize", 0.3);
desc.add<double>("maxAssocCaloE", -99);
desc.add<double>("maxAssocCaloEDeltaRSize", 0.5);
desc.add<edm::InputTag>("caloTowersTag",edm::InputTag("hltTowerMakerForAll"));
desc.add<edm::InputTag>("inputTracksTag",edm::InputTag("hltL3Mouns"));
desc.add<edm::InputTag>("inputDeDxTag",edm::InputTag("HLTdedxHarm2"));
descriptions.add("hltDeDxFilter",desc);
}
// ------------ method called to produce the data ------------
bool
HLTDeDxFilter::hltFilter(edm::Event& iEvent, const edm::EventSetup& iSetup, trigger::TriggerFilterObjectWithRefs & filterproduct) const
{
using namespace std;
using namespace edm;
using namespace reco;
using namespace trigger;
auto chargedCandidates = std::make_unique<std::vector<RecoChargedCandidate>>();
ModuleDescription moduleDesc_;
if (saveTags()){
filterproduct.addCollectionTag(thisModuleTag_);
filterproduct.addCollectionTag(inputTracksTag_);
filterproduct.addCollectionTag(inputdedxTag_);
}
edm::Handle<reco::TrackCollection> trackCollectionHandle;
iEvent.getByToken(inputTracksToken_,trackCollectionHandle);
const reco::TrackCollection &trackCollection = *trackCollectionHandle.product();
edm::Handle<edm::ValueMap<reco::DeDxData> > dEdxTrackHandle;
iEvent.getByToken(inputdedxToken_, dEdxTrackHandle);
const edm::ValueMap<reco::DeDxData> &dEdxTrack = *dEdxTrackHandle.product();
edm::Handle<CaloTowerCollection> caloTowersHandle;
if(maxAssocCaloE_ >= 0) iEvent.getByToken(caloTowersToken_, caloTowersHandle);
bool accept=false;
int NTracks = 0;
//fill local arrays for eta, phi, and pt
float eta[trackCollection.size()], phi[trackCollection.size()], pt[trackCollection.size()];
for(unsigned int i=0; i<trackCollection.size(); i++){
eta[i] = trackCollection[i].eta();
phi[i] = trackCollection[i].phi();
pt[i] = trackCollection[i].pt();
}
for(unsigned int i=0; i<trackCollection.size(); i++){
reco::TrackRef track = reco::TrackRef( trackCollectionHandle, i );
if(pt[i]>minPT_ && fabs(eta[i])<maxETA_ && dEdxTrack[track].numberOfMeasurements()>minNOM_ && dEdxTrack[track].dEdx()>minDEDx_){
NTracks++;
if(track->numberOfValidHits() < minNumValidHits_) continue;
if(track->hitPattern().trackerLayersWithoutMeasurement( reco::HitPattern::MISSING_INNER_HITS) > maxNHitMissIn_) continue;
if(track->hitPattern().trackerLayersWithoutMeasurement( reco::HitPattern::TRACK_HITS) > maxNHitMissMid_) continue;
if (saveTags()){
Particle::Charge q = track->charge();
//SAVE DEDX INFORMATION AS IF IT WAS THE MASS OF THE PARTICLE
Particle::LorentzVector p4(track->px(), track->py(), track->pz(), sqrt(pow(track->p(),2) + pow(dEdxTrack[track].dEdx(),2)));
Particle::Point vtx(track->vx(),track->vy(), track->vz());
//SAVE NOH, NOM, NOS INFORMATION AS IF IT WAS THE PDGID OF THE PARTICLE
int Hits = ((dEdxTrack[track].numberOfSaturatedMeasurements()&0xFF)<<16) | ((dEdxTrack[track].numberOfMeasurements()&0xFF)<<8) | (track->found()&0xFF);
RecoChargedCandidate cand(q, p4, vtx, Hits, 0);
cand.setTrack(track);
chargedCandidates->push_back(cand);
}
//calculate relative trk isolation only if parameter maxRelTrkIsoDeltaRp3 is greater than 0
if(maxRelTrkIsoDeltaRp3_ >= 0){
auto ptCone = trackCollection[i].pt();
for(unsigned int j=0; j<trackCollection.size(); j++){
if (i==j) continue; // do not compare track to itself
auto trkDeltaR2 = deltaR2(eta[i], phi[i], eta[j], phi[j]);
if (trkDeltaR2 < relTrkIsoDeltaRSize_ * relTrkIsoDeltaRSize_){
ptCone+=pt[j];
}
}
double relTrkIso = (ptCone - pt[i])/(pt[i]);
if (relTrkIso > maxRelTrkIsoDeltaRp3_) continue;
}
//calculate the calorimeter energy associated with the track if maxAssocCaloE_ >= 0
if(maxAssocCaloE_ >= 0){
//Access info about Calo Towers
double caloEMDeltaRp5 = 0;
double caloHadDeltaRp5 = 0;
const CaloTowerCollection &caloTower = *caloTowersHandle.product();
for (CaloTowerCollection::const_iterator j=caloTower.begin(); j!=caloTower.end(); j++) {
auto caloDeltaR2 = deltaR2(eta[i], phi[i], j->eta(), j->phi());
double Eem = j->emEnergy();
double Ehad = j->hadEnergy();
if (caloDeltaR2 < (maxAssocCaloEDeltaRSize_ * maxAssocCaloEDeltaRSize_) ) {
caloEMDeltaRp5 += Eem;
caloHadDeltaRp5 += Ehad;
}
}
if (caloEMDeltaRp5 + caloHadDeltaRp5 > maxAssocCaloE_) continue;
}
accept=true;
}
}
// put filter object into the Event
if(saveTags()){
edm::OrphanHandle<RecoChargedCandidateCollection> chargedCandidatesHandle = iEvent.put(std::move(chargedCandidates));
for(int i=0; i<NTracks; i++){
filterproduct.addObject(TriggerMuon,RecoChargedCandidateRef(chargedCandidatesHandle,i));
}
}
return accept;
}
//define this as a plug-in
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(HLTDeDxFilter);
| 43.116751 | 162 | 0.707911 | nistefan |
56bccc252675fd7781e195c0e5ae15833837e4f8 | 189 | hpp | C++ | lib/src/backend/cuda/deviceHostBuffer.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 182 | 2019-04-19T12:38:30.000Z | 2022-03-20T16:48:20.000Z | lib/src/backend/cuda/deviceHostBuffer.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 107 | 2019-04-23T10:49:35.000Z | 2022-03-02T18:12:28.000Z | lib/src/backend/cuda/deviceHostBuffer.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 59 | 2019-06-04T11:27:25.000Z | 2022-03-17T23:49:49.000Z | // Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#pragma once
#include "gpu/hostBuffer.hpp"
namespace VideoStitch {
namespace GPU {}
} // namespace VideoStitch
| 17.181818 | 42 | 0.73545 | tlalexander |
56c1b0a833b492e6f545340d6fab31648eb920b3 | 1,649 | cpp | C++ | cpp/segment_trees_2017/segtree.cpp | petuhovskiy/Templates-CP | 7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e | [
"MIT"
] | 8 | 2016-06-05T19:19:27.000Z | 2019-05-14T10:33:37.000Z | cpp/segment_trees_2017/segtree.cpp | petuhovskiy/Templates-CP | 7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e | [
"MIT"
] | 2 | 2017-02-21T12:38:27.000Z | 2018-01-28T20:05:00.000Z | cpp/segment_trees_2017/segtree.cpp | petuhovskiy/Templates-CP | 7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e | [
"MIT"
] | 6 | 2015-12-26T21:12:17.000Z | 2022-03-26T21:40:17.000Z | template<typename T, typename U>
struct segtree {
int n;
int h;
std::vector<T> t;
std::vector<U> u;
template<typename U2>
void apply(int x, U2 upd) {
t[x].apply(upd);
if (x < n) u[x].apply(upd);
}
void push(int x) {
for (int i = h; i > 0; i--) {
int y = x >> i;
if (!u[y].empty()) {
apply(y << 1, u[y]);
apply(y << 1 | 1, u[y]);
u[y].clear();
}
}
}
void recalc(int x) {
while ((x >>= 1) > 0) {
t[x] = t[x << 1] + t[x << 1 | 1];
t[x].apply(u[x]);
}
}
template<typename U2>
void update(int l, int r, U2 upd) {
l += n; r += n;
int l0 = l, r0 = r - 1;
push(l0); push(r0);
for (; l < r; l >>= 1, r >>= 1) {
if (l & 1) apply(l++, upd);
if (r & 1) apply(--r, upd);
}
recalc(l0); recalc(r0);
}
T query(int l, int r) {
l += n; r += n;
push(l); push(r - 1);
T al, ar;
for (; l < r; l >>= 1, r >>= 1) {
if (l & 1) al = al + t[l++];
if (r & 1) ar = t[--r] + ar;
}
return al + ar;
}
void rebuildLayers() {
for (int i = n - 1; i > 0; i--) {
t[i] = t[i << 1] + t[i << 1 | 1];
}
}
segtree(int n) : n(n), h(32 - __builtin_clz(n)), t(n << 1), u(n) {}
segtree(std::vector<T> v) : segtree(v.size()) {
std::copy(v.begin(), v.end(), t.begin() + n);
rebuildLayers();
}
segtree(int n, T def) : segtree(std::vector<T>(n, def)) {}
};
| 23.557143 | 71 | 0.363857 | petuhovskiy |
56c7bc9c5e57bde17ed2ebe4aee5336406aa3e5c | 142 | cpp | C++ | contest/yukicoder/159.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/yukicoder/159.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/yukicoder/159.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "template.hpp"
int main() {
setBoolName("YES", "NO");
double p(in), q(in);
cout << ((1 - p) * q < p * (1 - q) * q) << endl;
}
| 17.75 | 50 | 0.478873 | not522 |
56cabcde658758a8006e3c4a5288675ffed5efc0 | 2,060 | cpp | C++ | tests/3rdparty/testngpp/tests/3rdparty/mockcpp/src/DecoratedConstraint.cpp | chencang1980/mockcpp | 45660e7bcf0a6cf8edce3c6a736e4b168acc016e | [
"Apache-2.0"
] | 30 | 2015-04-16T02:42:36.000Z | 2022-03-19T02:53:43.000Z | tests/3rdparty/testngpp/tests/3rdparty/mockcpp/src/DecoratedConstraint.cpp | chencang1980/mockcpp | 45660e7bcf0a6cf8edce3c6a736e4b168acc016e | [
"Apache-2.0"
] | 21 | 2021-03-17T06:41:56.000Z | 2022-02-01T12:27:28.000Z | tests/3rdparty/testngpp/tests/3rdparty/mockcpp/src/DecoratedConstraint.cpp | chencang1980/mockcpp | 45660e7bcf0a6cf8edce3c6a736e4b168acc016e | [
"Apache-2.0"
] | 23 | 2015-04-16T02:44:30.000Z | 2021-12-21T09:50:24.000Z | /***
mockcpp is a C/C++ mock framework.
Copyright [2008] [Darwin Yuan <darwin.yuan@gmail.com>]
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 <mockcpp/OutputStringStream.h>
#include <mockcpp/DecoratedConstraint.h>
MOCKCPP_NS_START
/////////////////////////////////////////////////////////////////////
DecoratedConstraint::DecoratedConstraint(Constraint* constraint)
: decoratedConstraint(constraint)
{}
/////////////////////////////////////////////////////////////////////
DecoratedConstraint::~DecoratedConstraint()
{
delete decoratedConstraint;
}
/////////////////////////////////////////////////////////////////////
bool DecoratedConstraint::eval(const RefAny& val) const
{
if (hasDecoratedConstraint() && !decoratedConstraint->eval(val))
{
return false;
}
return evalSelf(val);
}
/////////////////////////////////////////////////////////////////////
std::string DecoratedConstraint::getDecoratedConstraintString() const
{
return hasDecoratedConstraint() ?
std::string(", ") + decoratedConstraint->toString() : "";
}
/////////////////////////////////////////////////////////////////////
bool DecoratedConstraint::hasDecoratedConstraint() const
{
return decoratedConstraint != 0;
}
/////////////////////////////////////////////////////////////////////
std::string DecoratedConstraint::toString() const
{
oss_t oss;
oss << getName() << "(" << getTypeAndValueString()
<< getDecoratedConstraintString() << ")";
return oss.str();
}
MOCKCPP_NS_END
| 28.219178 | 75 | 0.569903 | chencang1980 |
08cadafc7c226980ddb194838ebce4d1b761edbc | 39,388 | cpp | C++ | blast/src/objmgr/seq_loc_mapper.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objmgr/seq_loc_mapper.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objmgr/seq_loc_mapper.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* $Id: seq_loc_mapper.cpp 591839 2019-08-21 15:03:00Z grichenk $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksey Grichenko
*
* File Description:
* Seq-loc mapper
*
*/
#include <ncbi_pch.hpp>
#include <objmgr/seq_loc_mapper.hpp>
#include <objmgr/scope.hpp>
#include <objmgr/object_manager.hpp>
#include <objmgr/objmgr_exception.hpp>
#include <objmgr/seq_map.hpp>
#include <objmgr/seq_map_ci.hpp>
#include <objmgr/impl/synonyms.hpp>
#include <objmgr/impl/seq_align_mapper.hpp>
#include <objmgr/impl/seq_loc_cvt.hpp>
#include <objmgr/gc_assembly_parser.hpp>
#include <objects/seqloc/Seq_loc.hpp>
#include <objects/seqfeat/Seq_feat.hpp>
#include <objects/seqfeat/Cdregion.hpp>
#include <objects/seqloc/Seq_loc_equiv.hpp>
#include <objects/seqloc/Seq_bond.hpp>
#include <objects/seqalign/seqalign__.hpp>
#include <objects/genomecoll/genome_collection__.hpp>
#include <objects/seq/Delta_ext.hpp>
#include <objects/seq/Delta_seq.hpp>
#include <objects/seq/Seq_literal.hpp>
#include <objects/seq/Seq_ext.hpp>
#include <objects/seq/Seq_gap.hpp>
#include <algorithm>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
/////////////////////////////////////////////////////////////////////
//
// CScope_Mapper_Sequence_Info
//
// Sequence type/length/synonyms provider using CScope to fetch
// the information.
class CScope_Mapper_Sequence_Info : public IMapper_Sequence_Info
{
public:
CScope_Mapper_Sequence_Info(CScope* scope);
virtual TSeqType GetSequenceType(const CSeq_id_Handle& idh);
virtual TSeqPos GetSequenceLength(const CSeq_id_Handle& idh);
virtual void CollectSynonyms(const CSeq_id_Handle& id,
TSynonyms& synonyms);
private:
CHeapScope m_Scope;
};
CScope_Mapper_Sequence_Info::CScope_Mapper_Sequence_Info(CScope* scope)
: m_Scope(scope)
{
}
void CScope_Mapper_Sequence_Info::
CollectSynonyms(const CSeq_id_Handle& id,
TSynonyms& synonyms)
{
if ( m_Scope.IsNull() ) {
synonyms.insert(id);
}
else {
CConstRef<CSynonymsSet> syns =
m_Scope.GetScope().GetSynonyms(id);
ITERATE(CSynonymsSet, syn_it, *syns) {
synonyms.insert(CSynonymsSet::GetSeq_id_Handle(syn_it));
}
}
}
CScope_Mapper_Sequence_Info::TSeqType
CScope_Mapper_Sequence_Info::GetSequenceType(const CSeq_id_Handle& idh)
{
if ( m_Scope.IsNull() ) {
return CSeq_loc_Mapper_Base::eSeq_unknown;
}
switch ( m_Scope.GetScope().GetSequenceType(idh) ) {
case CSeq_inst::eMol_dna:
case CSeq_inst::eMol_rna:
case CSeq_inst::eMol_na:
return CSeq_loc_Mapper_Base::eSeq_nuc;
case CSeq_inst::eMol_aa:
return CSeq_loc_Mapper_Base::eSeq_prot;
default:
return CSeq_loc_Mapper_Base::eSeq_unknown;
}
}
TSeqPos CScope_Mapper_Sequence_Info::GetSequenceLength(const CSeq_id_Handle& idh)
{
CBioseq_Handle h;
if ( m_Scope.IsNull() ) {
return kInvalidSeqPos;
}
h = m_Scope.GetScope().GetBioseqHandle(idh);
return h ? h.GetBioseqLength() : kInvalidSeqPos;
}
/////////////////////////////////////////////////////////////////////
//
// CSeq_loc_Mapper
//
/////////////////////////////////////////////////////////////////////
//
// Initialization of the mapper
//
inline
ENa_strand s_IndexToStrand(size_t idx)
{
_ASSERT(idx != 0);
return ENa_strand(idx - 1);
}
#define STRAND_TO_INDEX(is_set, strand) \
((is_set) ? size_t((strand) + 1) : 0)
#define INDEX_TO_STRAND(idx) \
s_IndexToStrand(idx)
CSeq_loc_Mapper_Options& SetOptionsScope(CSeq_loc_Mapper_Options& options, CScope* scope)
{
if (!options.GetMapperSequenceInfo()) {
options.SetMapperSequenceInfo(new CScope_Mapper_Sequence_Info(scope));
}
return options;
}
CSeq_loc_Mapper::CSeq_loc_Mapper(CMappingRanges* mapping_ranges,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(mapping_ranges, SetOptionsScope(options, scope)),
m_Scope(scope)
{
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CSeq_feat& map_feat,
EFeatMapDirection dir,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeFeat(map_feat, dir);
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CSeq_loc& source,
const CSeq_loc& target,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeLocs(source, target);
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CSeq_align& map_align,
const CSeq_id& to_id,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeAlign(map_align, to_id);
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CSeq_align& map_align,
size_t to_row,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeAlign(map_align, to_row);
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CSeq_id& from_id,
const CSeq_id& to_id,
const CSeq_align& map_align,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeAlign(map_align, to_id, &from_id);
}
CSeq_loc_Mapper::CSeq_loc_Mapper(size_t from_row,
size_t to_row,
const CSeq_align& map_align,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeAlign(map_align, to_row, from_row);
}
CSeq_loc_Mapper::CSeq_loc_Mapper(CBioseq_Handle target_seq,
ESeqMapDirection direction,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, &target_seq.GetScope())),
m_Scope(&target_seq.GetScope())
{
CConstRef<CSeq_id> top_level_id = target_seq.GetSeqId();
if ( !top_level_id ) {
// Bioseq handle has no id, try to get one.
CConstRef<CSynonymsSet> syns = target_seq.GetSynonyms();
if ( !syns->empty() ) {
top_level_id = syns->GetSeq_id_Handle(syns->begin()).GetSeqId();
}
}
x_InitializeSeqMap(target_seq.GetSeqMap(),
top_level_id.GetPointerOrNull(),
direction);
if (direction == eSeqMap_Up) {
// Ignore seq-map destination ranges, map whole sequence to itself,
// use unknown strand only.
m_DstRanges.resize(1);
m_DstRanges[0].clear();
m_DstRanges[0][CSeq_id_Handle::GetHandle(*top_level_id)]
.push_back(TRange::GetWhole());
}
x_PreserveDestinationLocs();
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CSeqMap& seq_map,
ESeqMapDirection direction,
const CSeq_id* top_level_id,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeSeqMap(seq_map, top_level_id, direction);
x_PreserveDestinationLocs();
}
CSeq_loc_Mapper::CSeq_loc_Mapper(CBioseq_Handle target_seq,
ESeqMapDirection direction,
SSeqMapSelector selector,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, &target_seq.GetScope())),
m_Scope(&target_seq.GetScope())
{
CConstRef<CSeq_id> top_id = target_seq.GetSeqId();
if ( !top_id ) {
// Bioseq handle has no id, try to get one.
CConstRef<CSynonymsSet> syns = target_seq.GetSynonyms();
if ( !syns->empty() ) {
top_id = syns->GetSeq_id_Handle(syns->begin()).GetSeqId();
}
}
selector.SetLinkUsedTSE(target_seq.GetTSE_Handle());
x_InitializeSeqMap(target_seq.GetSeqMap(), selector, top_id, direction);
if (direction == eSeqMap_Up) {
// Ignore seq-map destination ranges, map whole sequence to itself,
// use unknown strand only.
m_DstRanges.resize(1);
m_DstRanges[0].clear();
m_DstRanges[0][CSeq_id_Handle::GetHandle(*top_id)]
.push_back(TRange::GetWhole());
}
x_PreserveDestinationLocs();
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CSeqMap& seq_map,
ESeqMapDirection direction,
SSeqMapSelector selector,
const CSeq_id* top_level_id,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
x_InitializeSeqMap(seq_map,
selector,
top_level_id,
direction);
x_PreserveDestinationLocs();
}
CSeq_loc_Mapper::CSeq_loc_Mapper(size_t depth,
const CBioseq_Handle& top_level_seq,
ESeqMapDirection direction,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, &top_level_seq.GetScope())),
m_Scope(&top_level_seq.GetScope())
{
if (depth > 0) {
depth--;
x_InitializeSeqMap(top_level_seq.GetSeqMap(),
depth,
top_level_seq.GetSeqId().GetPointer(),
direction);
}
else if (direction == eSeqMap_Up) {
// Synonyms conversion
CConstRef<CSeq_id> top_level_id = top_level_seq.GetSeqId();
m_DstRanges.resize(1);
m_DstRanges[0][CSeq_id_Handle::GetHandle(*top_level_id)]
.push_back(TRange::GetWhole());
}
x_PreserveDestinationLocs();
}
CSeq_loc_Mapper::CSeq_loc_Mapper(size_t depth,
const CSeqMap& top_level_seq,
ESeqMapDirection direction,
const CSeq_id* top_level_id,
CScope* scope,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
if (depth > 0) {
depth--;
x_InitializeSeqMap(top_level_seq, depth, top_level_id, direction);
}
else if (direction == eSeqMap_Up) {
// Synonyms conversion
m_DstRanges.resize(1);
m_DstRanges[0][CSeq_id_Handle::GetHandle(*top_level_id)]
.push_back(TRange::GetWhole());
}
x_PreserveDestinationLocs();
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CGC_Assembly& gc_assembly,
EGCAssemblyAlias to_alias,
CScope* scope,
EScopeFlag scope_flag)
: CSeq_loc_Mapper_Base(CSeq_loc_Mapper_Options(new CScope_Mapper_Sequence_Info(scope))),
m_Scope(scope)
{
// While parsing GC-Assembly the mapper will need to add virtual
// bioseqs to the scope. To keep the original scope clean of them,
// create a new scope and add the original one as a child.
if (scope_flag == eCopyScope) {
m_Scope = CHeapScope(new CScope(*CObjectManager::GetInstance()));
if ( scope ) {
m_Scope.GetScope().AddScope(*scope);
}
m_MapOptions.SetMapperSequenceInfo(new CScope_Mapper_Sequence_Info(m_Scope));
}
x_InitGCAssembly(gc_assembly, to_alias);
}
CSeq_loc_Mapper::CSeq_loc_Mapper(const CGC_Assembly& gc_assembly,
ESeqMapDirection direction,
SSeqMapSelector selector,
CScope* scope,
EScopeFlag scope_flag,
CSeq_loc_Mapper_Options options)
: CSeq_loc_Mapper_Base(SetOptionsScope(options, scope)),
m_Scope(scope)
{
// While parsing GC-Assembly the mapper will need to add virtual
// bioseqs to the scope. To keep the original scope clean of them,
// create a new scope and add the original one as a child.
if (scope_flag == eCopyScope) {
m_Scope = CHeapScope(new CScope(*CObjectManager::GetInstance()));
if ( scope ) {
m_Scope.GetScope().AddScope(*scope);
}
m_MapOptions.SetMapperSequenceInfo(new CScope_Mapper_Sequence_Info(m_Scope));
}
CGC_Assembly_Parser parser(gc_assembly);
CRef<CSeq_entry> entry = parser.GetTSE();
m_Scope.GetScope().AddTopLevelSeqEntry(*entry);
const CGC_Assembly_Parser::TSeqIds& ids = parser.GetTopLevelSequences();
ITERATE(CGC_Assembly_Parser::TSeqIds, id, ids) {
CBioseq_Handle h = m_Scope.GetScope().GetBioseqHandle(*id);
if ( !h ) continue;
x_InitializeSeqMap(h.GetSeqMap(), selector, id->GetSeqId(), direction);
if (direction == eSeqMap_Up) {
// Ignore seq-map destination ranges, map whole sequence to itself,
// use unknown strand only.
m_DstRanges.resize(1);
m_DstRanges[0].clear();
m_DstRanges[0][*id].push_back(TRange::GetWhole());
}
x_PreserveDestinationLocs();
}
}
CSeq_loc_Mapper::~CSeq_loc_Mapper(void)
{
return;
}
void CSeq_loc_Mapper::x_InitializeSeqMap(const CSeqMap& seq_map,
const CSeq_id* top_id,
ESeqMapDirection direction)
{
x_InitializeSeqMap(seq_map, size_t(-1), top_id, direction);
}
void CSeq_loc_Mapper::x_InitializeSeqMap(const CSeqMap& seq_map,
size_t depth,
const CSeq_id* top_id,
ESeqMapDirection direction)
{
x_InitializeSeqMap(seq_map,
SSeqMapSelector(0, depth),
top_id,
direction);
}
void CSeq_loc_Mapper::x_InitializeSeqMap(const CSeqMap& seq_map,
SSeqMapSelector selector,
const CSeq_id* top_id,
ESeqMapDirection direction)
{
selector.SetFlags(CSeqMap::fFindRef | CSeqMap::fIgnoreUnresolved)
.SetLinkUsedTSE();
x_InitializeSeqMap(CSeqMap_CI(ConstRef(&seq_map),
m_Scope.GetScopeOrNull(), selector),
top_id,
direction);
}
void CSeq_loc_Mapper::x_InitializeSeqMap(CSeqMap_CI seg_it,
const CSeq_id* top_id,
ESeqMapDirection direction)
{
if (m_MapOptions.GetMapSingleLevel()) {
x_InitializeSeqMapSingleLevel(seg_it, top_id, direction);
}
else if (direction == eSeqMap_Up) {
x_InitializeSeqMapUp(seg_it, top_id);
}
else {
x_InitializeSeqMapDown(seg_it, top_id);
}
}
void CSeq_loc_Mapper::x_InitializeSeqMapUp(CSeqMap_CI seg_it,
const CSeq_id* top_id)
{
TSeqPos src_from, src_len, dst_from, dst_len;
ENa_strand dst_strand = eNa_strand_unknown;
// Mapping up - for each iterator create mapping to the top level.
// If top_id is set, top level positions are the iterator's positions.
// Otherwise top-level ids and positions must be taked from the
// iterators with depth == 1.
TSeqPos top_ref_start = 0;
TSeqPos top_start = 0;
CConstRef<CSeq_id> dst_id(top_id);
_ASSERT(seg_it.GetDepth() == 1);
while ( seg_it ) {
ENa_strand src_strand = seg_it.GetRefMinusStrand() ? eNa_strand_minus : eNa_strand_plus;
src_from = seg_it.GetRefPosition();
src_len = seg_it.GetLength();
dst_len = src_len;
if (top_id) {
dst_from = seg_it.GetPosition();
x_NextMappingRange(
*seg_it.GetRefSeqid().GetSeqId(),
src_from, src_len, src_strand,
*top_id,
dst_from, dst_len, dst_strand);
}
else /* !top_id */ {
if (seg_it.GetDepth() == 1) {
// Depth==1 - top level sequences (destination).
dst_id.Reset(seg_it.GetRefSeqid().GetSeqId());
top_ref_start = seg_it.GetRefPosition();
top_start = seg_it.GetPosition();
dst_strand = seg_it.GetRefMinusStrand() ? eNa_strand_minus : eNa_strand_plus;
}
else {
_ASSERT(seg_it.GetPosition() >= top_start);
TSeqPos shift = seg_it.GetPosition() - top_start;
dst_from = top_ref_start + shift;
x_NextMappingRange(
*seg_it.GetRefSeqid().GetSeqId(),
src_from, src_len, src_strand,
*dst_id,
dst_from, dst_len, dst_strand);
}
}
++seg_it;
}
}
void CSeq_loc_Mapper::x_InitializeSeqMapDown(CSeqMap_CI seg_it,
const CSeq_id* top_id)
{
TSeqPos src_from, src_len, dst_from, dst_len;
ENa_strand dst_strand = eNa_strand_unknown;
// eSeqMap_Down
// Collect all non-leaf references, create mapping from each non-leaf
// to the bottom level.
list<CSeqMap_CI> refs;
refs.push_back(seg_it);
while ( seg_it ) {
++seg_it;
// While depth increases push all iterators to the stack.
if ( seg_it ) {
if (refs.empty() || refs.back().GetDepth() < seg_it.GetDepth()) {
refs.push_back(seg_it);
continue;
}
}
// End of seq-map or the last iterator was a leaf - create mappings.
if ( !refs.empty() ) {
CSeqMap_CI leaf = refs.back();
// Exclude self-mapping of the leaf reference.
refs.pop_back();
dst_strand = leaf.GetRefMinusStrand() ? eNa_strand_minus : eNa_strand_plus;
if ( top_id ) {
// Add mapping from the top-level sequence if any.
src_from = leaf.GetPosition();
src_len = leaf.GetLength();
dst_from = leaf.GetRefPosition();
dst_len = src_len;
x_NextMappingRange(
*top_id,
src_from, src_len, eNa_strand_unknown,
*leaf.GetRefSeqid().GetSeqId(),
dst_from, dst_len, dst_strand);
}
// Create mapping from each non-leaf level.
ITERATE(list<CSeqMap_CI>, it, refs) {
TSeqPos shift = leaf.GetPosition() - it->GetPosition();
ENa_strand src_strand = it->GetRefMinusStrand() ? eNa_strand_minus : eNa_strand_plus;
src_from = it->GetRefPosition() + shift;
src_len = leaf.GetLength();
dst_from = leaf.GetRefPosition();
dst_len = src_len;
x_NextMappingRange(
*it->GetRefSeqid().GetSeqId(),
src_from, src_len, src_strand,
*leaf.GetRefSeqid().GetSeqId(),
dst_from, dst_len, dst_strand);
}
while ( !refs.empty() && refs.back().GetDepth() >= seg_it.GetDepth()) {
refs.pop_back();
}
}
if ( seg_it ) {
refs.push_back(seg_it);
}
}
}
void CSeq_loc_Mapper::x_InitializeSeqMapSingleLevel(CSeqMap_CI seg_it,
const CSeq_id* top_id,
ESeqMapDirection direction)
{
TSeqPos seg_from, seg_len, ref_from, ref_len;
ENa_strand seg_strand = eNa_strand_unknown;
ENa_strand ref_strand = eNa_strand_unknown;
// Stack of segments for each level.
list<CSeqMap_CI> refs;
refs.push_back(seg_it);
while ( seg_it ) {
++seg_it;
// While depth increases push all iterators to the stack.
if ( seg_it ) {
if (refs.empty() || refs.back().GetDepth() < seg_it.GetDepth()) {
refs.push_back(seg_it);
continue;
}
}
// End of seq-map or the last iterator was a leaf - create mappings.
if ( !refs.empty() ) {
CSeqMap_CI ref = refs.back();
refs.pop_back();
if (direction == eSeqMap_Down) {
// Create self-mapping of the leaf reference - we can not use
// m_DstRanges here since they will contain ranges for each
// level while we need only the bottom.
seg_from = ref.GetRefPosition();
seg_len = ref.GetLength();
ref_from = seg_from;
ref_len = seg_len;
CConstRef<CSeq_id> id = ref.GetRefSeqid().GetSeqId();
x_NextMappingRange(*id, seg_from, seg_len, eNa_strand_unknown,
*id, ref_from, ref_len, eNa_strand_unknown);
}
// Create mapping for each non-leaf level.
while ( !refs.empty() ) {
const CSeqMap_CI& seg = refs.back();
TSeqPos shift = ref.GetPosition() - seg.GetPosition();
seg_strand = seg.GetRefMinusStrand() ? eNa_strand_minus : eNa_strand_plus;
seg_from = seg.GetRefPosition() + shift;
seg_len = ref.GetLength();
ref_from = ref.GetRefPosition();
ref_len = seg_len;
ref_strand = ref.GetRefMinusStrand() ? eNa_strand_minus : eNa_strand_plus;
switch (direction) {
case eSeqMap_Down:
x_NextMappingRange(
*seg.GetRefSeqid().GetSeqId(),
seg_from, seg_len, seg_strand,
*ref.GetRefSeqid().GetSeqId(),
ref_from, ref_len, ref_strand);
break;
case eSeqMap_Up:
x_NextMappingRange(
*ref.GetRefSeqid().GetSeqId(),
ref_from, ref_len, ref_strand,
*seg.GetRefSeqid().GetSeqId(),
seg_from, seg_len, seg_strand);
break;
}
ref = seg;
if (ref.GetDepth() >= seg_it.GetDepth()) {
refs.pop_back();
}
else {
break;
}
}
// Are there still segments above?
if ( refs.empty() ) {
// Top level segment.
_ASSERT(ref);
if (top_id) {
// If the top level is a single bioseq, add mapping.
seg_from = ref.GetPosition();
seg_len = ref.GetLength();
ref_from = ref.GetRefPosition();
ref_len = seg_len;
ref_strand = ref.GetRefMinusStrand() ? eNa_strand_minus : eNa_strand_plus;
switch (direction) {
case eSeqMap_Down:
x_NextMappingRange(
*top_id,
seg_from, seg_len, eNa_strand_unknown,
*ref.GetRefSeqid().GetSeqId(),
ref_from, ref_len, ref_strand);
break;
case eSeqMap_Up:
x_NextMappingRange(
*ref.GetRefSeqid().GetSeqId(),
ref_from, ref_len, ref_strand,
*top_id,
seg_from, seg_len, seg_strand);
break;
}
}
else if (direction == eSeqMap_Up) {
// Create self-mapping of the top-level reference if the top
// level is not a single bioseq but rather a seq-map level.
ref_from = ref.GetRefPosition();
ref_len = ref.GetLength();
seg_from = ref_from;
seg_len = ref_len;
CConstRef<CSeq_id> id = ref.GetRefSeqid().GetSeqId();
x_NextMappingRange(*id, ref_from, ref_len, eNa_strand_unknown,
*id, seg_from, seg_len, eNa_strand_unknown);
}
}
}
if ( seg_it ) {
refs.push_back(seg_it);
}
}
// Remove all collected destination ranges - they are not real destinations.
m_DstRanges.clear();
// If top level is a single sequence, create self-mapping for it.
if (top_id && direction == eSeqMap_Up) {
m_DstRanges.resize(1);
m_DstRanges[0].clear();
m_DstRanges[0][CSeq_id_Handle::GetHandle(*top_id)].push_back(TRange::GetWhole());
}
}
CBioseq_Handle
CSeq_loc_Mapper::x_AddVirtualBioseq(const TSynonyms& synonyms,
const CGC_Sequence& gc_seq)
{
CRef<CBioseq> bioseq(new CBioseq);
ITERATE(IMapper_Sequence_Info::TSynonyms, syn, synonyms) {
CBioseq_Handle h = m_Scope.GetScope().GetBioseqHandle(*syn);
if ( h ) {
return h;
}
CRef<CSeq_id> syn_id(new CSeq_id);
syn_id->Assign(*syn->GetSeqId());
bioseq->SetId().push_back(syn_id);
}
bioseq->SetInst().SetMol(CSeq_inst::eMol_na);
if ( gc_seq.CanGetLength() ) {
bioseq->SetInst().SetLength(gc_seq.GetLength());
}
// Create virtual bioseq without length/data.
bioseq->SetInst().SetRepr(CSeq_inst::eRepr_virtual);
return m_Scope.GetScope().AddBioseq(*bioseq);
}
void CSeq_loc_Mapper::x_InitGCAssembly(const CGC_Assembly& gc_assembly,
EGCAssemblyAlias to_alias)
{
if ( gc_assembly.IsUnit() ) {
const CGC_AssemblyUnit& unit = gc_assembly.GetUnit();
if ( unit.IsSetMols() ) {
ITERATE(CGC_AssemblyUnit::TMols, it, unit.GetMols()) {
const CGC_Replicon::TSequence& seq = (*it)->GetSequence();
if ( seq.IsSingle() ) {
x_InitGCSequence(seq.GetSingle(), to_alias);
}
else {
ITERATE(CGC_Replicon::TSequence::TSet, tseq, seq.GetSet()) {
x_InitGCSequence(**tseq, to_alias);
}
}
}
}
if ( unit.IsSetOther_sequences() ) {
ITERATE(CGC_Sequence::TSequences, seq, unit.GetOther_sequences()) {
ITERATE(CGC_TaggedSequences::TSeqs, tseq, (*seq)->GetSeqs()) {
x_InitGCSequence(**tseq, to_alias);
}
}
}
}
else if ( gc_assembly.IsAssembly_set() ) {
const CGC_AssemblySet& aset = gc_assembly.GetAssembly_set();
x_InitGCAssembly(aset.GetPrimary_assembly(), to_alias);
if ( aset.IsSetMore_assemblies() ) {
ITERATE(CGC_AssemblySet::TMore_assemblies, assm, aset.GetMore_assemblies()) {
x_InitGCAssembly(**assm, to_alias);
}
}
}
}
inline bool s_IsLocalRandomChrId(const CSeq_id& id)
{
return id.IsLocal() && id.GetLocal().IsStr() &&
id.GetLocal().GetStr().find("_random") != string::npos;
}
bool CSeq_loc_Mapper::x_IsUCSCRandomChr(const CGC_Sequence& gc_seq,
CConstRef<CSeq_id>& chr_id,
TSynonyms& synonyms) const
{
chr_id.Reset();
if (!gc_seq.IsSetStructure()) return false;
CConstRef<CSeq_id> id(&gc_seq.GetSeq_id());
synonyms.insert(CSeq_id_Handle::GetHandle(*id));
if ( s_IsLocalRandomChrId(*id) ) {
chr_id = id;
}
// Collect all synonyms.
ITERATE(CGC_Sequence::TSeq_id_synonyms, it, gc_seq.GetSeq_id_synonyms()) {
const CGC_TypedSeqId& gc_id = **it;
switch ( gc_id.Which() ) {
case CGC_TypedSeqId::e_Genbank:
if ( gc_id.GetGenbank().IsSetGi() ) {
id.Reset(&gc_id.GetGenbank().GetGi());
}
break;
case CGC_TypedSeqId::e_Refseq:
if ( gc_id.GetRefseq().IsSetGi() ) {
id.Reset(&gc_id.GetRefseq().GetGi());
}
break;
case CGC_TypedSeqId::e_External:
id.Reset(&gc_id.GetExternal().GetId());
break;
case CGC_TypedSeqId::e_Private:
id.Reset(&gc_id.GetPrivate());
break;
default:
continue;
}
synonyms.insert(CSeq_id_Handle::GetHandle(*id));
if ( !chr_id && s_IsLocalRandomChrId(*id) ) {
chr_id = id;
}
}
if ( !chr_id ) {
synonyms.clear();
return false;
}
// Use only random chromosome ids, ignore other synonyms (?)
string lcl_str = chr_id->GetLocal().GetStr();
if ( !NStr::StartsWith(lcl_str, "chr") ) {
CSeq_id lcl;
lcl.SetLocal().SetStr("chr" + lcl_str);
synonyms.insert(CSeq_id_Handle::GetHandle(lcl));
}
return true;
}
const CSeq_id* s_GetSeqIdAlias(const CGC_TypedSeqId& id,
CSeq_loc_Mapper::EGCAssemblyAlias alias)
{
switch ( id.Which() ) {
case CGC_TypedSeqId::e_Genbank:
if (alias == CSeq_loc_Mapper::eGCA_Genbank) {
return id.GetGenbank().IsSetGi() ?
&id.GetGenbank().GetGi() : &id.GetGenbank().GetPublic();
}
if (alias == CSeq_loc_Mapper::eGCA_GenbankAcc) {
return &id.GetGenbank().GetPublic();
}
break;
case CGC_TypedSeqId::e_Refseq:
if (alias == CSeq_loc_Mapper::eGCA_Refseq) {
return id.GetRefseq().IsSetGi() ?
&id.GetRefseq().GetGi() : &id.GetRefseq().GetPublic();
}
if (alias == CSeq_loc_Mapper::eGCA_RefseqAcc) {
return &id.GetRefseq().GetPublic();
}
break;
case CGC_TypedSeqId::e_External:
if (alias == CSeq_loc_Mapper::eGCA_UCSC &&
id.GetExternal().GetExternal() == "UCSC") {
return &id.GetExternal().GetId();
}
break;
case CGC_TypedSeqId::e_Private:
if (alias == CSeq_loc_Mapper::eGCA_Other) {
return &id.GetPrivate();
}
break;
default:
break;
}
return 0;
}
void CSeq_loc_Mapper::x_InitGCSequence(const CGC_Sequence& gc_seq,
EGCAssemblyAlias to_alias)
{
if ( gc_seq.IsSetSeq_id_synonyms() ) {
CConstRef<CSeq_id> dst_id;
ITERATE(CGC_Sequence::TSeq_id_synonyms, it, gc_seq.GetSeq_id_synonyms()) {
const CGC_TypedSeqId& id = **it;
dst_id.Reset(s_GetSeqIdAlias(id, to_alias));
if ( dst_id ) break; // Use the first matching alias
}
if ( dst_id ) {
TSynonyms synonyms;
synonyms.insert(CSeq_id_Handle::GetHandle(gc_seq.GetSeq_id()));
ITERATE(CGC_Sequence::TSeq_id_synonyms, it, gc_seq.GetSeq_id_synonyms()) {
// Add conversion for each synonym which can be used
// as a source id.
const CGC_TypedSeqId& id = **it;
switch ( id.Which() ) {
case CGC_TypedSeqId::e_Genbank:
if (id.GetGenbank().IsSetGi() && dst_id != &id.GetGenbank().GetGi()) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetGenbank().GetGi()));
}
if (dst_id != &id.GetGenbank().GetPublic()) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetGenbank().GetPublic()));
}
if ( id.GetGenbank().IsSetGpipe() ) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetGenbank().GetGpipe()));
}
break;
case CGC_TypedSeqId::e_Refseq:
if (id.GetRefseq().IsSetGi() && dst_id != &id.GetRefseq().GetGi()) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetRefseq().GetGi()));
}
if (dst_id != &id.GetRefseq().GetPublic()) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetRefseq().GetPublic()));
}
if ( id.GetRefseq().IsSetGpipe() ) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetRefseq().GetGpipe()));
}
break;
case CGC_TypedSeqId::e_Private:
// Ignore private local ids - they are not unique.
if (id.GetPrivate().IsLocal()) continue;
if (dst_id != &id.GetPrivate()) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetPrivate()));
}
break;
case CGC_TypedSeqId::e_External:
if (dst_id != &id.GetExternal().GetId()) {
synonyms.insert(CSeq_id_Handle::GetHandle(id.GetExternal().GetId()));
}
break;
default:
NCBI_THROW(CAnnotMapperException, eOtherError,
"Unsupported alias type in GC-Sequence synonyms");
break;
}
}
CBioseq_Handle h = x_AddVirtualBioseq(synonyms, gc_seq);
TSeqPos hlen = kInvalidSeqPos;
if (h && h.CanGetInst_Length()) {
hlen = h.GetInst_Length();
}
x_AddConversion(gc_seq.GetSeq_id(), 0, eNa_strand_unknown,
*dst_id, 0, eNa_strand_unknown,
hlen != kInvalidSeqPos ? hlen : TRange::GetWholeLength(),
false, 0, hlen, hlen);
}
else if (to_alias == eGCA_UCSC || to_alias == eGCA_Refseq) {
TSynonyms synonyms;
CConstRef<CSeq_id> chr_id;
// The requested alias type not found,
// check for UCSC random chromosomes.
if ( x_IsUCSCRandomChr(gc_seq, chr_id, synonyms) ) {
_ASSERT(chr_id);
// Use structure (delta-seq) to initialize the mapper.
// Here we use just one level of the delta and parse it
// directly rather than use CSeqMap.
TSeqPos chr_pos = 0;
TSeqPos chr_len = kInvalidSeqPos;
ITERATE(CDelta_ext::Tdata, it, gc_seq.GetStructure().Get()) {
// Do not create mappings for literals/gaps.
if ( (*it)->IsLiteral() ) {
chr_pos += (*it)->GetLiteral().GetLength();
}
if ( !(*it)->IsLoc() ) {
continue;
}
CSeq_loc_CI loc_it((*it)->GetLoc());
for (; loc_it; ++loc_it) {
if ( loc_it.IsEmpty() ) continue;
TSeqPos seg_pos = loc_it.GetRange().GetFrom();
TSeqPos seg_len = loc_it.GetRange().GetLength();
ENa_strand seg_str = loc_it.IsSetStrand() ?
loc_it.GetStrand() : eNa_strand_unknown;
switch ( to_alias ) {
case eGCA_UCSC:
// Map up to the chr
x_NextMappingRange(loc_it.GetSeq_id(),
seg_pos, seg_len, seg_str,
*chr_id, chr_pos, chr_len,
eNa_strand_unknown);
break;
case eGCA_Refseq:
// Map down to delta parts
x_NextMappingRange(*chr_id, chr_pos, chr_len,
eNa_strand_unknown,
loc_it.GetSeq_id(), seg_pos, seg_len,
seg_str);
break;
default:
break;
}
}
}
x_AddVirtualBioseq(synonyms, gc_seq);
}
}
}
if ( gc_seq.IsSetSequences() ) {
ITERATE(CGC_Sequence::TSequences, seq, gc_seq.GetSequences()) {
ITERATE(CGC_TaggedSequences::TSeqs, tseq, (*seq)->GetSeqs()) {
x_InitGCSequence(**tseq, to_alias);
}
}
}
}
/////////////////////////////////////////////////////////////////////
//
// Initialization helpers
//
CSeq_align_Mapper_Base*
CSeq_loc_Mapper::InitAlignMapper(const CSeq_align& src_align)
{
return new CSeq_align_Mapper(src_align, *this);
}
END_SCOPE(objects)
END_NCBI_SCOPE
| 37.405508 | 101 | 0.540901 | mycolab |
08cbc5884ae6e5a991bbf315d056721f69138e0d | 1,507 | cpp | C++ | breeze/text/test/string_builder_test.cpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-04-03T22:35:52.000Z | 2021-04-03T22:35:52.000Z | breeze/text/test/string_builder_test.cpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | null | null | null | breeze/text/test/string_builder_test.cpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-10-01T04:26:48.000Z | 2021-10-01T04:26:48.000Z | // ===========================================================================
// Copyright 2021 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
#include "breeze/text/string_builder.hpp"
#include "breeze/testing/testing.hpp"
#include <ios>
#include <ostream>
#include <iomanip>
int test_string_builder() ;
namespace {
void
do_test()
{
using breeze::string_builder ;
// Format with a named string builder.
{
string_builder builder ;
builder << "This is a number: " << 100 ;
BREEZE_CHECK( builder.str() == "This is a number: 100" ) ;
}
// Format with a temporary string builder.
{
BREEZE_CHECK(
( string_builder() << "This is a number: " << 100 ).str()
== "This is a number: 100" ) ;
}
// Use manipulators.
{
std::string const s = "bar" ;
BREEZE_CHECK(
( string_builder() << std::setw( 8 ) << std::setfill( '*' )
<< "foo" << std::hex << 64 << s << std::endl ).str()
== "*****foo40bar\n" ) ;
}
}
}
int
test_string_builder()
{
return breeze::test_runner::instance().run(
"string_builder",
{ do_test } ) ;
}
| 25.542373 | 78 | 0.512276 | gennaroprota |
08e150cb96743d39c259b66326e3235961fdfd70 | 8,644 | cc | C++ | tests/ut/cpp/serving/acl_session_test_two_input_output.cc | dongkcs/mindspore | cd7df6dbf463ff3128e9181e9d0c779cecb81320 | [
"Apache-2.0"
] | 2 | 2020-11-23T13:46:37.000Z | 2020-12-20T02:02:38.000Z | tests/ut/cpp/serving/acl_session_test_two_input_output.cc | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | 1 | 2020-12-29T06:46:38.000Z | 2020-12-29T06:46:38.000Z | tests/ut/cpp/serving/acl_session_test_two_input_output.cc | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | 1 | 2021-01-01T08:35:01.000Z | 2021-01-01T08:35:01.000Z | /**
* Copyright 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 "acl_session_test_common.h"
using namespace std;
namespace mindspore {
namespace serving {
class AclSessionTwoInputTwoOutputTest : public AclSessionTest {
public:
AclSessionTwoInputTwoOutputTest() = default;
void SetUp() override {
AclSessionTest::SetUp();
aclmdlDesc model_desc;
model_desc.inputs.push_back(
AclTensorDesc{.dims = {2, 24, 24, 3}, .data_type = ACL_FLOAT, .size = 2 * 24 * 24 * 3 * sizeof(float)});
model_desc.inputs.push_back(
AclTensorDesc{.dims = {2, 32}, .data_type = ACL_INT32, .size = 2 * 32 * sizeof(int32_t)});
model_desc.outputs.push_back(
AclTensorDesc{.dims = {2, 8, 8, 3}, .data_type = ACL_FLOAT, .size = 2 * 8 * 8 * 3 * sizeof(float)});
model_desc.outputs.push_back(
AclTensorDesc{.dims = {2, 1024}, .data_type = ACL_BOOL, .size = 2 * 1024 * sizeof(bool)});
mock_model_desc_ = MockModelDesc(model_desc);
g_acl_model_desc = &mock_model_desc_;
}
void CreateDefaultRequest(PredictRequest &request) {
auto input0 = request.add_data();
CreateTensor(*input0, {2, 24, 24, 3}, ::ms_serving::DataType::MS_FLOAT32);
auto input1 = request.add_data();
CreateTensor(*input1, {2, 32}, ::ms_serving::DataType::MS_INT32);
}
void CreateInvalidDataSizeRequest0(PredictRequest &request) {
auto input0 = request.add_data();
// data size invalid, not match model input required
CreateTensor(*input0, {2, 24, 24, 2}, ::ms_serving::DataType::MS_FLOAT32);
auto input1 = request.add_data();
CreateTensor(*input1, {2, 32}, ::ms_serving::DataType::MS_INT32);
}
void CreateInvalidDataSizeRequest1(PredictRequest &request) {
auto input0 = request.add_data();
CreateTensor(*input0, {2, 24, 24, 3}, ::ms_serving::DataType::MS_FLOAT32);
auto input1 = request.add_data();
// data size invalid, not match model input required
CreateTensor(*input1, {2, 16}, ::ms_serving::DataType::MS_INT32);
}
void CreateInvalidDataSizeRequestOneInput0(PredictRequest &request) {
// only has one input for input0
auto input0 = request.add_data();
CreateTensor(*input0, {2, 24, 24, 3}, ::ms_serving::DataType::MS_FLOAT32);
}
void CreateInvalidDataSizeRequestOneInput1(PredictRequest &request) {
// only has one input for input1
auto input0 = request.add_data();
CreateTensor(*input0, {2, 32}, ::ms_serving::DataType::MS_INT32);
}
void CheckDefaultReply(const PredictReply &reply) {
EXPECT_TRUE(reply.result().size() == 2);
if (reply.result().size() == 2) {
CheckTensorItem(reply.result(0), {2, 8, 8, 3}, ::ms_serving::DataType::MS_FLOAT32);
CheckTensorItem(reply.result(1), {2, 1024}, ::ms_serving::DataType::MS_BOOL);
}
}
MockModelDesc mock_model_desc_;
};
TEST_F(AclSessionTwoInputTwoOutputTest, TestAclSession_OneTime_Success) {
inference::AclSession acl_session;
uint32_t device_id = 1;
EXPECT_TRUE(acl_session.InitEnv("Ascend", device_id) == SUCCESS);
uint32_t model_id = 0;
EXPECT_TRUE(acl_session.LoadModelFromFile("fake_model_path", model_id) == SUCCESS);
// create inputs
PredictRequest request;
CreateDefaultRequest(request);
PredictReply reply;
ServingRequest serving_request(request);
ServingReply serving_reply(reply);
EXPECT_TRUE(acl_session.ExecuteModel(model_id, serving_request, serving_reply) == SUCCESS);
CheckDefaultReply(reply);
EXPECT_TRUE(acl_session.UnloadModel(model_id) == SUCCESS);
EXPECT_TRUE(acl_session.FinalizeEnv() == SUCCESS);
};
TEST_F(AclSessionTwoInputTwoOutputTest, TestAclSession_MutilTimes_Success) {
inference::AclSession acl_session;
uint32_t device_id = 1;
EXPECT_TRUE(acl_session.InitEnv("Ascend", device_id) == SUCCESS);
uint32_t model_id = 0;
EXPECT_TRUE(acl_session.LoadModelFromFile("fake_model_path", model_id) == SUCCESS);
for (int i = 0; i < 10; i++) {
// create inputs
PredictRequest request;
CreateDefaultRequest(request);
PredictReply reply;
ServingRequest serving_request(request);
ServingReply serving_reply(reply);
EXPECT_TRUE(acl_session.ExecuteModel(model_id, serving_request, serving_reply) == SUCCESS);
CheckDefaultReply(reply);
}
EXPECT_TRUE(acl_session.UnloadModel(model_id) == SUCCESS);
EXPECT_TRUE(acl_session.FinalizeEnv() == SUCCESS);
};
TEST_F(AclSessionTwoInputTwoOutputTest, TestAclSession_Input0_InvalidDataSize_Fail) {
inference::AclSession acl_session;
uint32_t device_id = 1;
EXPECT_TRUE(acl_session.InitEnv("Ascend", device_id) == SUCCESS);
uint32_t model_id = 0;
EXPECT_TRUE(acl_session.LoadModelFromFile("fake_model_path", model_id) == SUCCESS);
// create inputs
PredictRequest request;
CreateInvalidDataSizeRequest0(request);
PredictReply reply;
ServingRequest serving_request(request);
ServingReply serving_reply(reply);
EXPECT_FALSE(acl_session.ExecuteModel(model_id, serving_request, serving_reply) == SUCCESS);
EXPECT_TRUE(acl_session.UnloadModel(model_id) == SUCCESS);
EXPECT_TRUE(acl_session.FinalizeEnv() == SUCCESS);
};
TEST_F(AclSessionTwoInputTwoOutputTest, TestAclSession_Input1_InvalidDataSize_Fail) {
inference::AclSession acl_session;
uint32_t device_id = 1;
EXPECT_TRUE(acl_session.InitEnv("Ascend", device_id) == SUCCESS);
uint32_t model_id = 0;
EXPECT_TRUE(acl_session.LoadModelFromFile("fake_model_path", model_id) == SUCCESS);
// create inputs
PredictRequest request;
CreateInvalidDataSizeRequest1(request);
PredictReply reply;
ServingRequest serving_request(request);
ServingReply serving_reply(reply);
EXPECT_FALSE(acl_session.ExecuteModel(model_id, serving_request, serving_reply) == SUCCESS);
EXPECT_TRUE(acl_session.UnloadModel(model_id) == SUCCESS);
EXPECT_TRUE(acl_session.FinalizeEnv() == SUCCESS);
};
TEST_F(AclSessionTwoInputTwoOutputTest, TestAclSession_OnlyInput0_Fail) {
inference::AclSession acl_session;
uint32_t device_id = 1;
EXPECT_TRUE(acl_session.InitEnv("Ascend", device_id) == SUCCESS);
uint32_t model_id = 0;
EXPECT_TRUE(acl_session.LoadModelFromFile("fake_model_path", model_id) == SUCCESS);
// create inputs
PredictRequest request;
CreateInvalidDataSizeRequestOneInput0(request);
PredictReply reply;
ServingRequest serving_request(request);
ServingReply serving_reply(reply);
EXPECT_FALSE(acl_session.ExecuteModel(model_id, serving_request, serving_reply) == SUCCESS);
EXPECT_TRUE(acl_session.UnloadModel(model_id) == SUCCESS);
EXPECT_TRUE(acl_session.FinalizeEnv() == SUCCESS);
};
TEST_F(AclSessionTwoInputTwoOutputTest, TestAclSession_OnlyInput1_Fail) {
inference::AclSession acl_session;
uint32_t device_id = 1;
EXPECT_TRUE(acl_session.InitEnv("Ascend", device_id) == SUCCESS);
uint32_t model_id = 0;
EXPECT_TRUE(acl_session.LoadModelFromFile("fake_model_path", model_id) == SUCCESS);
// create inputs
PredictRequest request;
CreateInvalidDataSizeRequestOneInput1(request);
PredictReply reply;
ServingRequest serving_request(request);
ServingReply serving_reply(reply);
EXPECT_FALSE(acl_session.ExecuteModel(model_id, serving_request, serving_reply) == SUCCESS);
EXPECT_TRUE(acl_session.UnloadModel(model_id) == SUCCESS);
EXPECT_TRUE(acl_session.FinalizeEnv() == SUCCESS);
};
TEST_F(AclSessionTwoInputTwoOutputTest, TestAclSession_InvalidDataSize_MultiTimes_Fail) {
inference::AclSession acl_session;
uint32_t device_id = 1;
EXPECT_TRUE(acl_session.InitEnv("Ascend", device_id) == SUCCESS);
uint32_t model_id = 0;
EXPECT_TRUE(acl_session.LoadModelFromFile("fake_model_path", model_id) == SUCCESS);
for (int i = 0; i < 10; i++) {
// create inputs
PredictRequest request;
CreateInvalidDataSizeRequest0(request);
PredictReply reply;
ServingRequest serving_request(request);
ServingReply serving_reply(reply);
EXPECT_FALSE(acl_session.ExecuteModel(model_id, serving_request, serving_reply) == SUCCESS);
}
EXPECT_TRUE(acl_session.UnloadModel(model_id) == SUCCESS);
EXPECT_TRUE(acl_session.FinalizeEnv() == SUCCESS);
};
} // namespace serving
} // namespace mindspore | 38.247788 | 110 | 0.748033 | dongkcs |
08e4befafcd01ec4d1f9b8754ad89c8c78b6f882 | 4,740 | cpp | C++ | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/vrml97/NormalInterpolator.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/vrml97/NormalInterpolator.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/vrml97/NormalInterpolator.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#ifdef HAVE_VRML97
/*!
\class SoVRMLNormalInterpolator SoVRMLNormalInterpolator.h Inventor/VRMLnodes/SoVRMLNormalInterpolator.h
\brief The SoVRMLNormalInterpolator class is used to interpolate normals.
\ingroup VRMLnodes
\WEB3DCOPYRIGHT
\verbatim
NormalInterpolator {
eventIn SFFloat set_fraction # (-inf, inf)
exposedField MFFloat key [] # (-inf, inf)
exposedField MFVec3f keyValue [] # (-inf, inf)
eventOut MFVec3f value_changed
}
\endverbatim
The NormalInterpolator node interpolates among a list of normal
vector sets specified by the keyValue field. The output vector,
value_changed, shall be a set of normalized vectors. Values in the
keyValue field shall be of unit length. The number of normals in the
keyValue field shall be an integer multiple of the number of
keyframes in the key field. That integer multiple defines how many
normals will be contained in the value_changed events. Normal
interpolation shall be performed on the surface of the unit sphere.
That is, the output values for a linear interpolation from a point P
on the unit sphere to a point Q also on the unit sphere shall lie
along the shortest arc (on the unit sphere) connecting points P and
Q. Also, equally spaced input fractions shall result in arcs of
equal length. The results are undefined if P and Q are diagonally
opposite. A more detailed discussion of interpolators is provided
in 4.6.8, Interpolator nodes
(<http://www.web3d.org/x3d/specifications/vrml/ISO-IEC-14772-VRML97/part1/concepts.html#4.6.8>).
*/
/*!
\var SoMFVec3f SoVRMLNormalInterpolator::keyValue
The keyValue vector.
*/
/*!
\var SoEngineOutput SoVRMLNormalInterpolator::value_changed
The eventOut which is sent every time the interpolator has calculated a new value.
*/
#include <Inventor/VRMLnodes/SoVRMLNormalInterpolator.h>
#include <Inventor/VRMLnodes/SoVRMLMacros.h>
#include "engines/SoSubNodeEngineP.h"
#ifndef DOXYGEN_SKIP_THIS
class SoVRMLNormalInterpolatorP {
public:
SbList <SbVec3f> tmplist;
};
#endif // DOXYGEN_SKIP_THIS
SO_NODEENGINE_SOURCE(SoVRMLNormalInterpolator);
// Doc in parent
void
SoVRMLNormalInterpolator::initClass(void)
{
SO_NODEENGINE_INTERNAL_INIT_CLASS(SoVRMLNormalInterpolator);
}
#define PRIVATE(obj) ((obj)->pimpl)
/*!
Constructor.
*/
SoVRMLNormalInterpolator::SoVRMLNormalInterpolator(void)
{
PRIVATE(this) = new SoVRMLNormalInterpolatorP;
SO_NODEENGINE_INTERNAL_CONSTRUCTOR(SoVRMLNormalInterpolator);
SO_VRMLNODE_ADD_EMPTY_EXPOSED_MFIELD(keyValue);
SO_NODEENGINE_ADD_OUTPUT(value_changed, SoMFVec3f);
}
/*!
Destructor.
*/
SoVRMLNormalInterpolator::~SoVRMLNormalInterpolator()
{
delete PRIVATE(this);
}
// Doc in parent
void
SoVRMLNormalInterpolator::evaluate(void)
{
if (!this->value_changed.isEnabled()) return;
float interp;
int i, idx = this->getKeyValueIndex(interp);
if (idx < 0) return;
PRIVATE(this)->tmplist.truncate(0);
const int numkeys = this->key.getNum();
const int numcoords = this->keyValue.getNum() / numkeys;
const SbVec3f * c0 = this->keyValue.getValues(idx*numcoords);
const SbVec3f * c1 = c0;
if (interp > 0.0f) c1 = this->keyValue.getValues((idx+1)*numcoords);
for (i = 0; i < numcoords; i++) {
PRIVATE(this)->tmplist.append(c0[i] + (c1[i]-c0[i]) * interp);
}
const SbVec3f * coords = PRIVATE(this)->tmplist.getArrayPtr();
SO_ENGINE_OUTPUT(value_changed, SoMFVec3f, setNum(numcoords));
SO_ENGINE_OUTPUT(value_changed, SoMFVec3f, setValues(0, numcoords, coords));
}
#undef PRIVATE
#endif // HAVE_VRML97
| 30.980392 | 106 | 0.722152 | KraftOreo |
08e53a94f9e8106f79cd21ed214e95e628393d72 | 122 | hpp | C++ | source/code/utilities/graphics/x11/xdo/lib.hpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/utilities/graphics/x11/xdo/lib.hpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/utilities/graphics/x11/xdo/lib.hpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #pragma once
#ifdef __cplusplus
extern "C"
{
#endif
#include "xdo.h"
#ifdef __cplusplus
} // extern "C"
#endif
| 9.384615 | 18 | 0.631148 | luxe |
08eccc436ec610da1ebbe503ed6e5fcd5fb7399d | 434 | cpp | C++ | src/commands/ServerDeviceListCommand.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 7 | 2018-06-09T05:55:59.000Z | 2021-01-05T05:19:02.000Z | src/commands/ServerDeviceListCommand.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 1 | 2019-12-25T10:39:06.000Z | 2020-01-03T08:35:29.000Z | src/commands/ServerDeviceListCommand.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 11 | 2018-05-10T08:29:05.000Z | 2020-01-22T20:49:32.000Z | #include "commands/ServerDeviceListCommand.h"
using namespace BeeeOn;
using namespace std;
ServerDeviceListCommand::ServerDeviceListCommand(
const DevicePrefix &prefix):
m_prefix(prefix)
{
}
ServerDeviceListCommand::~ServerDeviceListCommand()
{
}
DevicePrefix ServerDeviceListCommand::devicePrefix() const
{
return m_prefix;
}
string ServerDeviceListCommand::toString() const
{
return name() + " " + m_prefix.toString();
}
| 17.36 | 58 | 0.781106 | jalowiczor |
08f1142801945f003535a870a05b21a6a8b3fe44 | 2,089 | cpp | C++ | src/zwave/ZWaveDriverEvent.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 7 | 2018-06-09T05:55:59.000Z | 2021-01-05T05:19:02.000Z | src/zwave/ZWaveDriverEvent.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 1 | 2019-12-25T10:39:06.000Z | 2020-01-03T08:35:29.000Z | src/zwave/ZWaveDriverEvent.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 11 | 2018-05-10T08:29:05.000Z | 2020-01-22T20:49:32.000Z | #include <Poco/Exception.h>
#include "zwave/ZWaveDriverEvent.h"
using namespace std;
using namespace Poco;
using namespace BeeeOn;
ZWaveDriverEvent::ZWaveDriverEvent(const map<string, uint32_t> &stats):
m_stats(stats)
{
}
uint32_t ZWaveDriverEvent::lookup(const string &key) const
{
auto it = m_stats.find(key);
if (it == m_stats.end())
throw NotFoundException("no such driver statistic " + key);
return it->second;
}
uint32_t ZWaveDriverEvent::SOFCount() const
{
return lookup("SOFCnt");
}
uint32_t ZWaveDriverEvent::ACKWaiting() const
{
return lookup("ACKWaiting");
}
uint32_t ZWaveDriverEvent::readAborts() const
{
return lookup("readAborts");
}
uint32_t ZWaveDriverEvent::badChecksum() const
{
return lookup("badChecksum");
}
uint32_t ZWaveDriverEvent::readCount() const
{
return lookup("readCnt");
}
uint32_t ZWaveDriverEvent::writeCount() const
{
return lookup("writeCnt");
}
uint32_t ZWaveDriverEvent::CANCount() const
{
return lookup("CANCnt");
}
uint32_t ZWaveDriverEvent::NAKCount() const
{
return lookup("NAKCnt");
}
uint32_t ZWaveDriverEvent::ACKCount() const
{
return lookup("ACKCnt");
}
uint32_t ZWaveDriverEvent::OOFCount() const
{
return lookup("OOFCnt");
}
uint32_t ZWaveDriverEvent::dropped() const
{
return lookup("dropped");
}
uint32_t ZWaveDriverEvent::retries() const
{
return lookup("retries");
}
uint32_t ZWaveDriverEvent::callbacks() const
{
return lookup("callbacks");
}
uint32_t ZWaveDriverEvent::badroutes() const
{
return lookup("badroutes");
}
uint32_t ZWaveDriverEvent::noACK() const
{
return lookup("noACK");
}
uint32_t ZWaveDriverEvent::netBusy() const
{
return lookup("netbusy");
}
uint32_t ZWaveDriverEvent::notIdle() const
{
return lookup("notidle");
}
uint32_t ZWaveDriverEvent::nonDelivery() const
{
return lookup("nondelivery");
}
uint32_t ZWaveDriverEvent::routedBusy() const
{
return lookup("routedbusy");
}
uint32_t ZWaveDriverEvent::broadcastReadCount() const
{
return lookup("broadcastReadCnt");
}
uint32_t ZWaveDriverEvent::broadcastWriteCount() const
{
return lookup("broadcastWriteCnt");
}
| 16.579365 | 71 | 0.746769 | jalowiczor |
08f27218e1d7766b91876bd6e2836fd0aec7beb2 | 1,428 | cpp | C++ | Practice/2018/2018.8.15/HDU5608.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.8.15/HDU5608.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.8.15/HDU5608.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=1000000;
const int Mod=1e9+7;
const int inf=2147483647;
bool notprime[maxN];
int pcnt,Prime[maxN],Mu[maxN];
int inv3;
int F[maxN];
map<int,int> Rc;
int QPow(int x,int cnt);
void Init();
int Calc(int n);
int main(){
inv3=QPow(3,Mod-2);
Init();
int TTT;scanf("%d",&TTT);
while (TTT--){
int n;scanf("%d",&n);
printf("%d\n",Calc(n));
}
return 0;
}
int QPow(int x,int cnt){
int ret=1;
while (cnt){
if (cnt&1) ret=1ll*ret*x%Mod;
x=1ll*x*x%Mod;cnt>>=1;
}
return ret;
}
void Init(){
Mu[1]=1;notprime[1]=1;
for (int i=2;i<maxN;i++){
if (notprime[i]==0) Prime[++pcnt]=i,Mu[i]=-1;
for (int j=1;(j<=pcnt)&&(1ll*i*Prime[j]<maxN);j++){
notprime[i*Prime[j]]=1;
if (i%Prime[j]==0){
Mu[i*Prime[j]]=0;break;
}
Mu[i*Prime[j]]=-Mu[i];
}
}
for (int i=1;i<maxN;i++){
int g=((1ll*i*i%Mod-3ll*i+2)%Mod+Mod)%Mod;
for (int j=i;j<maxN;j+=i)
F[j]=(F[j]+1ll*g*Mu[j/i]+Mod)%Mod;
}
for (int i=1;i<maxN;i++) F[i]=(F[i-1]+F[i])%Mod;
return;
}
int Calc(int n){
if (n<maxN) return F[n];
if (Rc.count(n)) return Rc[n];
int ret=0;
for (int i=2,j;i<=n;i=j+1){
j=n/(int)(n/i);
ret=(ret+1ll*(j-i+1)*Calc(n/i)%Mod)%Mod;
}
return Rc[n]=(1ll*n*(n-1)%Mod*(n-2)%Mod*inv3%Mod+Mod-ret)%Mod;
}
| 18.075949 | 63 | 0.584734 | SYCstudio |
08f41bb96ec1e898fbcac9a8e314b2486240411c | 335 | hpp | C++ | external/boost/logging/boost/logging/detail/raw_doc/customize_manipulator.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 5 | 2015-09-15T16:24:14.000Z | 2021-08-12T11:05:55.000Z | external/boost/logging/boost/logging/detail/raw_doc/customize_manipulator.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | null | null | null | external/boost/logging/boost/logging/detail/raw_doc/customize_manipulator.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 3 | 2016-11-17T04:38:38.000Z | 2021-04-10T17:23:52.000Z | namespace boost { namespace logging {
/**
@page customize_manipulator Customizing manipulator arguments (Advanced)
FIXME
optimize::cache_string_on_str
optimize::cache_string_several_str
@section customize_optimize Optimizing manipulator arguments
optimize::cache_string_on_str
optimize::cache_string_several_str
FIXME
*/
}}
| 14.565217 | 72 | 0.826866 | saga-project |
08fbf28b60491927237ba1a957ca35654ce85c51 | 1,481 | hpp | C++ | app_config.hpp | rockonedege/ADS | 655684d98013056b07f17c846656823625824ab4 | [
"MIT"
] | null | null | null | app_config.hpp | rockonedege/ADS | 655684d98013056b07f17c846656823625824ab4 | [
"MIT"
] | null | null | null | app_config.hpp | rockonedege/ADS | 655684d98013056b07f17c846656823625824ab4 | [
"MIT"
] | null | null | null | #pragma once
#if !defined(__ADSDEF_H__)
#pragma message("must #include <AdsLib.h> before this file if using AdsLib or TcAdsDef.h if TWinCAT ADS-DLL")
#endif
namespace appinfo
{
struct {
const int major = 0;
const int minor = 0;
const int patch = 0;
const int build = 1;
const char* to_string = "0.0.0.1";
const wchar_t* to_wstring = L"0.0.0.1";
} const version;
const char* name = "Ads";
const char* meta_text =
"==============================================================================\n"
"\tAds version 0.0.0.1 for Windows x86, " __DATE__ ".\n"
#if defined(_DEBUG)
"\n\t!!THIS IS A DEBUG BUILD, NOT FOR PRODUCTION USAGES. !!\n"
#endif
"==============================================================================\n";
}
namespace test_twincat_server
{
struct remote_target {
const char* ip_v4;
AmsAddr server;
};
// example for TWinCAT2
remote_target tc2 = {
"10.8.9.36", // ip v4
{
{ 10, 0, 96, 139, 1, 1 }, // AMS Net Id
AMSPORT_R0_PLC // AMS Port number
}
};
// example for TWinCAT3
const remote_target tc3 = {
"192.168.0.232", // ip v4
{
{ 192, 168, 0, 231, 1, 1 }, // AMS Net Id
AMSPORT_R0_PLC_TC3 // AMS Port number
}
};
const remote_target& tc = tc2;
}
| 26.446429 | 109 | 0.46185 | rockonedege |
08fcbb24991ab9a054938e8cfde53ec259afe217 | 942 | cpp | C++ | metagen/meta_gincugconfiginfo.cpp | wqking/gincu | dd9d83cc75561d873fc396d009436ba07219ff4d | [
"Apache-2.0"
] | 51 | 2017-02-01T14:50:03.000Z | 2022-01-14T11:19:51.000Z | metagen/meta_gincugconfiginfo.cpp | wqking/gincu | dd9d83cc75561d873fc396d009436ba07219ff4d | [
"Apache-2.0"
] | null | null | null | metagen/meta_gincugconfiginfo.cpp | wqking/gincu | dd9d83cc75561d873fc396d009436ba07219ff4d | [
"Apache-2.0"
] | 9 | 2018-07-20T07:47:39.000Z | 2020-10-31T16:26:08.000Z | // Auto generated file, don't modify.
#include "gincu/gincuall.h"
#include "cpgf/metatraits/gmetasharedptrtraits_cpp11_shared_ptr.h"
#include "gincu/gconfiginfo.h"
#include "meta_gincugconfiginfo.h"
using namespace cpgf;
namespace meta_gincu {
#ifdef CPGF_METAGEN_LINKAGE_SPEC
CPGF_METAGEN_LINKAGE_SPEC
#endif
GDefineMetaInfo createMetaClass_Global_gconfiginfo()
{
GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle();
buildMetaClass_Global_gconfiginfo(_d);
return _d.getMetaInfo();
}
#ifdef CPGF_METAGEN_LINKAGE_SPEC
CPGF_METAGEN_LINKAGE_SPEC
#endif
GDefineMetaInfo createMetaClass_GConfigInfo()
{
GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle();
{
GDefineMetaClass<gincu::GConfigInfo> _nd = GDefineMetaClass<gincu::GConfigInfo>::lazyDeclare("GConfigInfo", &buildMetaClass_GConfigInfo);
_d._class(_nd);
}
return _d.getMetaInfo();
}
} // namespace meta_gincu
| 21.906977 | 145 | 0.779193 | wqking |
08ffd660c5269eee13ef98ace59083cf438ac180 | 6,995 | cpp | C++ | Wml/Source/Graphics/WmlSpotLight.cpp | 1iyiwei/deform2d | 1a350dd20f153e72de1ea9cffb873eb67bf3d668 | [
"MIT"
] | 26 | 2018-07-04T15:31:11.000Z | 2021-09-23T02:43:46.000Z | Wml/Source/Graphics/WmlSpotLight.cpp | 1iyiwei/deform2d | 1a350dd20f153e72de1ea9cffb873eb67bf3d668 | [
"MIT"
] | null | null | null | Wml/Source/Graphics/WmlSpotLight.cpp | 1iyiwei/deform2d | 1a350dd20f153e72de1ea9cffb873eb67bf3d668 | [
"MIT"
] | 1 | 2019-06-11T03:20:28.000Z | 2019-06-11T03:20:28.000Z | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2004. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlMatrix3.h"
#include "WmlSpotLight.h"
using namespace Wml;
WmlImplementRTTI(SpotLight,PointLight);
WmlImplementStream(SpotLight);
//----------------------------------------------------------------------------
SpotLight::SpotLight ()
:
m_kDirection(-Vector3f::UNIT_Z)
{
SetAngle(Mathf::PI);
m_fExponent = 0.0f;
}
//----------------------------------------------------------------------------
void SpotLight::SetAngle (float fAngle)
{
m_fAngle = fAngle;
m_fCosSqr = Mathf::Cos(m_fAngle);
m_fCosSqr *= m_fCosSqr;
m_fSinSqr = Mathf::Sin(m_fAngle);
m_fSinSqr *= m_fSinSqr;
}
//----------------------------------------------------------------------------
void SpotLight::ComputeDiffuse (const Matrix3f& rkWorldRotate,
const Vector3f& rkWorldTranslate, float fWorldScale,
const Vector3f* akVertex, const Vector3f* akNormal, int iQuantity,
const bool* abVisible, ColorRGB* akDiffuse)
{
// transform light position to model space of old mesh
float fInvWScale = 1.0f/fWorldScale;
Vector3f kDiff = m_kLocation - rkWorldTranslate;
Vector3f kModelPos = (kDiff*rkWorldRotate)*fInvWScale;
Vector3f kModelDir = m_kDirection*rkWorldRotate;
// adjust diffuse color by light intensity
ColorRGB kAdjDiffuse = m_fIntensity*m_kDiffuse;
for (int i = 0; i < iQuantity; i++)
{
if ( abVisible[i] )
{
kDiff = kModelPos - akVertex[i];
float fDiffDotDir = kDiff.Dot(kModelDir);
if ( fDiffDotDir >= 0.0f )
continue;
float fLenSqr = kDiff.Dot(kDiff);
float fDiffDotDirSqr = fDiffDotDir*fDiffDotDir;
float fAngleAttenuate = fDiffDotDirSqr - fLenSqr*m_fCosSqr;
if ( fAngleAttenuate <= 0.0f )
continue;
float fDot = kDiff.Dot(akNormal[i]);
if ( fDot > 0.0f )
{
float fNumer = fDot*fAngleAttenuate;
float fDenom = fDiffDotDirSqr*m_fSinSqr*Mathf::Sqrt(fLenSqr);
akDiffuse[i] += (fNumer/fDenom)*kAdjDiffuse;
}
}
}
}
//----------------------------------------------------------------------------
void SpotLight::ComputeSpecular (const Matrix3f& rkWorldRotate,
const Vector3f& rkWorldTranslate, float fWorldScale,
const Vector3f* akVertex, const Vector3f* akNormal, int iQuantity,
const bool* abVisible, const Vector3f& rkCameraModelLocation,
ColorRGB* akSpecular)
{
// transform light position to model space of old mesh
float fInvWScale = 1.0f/fWorldScale;
Vector3f kDiff = m_kLocation - rkWorldTranslate;
Vector3f kModelPos = (kDiff*rkWorldRotate)*fInvWScale;
Vector3f kModelDir = m_kDirection*rkWorldRotate;
// adjust diffuse color by light intensity
ColorRGB kAdjSpecular = m_fIntensity*m_kSpecular;
for (int i = 0; i < iQuantity; i++)
{
if ( abVisible[i] )
{
kDiff = kModelPos - akVertex[i];
float fDiffDotDir = kDiff.Dot(kModelDir);
if ( fDiffDotDir >= 0.0f )
continue;
float fLenSqr = kDiff.Dot(kDiff);
float fDiffDotDirSqr = fDiffDotDir*fDiffDotDir;
float fAngleAttenuate = fDiffDotDirSqr - fLenSqr*m_fCosSqr;
if ( fAngleAttenuate <= 0.0f )
continue;
float fDot = kDiff.Dot(akNormal[i]);
Vector3f kReflect = (2.0f*fDot)*akNormal[i] - kDiff;
Vector3f kViewDir = rkCameraModelLocation - akVertex[i];
fDot = kViewDir.Dot(kReflect);
if ( fDot > 0.0f )
{
float fNumer = fDot*fDot*fAngleAttenuate;
float fDenom = fDiffDotDirSqr*m_fSinSqr*Mathf::Sqrt(fLenSqr)*
kViewDir.Dot(kViewDir);
akSpecular[i] += (fNumer/fDenom)*kAdjSpecular;
}
}
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// streaming
//----------------------------------------------------------------------------
Object* SpotLight::Factory (Stream& rkStream)
{
SpotLight* pkObject = new SpotLight;
Stream::Link* pkLink = new Stream::Link(pkObject);
pkObject->Load(rkStream,pkLink);
return pkObject;
}
//----------------------------------------------------------------------------
void SpotLight::Load (Stream& rkStream, Stream::Link* pkLink)
{
PointLight::Load(rkStream,pkLink);
// native data
StreamRead(rkStream,m_kDirection);
StreamRead(rkStream,m_fAngle);
StreamRead(rkStream,m_fExponent);
}
//----------------------------------------------------------------------------
void SpotLight::Link (Stream& rkStream, Stream::Link* pkLink)
{
PointLight::Link(rkStream,pkLink);
}
//----------------------------------------------------------------------------
bool SpotLight::Register (Stream& rkStream)
{
return PointLight::Register(rkStream);
}
//----------------------------------------------------------------------------
void SpotLight::Save (Stream& rkStream)
{
PointLight::Save(rkStream);
// native data
StreamWrite(rkStream,m_kDirection);
StreamWrite(rkStream,m_fAngle);
StreamWrite(rkStream,m_fExponent);
}
//----------------------------------------------------------------------------
StringTree* SpotLight::SaveStrings ()
{
StringTree* pkTree = new StringTree(4,0,1,0);
// strings
pkTree->SetString(0,MakeString(&ms_kRTTI,GetName()));
pkTree->SetString(1,MakeString("direction =",m_kDirection));
pkTree->SetString(2,MakeString("angle =",m_fAngle));
pkTree->SetString(3,MakeString("exponent =",m_fExponent));
// children
pkTree->SetChild(0,PointLight::SaveStrings());
return pkTree;
}
//----------------------------------------------------------------------------
int SpotLight::GetMemoryUsed () const
{
int iBaseSize = sizeof(SpotLight) - sizeof(PointLight);
int iTotalSize = iBaseSize + PointLight::GetMemoryUsed();
return iTotalSize;
}
//----------------------------------------------------------------------------
int SpotLight::GetDiskUsed () const
{
return PointLight::GetDiskUsed() +
sizeof(m_kDirection) +
sizeof(m_fAngle) +
sizeof(m_fExponent);
}
//----------------------------------------------------------------------------
| 36.056701 | 79 | 0.521658 | 1iyiwei |
1c0bc29f6f372f1a32d6571391dd1bcac5fb73da | 1,633 | hpp | C++ | Node/Software/ShellMMap.hpp | UofT-HPRC/FFIVE | 4bb17f9669b0c731fe23ea06de26a8921c708ab5 | [
"BSD-Source-Code"
] | 3 | 2021-08-17T11:07:32.000Z | 2022-01-14T15:52:23.000Z | Node/Software/ShellMMap.hpp | UofT-HPRC/FFIVE | 4bb17f9669b0c731fe23ea06de26a8921c708ab5 | [
"BSD-Source-Code"
] | null | null | null | Node/Software/ShellMMap.hpp | UofT-HPRC/FFIVE | 4bb17f9669b0c731fe23ea06de26a8921c708ab5 | [
"BSD-Source-Code"
] | null | null | null | #ifndef SHELL_MMAP_HPP
#define SHELL_MMAP_HPP
#include <iostream>
#include <cstdint>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include "ShellUtils.hpp"
namespace FPGA_SHELL
{
// Open /dev/mem, if not already done, to give access to physical addresses
int32_t OpenPhysical(int32_t fd)
{
if (fd == -1)
{
if ((fd = open( "/dev/mem", O_RDWR | O_SYNC)) == -1)
{
std::cout << "ERROR: Could not open \"/dev/mem\".\n";
PrintTrace();
}
}
return fd;
}
// Close /dev/mem to give access to physical addresses
void ClosePhysical(int32_t fd)
{
close (fd);
}
// Establish a virtual address mapping for the physical addresses starting at base, and
// extending by span bytes.
void* MapPhysical(int32_t fd, uint64_t base, uint32_t span)
{
void *virtual_base;
// Get a mapping from physical addresses to virtual addresses
virtual_base = mmap (NULL, span, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, base);
if (virtual_base == MAP_FAILED)
{
std::cout << "ERROR: mmap() failed.\n";
close (fd);
PrintTrace();
}
return virtual_base;
}
// Close the previously-opened virtual address mapping
int32_t UnmapPhysical(volatile void * virtual_base, uint32_t span)
{
if (munmap ((void *) virtual_base, span) != 0)
{
std::cout << "ERROR: munmap() failed.\n";
PrintTrace();
}
return 0;
}
}
#endif // SHELL_MMAP_HPP
| 25.515625 | 91 | 0.568279 | UofT-HPRC |
1c136acbf99428c3715e72a45f52aa31e837c7b2 | 3,461 | cpp | C++ | src/core/util/DenseFlagArray.cpp | Kelan0/WorldEngine | e76e7ff47278e837f4d1b9216773dd79eeee1b52 | [
"MIT"
] | null | null | null | src/core/util/DenseFlagArray.cpp | Kelan0/WorldEngine | e76e7ff47278e837f4d1b9216773dd79eeee1b52 | [
"MIT"
] | null | null | null | src/core/util/DenseFlagArray.cpp | Kelan0/WorldEngine | e76e7ff47278e837f4d1b9216773dd79eeee1b52 | [
"MIT"
] | null | null | null |
#include "DenseFlagArray.h"
#define BIT(bitIndex) (1 << (bitIndex))
#define SET_BIT(val, bitIndex, isSet) if (isSet) val |= BIT(bitIndex); else val &= ~BIT(bitIndex);
#define GET_BIT(val, bitIndex) (((val) >> (bitIndex)) & 1)
DenseFlagArray::DenseFlagArray():
m_size(0) {
}
DenseFlagArray::~DenseFlagArray() {
}
size_t DenseFlagArray::size() const {
return m_size;
}
size_t DenseFlagArray::capacity() const {
return m_data.capacity() * pack_bits;
}
void DenseFlagArray::clear() {
m_data.clear();
m_size = 0;
}
void DenseFlagArray::reserve(const size_t& capacity) {
m_data.reserve(capacity * pack_bits);
}
void DenseFlagArray::resize(const size_t& size, const bool& flag) {
PROFILE_SCOPE("DenseFlagArray::resize")
size_t packedSize = INT_DIV_CEIL(size, pack_bits);
if (packedSize != m_data.size())
m_data.resize(packedSize, flag ? TRUE_BITS : FALSE_BITS);
m_size = size;
}
void DenseFlagArray::ensureSize(const size_t& size, const bool& flag) {
if (m_size < size)
resize(size, flag);
}
void DenseFlagArray::expand(const size_t& index, const bool& flag) {
if (m_size <= index) {
size_t next = index + 1;
if (next >= capacity())
reserve(next + next / 2);
resize(next, flag);
}
}
bool DenseFlagArray::get(const size_t& index) const {
if (index >= size()) {
assert(false);
}
assert(index < size());
if constexpr (pack_bits == 1) {
return m_data[index];
} else {
return GET_BIT(m_data[index / pack_bits], index % pack_bits);
}
}
void DenseFlagArray::set(const size_t& index, const bool& flag) {
assert(index < size());
// ensureCapacity(index);
SET_BIT(m_data[index / pack_bits], index % pack_bits, flag);
}
void DenseFlagArray::set(const size_t& index, const size_t& count, const bool& flag) {
PROFILE_SCOPE("DenseFlagArray::set");
assert(index + count <= size());
if (count == 0) {
return;
}
if (count == 1) {
SET_BIT(m_data[index / pack_bits], index % pack_bits, flag);
return;
}
size_t firstPackIndex = index / pack_bits;
size_t firstBitIndex = index % pack_bits;
size_t lastPackIndex = (index + count) / pack_bits;
size_t lastBitIndex = (index + count) % pack_bits;
PROFILE_REGION("Set first unaligned bits")
if (firstBitIndex != 0) {
if (firstPackIndex == lastPackIndex) {
for (size_t i = firstBitIndex; i < lastBitIndex; ++i)
SET_BIT(m_data[firstPackIndex], i, flag);
lastBitIndex = 0;
} else {
for (size_t i = firstBitIndex; i < pack_bits; ++i)
SET_BIT(m_data[firstPackIndex], i, flag);
++firstPackIndex;
}
}
PROFILE_REGION("Set all aligned bits")
if (firstPackIndex != lastPackIndex)
memset(&m_data[firstPackIndex], flag ? TRUE_BITS : FALSE_BITS, (lastPackIndex - firstPackIndex) * sizeof(pack_t));
// for (size_t i = firstPackIndex; i != lastPackIndex; ++i)
// m_data[i] = flag ? TRUE_BITS : FALSE_BITS;
PROFILE_REGION("Set last unaligned bits")
for (size_t i = 0; i < lastBitIndex; ++i)
SET_BIT(m_data[lastPackIndex], i, flag);
}
bool DenseFlagArray::operator[](const size_t& index) const {
return get(index);
}
void DenseFlagArray::push_back(const bool& flag) {
size_t index = size();
expand(index);
set(index, flag);
}
| 26.419847 | 122 | 0.625253 | Kelan0 |
1c1374a5937184a0749c23e341dea52f0f75a73a | 8,431 | cpp | C++ | src/ObjectPool.cpp | 9chu/Moe.Core | 24fc7701fe8f4b70911fac18438b8f7557aa1773 | [
"MIT"
] | 29 | 2018-09-05T09:50:32.000Z | 2021-04-19T15:39:38.000Z | src/ObjectPool.cpp | 9chu/Moe.Core | 24fc7701fe8f4b70911fac18438b8f7557aa1773 | [
"MIT"
] | 1 | 2017-09-12T09:07:51.000Z | 2017-12-08T15:49:24.000Z | src/ObjectPool.cpp | 9chu/MOE.Core | 24fc7701fe8f4b70911fac18438b8f7557aa1773 | [
"MIT"
] | 2 | 2018-09-19T13:49:23.000Z | 2021-01-13T08:52:35.000Z | /**
* @file
* @author chu
* @date 2018/8/2
*/
#include <Moe.Core/ObjectPool.hpp>
using namespace std;
using namespace moe;
//////////////////////////////////////////////////////////////////////////////// Node
#ifndef NDEBUG
void ObjectPool::Node::Attach(Node* node)noexcept
{
assert(node);
Header.Prev = node;
Header.Next = node->Header.Next;
node->Header.Next = this;
if (Header.Next)
Header.Next->Header.Prev = this;
}
void ObjectPool::Node::Detach()noexcept
{
if (Header.Prev)
{
assert(Header.Prev->Header.Next == this);
Header.Prev->Header.Next = Header.Next;
}
if (Header.Next)
{
assert(Header.Next->Header.Prev == this);
Header.Next->Header.Prev = Header.Prev;
}
Header.Prev = Header.Next = nullptr;
}
#else
void ObjectPool::Node::Attach(Node* parent)noexcept
{
assert(parent);
Header.Next = parent->Header.Next;
parent->Header.Next = this;
}
void ObjectPool::Node::Detach(Node* parent)noexcept
{
assert(parent);
assert(parent->Header.Next == this);
parent->Header.Next = Header.Next;
Header.Next = nullptr;
}
#endif
//////////////////////////////////////////////////////////////////////////////// ObjectPool
namespace
{
size_t SizeToIndex(size_t size)noexcept
{
if (size <= ObjectPool::kSmallSizeThreshold)
return (size + (ObjectPool::kSmallSizeBlockSize - 1)) / ObjectPool::kSmallSizeBlockSize;
else if (size <= ObjectPool::kLargeSizeThreshold)
{
size -= ObjectPool::kSmallSizeThreshold;
return (size + (ObjectPool::kLargeSizeBlockSize - 1)) / ObjectPool::kLargeSizeBlockSize +
ObjectPool::kSmallSizeBlocks;
}
assert(false);
return 0;
}
}
ObjectPool* ObjectPool::GetPoolFromPointer(void* p)noexcept
{
if (!p)
return nullptr;
Node* n = reinterpret_cast<Node*>(static_cast<uint8_t*>(p) - offsetof(Node, Data));
assert(n->Header.Status == NodeStatus::Used);
assert(n->Header.Parent);
return n->Header.Parent->Pool;
}
void ObjectPool::Free(void* p)noexcept
{
if (!p)
return;
Node* n = reinterpret_cast<Node*>(static_cast<uint8_t*>(p) - offsetof(Node, Data));
assert(n->Header.Status == NodeStatus::Used);
assert(n->Header.Parent);
n->Header.Parent->Pool->InternalFree(n);
}
ObjectPool::ObjectPool()
{
m_stBuckets[0].NodeSize = 0;
for (unsigned i = 1; i <= kSmallSizeBlocks; ++i)
{
m_stBuckets[i].Pool = this;
m_stBuckets[i].NodeSize = i * kSmallSizeBlockSize;
}
for (unsigned i = kSmallSizeBlocks + 1; i < kTotalBlocks; ++i)
{
m_stBuckets[i].Pool = this;
m_stBuckets[i].NodeSize = (i - kSmallSizeBlocks) * kLargeSizeBlockSize + kSmallSizeThreshold;
}
}
ObjectPool::~ObjectPool()
{
CollectGarbage(); // 收集所有节点
// 检查内存泄漏
bool leak = false;
for (unsigned i = 0; i < CountOf(m_stBuckets); ++i)
{
auto& bucket = m_stBuckets[i];
#ifndef NDEBUG
auto p = bucket.UseList.Header.Next;
if (p)
{
while (p && m_pLeakReporter)
{
m_pLeakReporter(p->Data, bucket.NodeSize, p->Header.Context);
p = p->Header.Next;
}
leak = true;
}
#else
if (bucket.AllocatedCount)
{
if (m_pLeakReporter)
m_pLeakReporter(bucket.NodeSize, bucket.AllocatedCount - bucket.FreeCount);
leak = true;
}
#endif
}
assert(!leak);
MOE_UNUSED(leak);
}
size_t ObjectPool::GetAllocatedSize()const noexcept
{
size_t ret = 0;
for (unsigned i = 0; i < CountOf(m_stBuckets); ++i)
ret += m_stBuckets[i].AllocatedCount * m_stBuckets[i].NodeSize;
return ret;
}
size_t ObjectPool::GetFreeSize()const noexcept
{
size_t ret = 0;
for (unsigned i = 0; i < CountOf(m_stBuckets); ++i)
ret += m_stBuckets[i].FreeCount * m_stBuckets[i].NodeSize;
return ret;
}
size_t ObjectPool::CollectGarbage(unsigned factor, size_t maxFree)noexcept
{
factor = max<unsigned>(factor, 1);
size_t ret = 0;
auto i = CountOf(m_stBuckets);
while (i-- > 0)
{
auto& bucket = m_stBuckets[i];
if (bucket.FreeCount == 0)
{
assert(bucket.FreeList.Header.Next == nullptr);
continue;
}
size_t collects = bucket.FreeCount / factor;
for (unsigned j = 0; j < collects; ++j)
{
auto obj = bucket.FreeList.Header.Next;
assert(obj);
#ifndef NDEBUG
obj->Detach();
#else
obj->Detach(&bucket.FreeList);
#endif
::free(obj);
--bucket.FreeCount;
--bucket.AllocatedCount;
ret += bucket.NodeSize;
if (maxFree && ret >= maxFree)
return ret;
}
}
return ret;
}
#ifndef NDEBUG
void* ObjectPool::InternalAlloc(size_t sz, const AllocContext& context)
#else
void* ObjectPool::InternalAlloc(size_t sz)
#endif
{
Node* ret = nullptr;
sz = max<size_t>(sz, 1);
if (sz > kLargeSizeThreshold) // 直接从系统分配,并挂在大小为0的节点上
{
ret = reinterpret_cast<Node*>(::malloc(offsetof(Node, Data) + sz));
if (!ret)
throw bad_alloc();
ret->Header.Status = NodeStatus::Used;
ret->Header.Parent = &m_stBuckets[0];
#ifndef NDEBUG
ret->Header.Context = context;
ret->Attach(&m_stBuckets->UseList);
#else
ret->Header.Next = nullptr;
#endif
++m_stBuckets[0].AllocatedCount;
return static_cast<void*>(ret->Data);
}
// 获取对应的Bucket
auto index = SizeToIndex(sz);
assert(m_stBuckets[index].NodeSize >= sz);
Bucket& bucket = m_stBuckets[index];
if (bucket.FreeList.Header.Next) // 如果有空闲节点,就分配
{
assert(bucket.FreeCount > 0);
ret = bucket.FreeList.Header.Next;
#ifndef NDEBUG
ret->Detach();
#else
ret->Detach(&bucket.FreeList);
#endif
--bucket.FreeCount;
}
else
{
ret = reinterpret_cast<Node*>(::malloc(offsetof(Node, Data) + bucket.NodeSize));
if (!ret)
throw bad_alloc();
ret->Header.Parent = &bucket;
++bucket.AllocatedCount;
}
assert(ret);
ret->Header.Status = NodeStatus::Used;
#ifndef NDEBUG
ret->Header.Context = context;
ret->Attach(&bucket.UseList);
#else
ret->Header.Next = nullptr;
#endif
return static_cast<void*>(ret->Data);
}
#ifndef NDEBUG
void* ObjectPool::InternalRealloc(void* p, size_t sz, const AllocContext& context)
#else
void* ObjectPool::InternalRealloc(void* p, size_t sz)
#endif
{
if (!p) // 当传入的p为nullptr时,Realloc的行为和Alloc一致
#ifndef NDEBUG
return InternalAlloc(sz, context);
#else
return InternalAlloc(sz);
#endif
Node* n = reinterpret_cast<Node*>(static_cast<uint8_t*>(p) - offsetof(Node, Data));
assert(n->Header.Parent->Pool == this);
if (sz == 0) // 当大小为0,其行为和Free一致
{
InternalFree(n);
return nullptr;
}
auto nodeSize = n->Header.Parent->NodeSize;
if (nodeSize == 0) // 超大对象,调用系统的realloc
{
auto ret = static_cast<Node*>(::realloc(n, offsetof(Node, Data) + sz));
if (!ret)
throw bad_alloc();
return static_cast<void*>(ret->Data);
}
if (nodeSize >= sz) // 如果本身分配的内存就足够使用,则直接返回
return p;
// 这里,只能新分配一块内存(当bad_alloc发生时,不影响已分配的内存)
#ifndef NDEBUG
auto* np = InternalAlloc(sz, context);
#else
auto* np = InternalAlloc(sz);
#endif
memcpy(np, p, nodeSize);
// 内存拷贝完毕,释放老内存,返回新内存
InternalFree(n);
return np;
}
void ObjectPool::InternalFree(Node* p)noexcept
{
assert(p);
assert(p->Header.Parent->Pool == this);
p->Header.Status = NodeStatus::Free;
#ifndef NDEBUG
p->Detach();
#endif
Bucket& bucket = *p->Header.Parent;
if (bucket.NodeSize == 0) // 超大对象,直接释放
{
::free(p);
--bucket.AllocatedCount;
return;
}
// 回收到FreeList
p->Attach(&bucket.FreeList);
++bucket.FreeCount;
}
| 25.394578 | 102 | 0.56316 | 9chu |
1c140d3dbcbc615613735a575bfeef40d18ce949 | 2,535 | cpp | C++ | Seagull-Core/src/Platform/DirectX/DirectX12CommandList.cpp | ILLmew/Seagull-Engine | fb51b66812eca6b70ed0e35ecba091e9874b5bea | [
"MIT"
] | null | null | null | Seagull-Core/src/Platform/DirectX/DirectX12CommandList.cpp | ILLmew/Seagull-Engine | fb51b66812eca6b70ed0e35ecba091e9874b5bea | [
"MIT"
] | null | null | null | Seagull-Core/src/Platform/DirectX/DirectX12CommandList.cpp | ILLmew/Seagull-Engine | fb51b66812eca6b70ed0e35ecba091e9874b5bea | [
"MIT"
] | null | null | null | #include "sgpch.h"
#include "DirectX12CommandList.h"
#include "DirectX12RenderQueue.h"
#include "DirectXHelper.h"
#include "d3dx12.h"
namespace SG
{
DirectX12CommandList::DirectX12CommandList(ID3D12Device1* device, const Ref<DirectX12RenderQueue>& renderQueue)
{
ThrowIfFailed(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, renderQueue->GetCommandAllocatorNative(),
nullptr /* PSO */, IID_PPV_ARGS(m_CommandList.GetAddressOf())));
}
void DirectX12CommandList::ResourceBarrier(UINT numBarriers, ID3D12Resource* resource,
D3D12_RESOURCE_STATES stateBefore, D3D12_RESOURCE_STATES stateAfter) const noexcept
{
m_CommandList->ResourceBarrier(numBarriers,
&CD3DX12_RESOURCE_BARRIER::Transition(resource, stateBefore, stateAfter));
}
void DirectX12CommandList::ResourceBarrier(UINT numBarriers, const D3D12_RESOURCE_BARRIER* pBarriers) const noexcept
{
m_CommandList->ResourceBarrier(numBarriers, pBarriers);
}
void DirectX12CommandList::SetViewports(UINT num, const D3D12_VIEWPORT* viewport) const noexcept
{
m_CommandList->RSSetViewports(num, viewport);
}
void DirectX12CommandList::SetScissorRect(UINT num, const D3D12_RECT* rect) const noexcept
{
m_CommandList->RSSetScissorRects(num, rect);
}
void DirectX12CommandList::SetDescriptorHeaps(UINT numDescritorHeaps, ID3D12DescriptorHeap* const* ppHeaps)
{
m_CommandList->SetDescriptorHeaps(numDescritorHeaps, ppHeaps);
}
void DirectX12CommandList::ClearRtv(D3D12_CPU_DESCRIPTOR_HANDLE Rtv, const FLOAT* color, UINT numRects,
const D3D12_RECT* pRects) const noexcept
{
m_CommandList->ClearRenderTargetView(Rtv, color, numRects, pRects);
}
void DirectX12CommandList::ClearDsv(D3D12_CPU_DESCRIPTOR_HANDLE Dsv, D3D12_CLEAR_FLAGS clearFlags, FLOAT depth,
UINT8 stencil, UINT numRects, const D3D12_RECT* pRects) const noexcept
{
m_CommandList->ClearDepthStencilView(Dsv, clearFlags, depth, stencil, numRects, pRects);
}
void DirectX12CommandList::SetRenderTarget(UINT numRenderTargetDesc, const D3D12_CPU_DESCRIPTOR_HANDLE* Rtv,
bool RTsSingleHandleToDescriptorRange, const D3D12_CPU_DESCRIPTOR_HANDLE* Dsv) const noexcept
{
m_CommandList->OMSetRenderTargets(numRenderTargetDesc, Rtv, RTsSingleHandleToDescriptorRange, Dsv);
}
void DirectX12CommandList::Reset(ID3D12CommandAllocator* commandAllocator, ID3D12PipelineState* pipelineState) const
{
ThrowIfFailed(m_CommandList->Reset(commandAllocator, pipelineState));
}
void DirectX12CommandList::Close() const noexcept
{
m_CommandList->Close();
}
} | 35.704225 | 118 | 0.810651 | ILLmew |
1c149f33f40239012576dde0f10ec4b3223387f2 | 35,500 | cc | C++ | src/tag.cc | mavit/loudgain | 0ff67eec6cc2d37df1cd9d0bd95c5076604a23bc | [
"BSD-2-Clause"
] | 125 | 2019-07-09T18:28:32.000Z | 2022-03-21T03:35:09.000Z | src/tag.cc | mavit/loudgain | 0ff67eec6cc2d37df1cd9d0bd95c5076604a23bc | [
"BSD-2-Clause"
] | 40 | 2019-07-31T15:34:32.000Z | 2022-02-28T21:39:05.000Z | src/tag.cc | mavit/loudgain | 0ff67eec6cc2d37df1cd9d0bd95c5076604a23bc | [
"BSD-2-Clause"
] | 33 | 2019-08-04T18:35:54.000Z | 2022-03-21T03:49:50.000Z | /*
* Loudness normalizer based on the EBU R128 standard
*
* Copyright (c) 2014, Alessandro Ghedini
* All rights reserved.
* 2019-06-30 - Matthias C. Hormann
* - Tag format in accordance with ReplayGain 2.0 spec
* https://wiki.hydrogenaud.io/index.php?title=ReplayGain_2.0_specification
* - Add Ogg Vorbis file handling
* 2019-07-07 - v0.2.3 - Matthias C. Hormann
* - Write lowercase REPLAYGAIN_* tags to MP3 ID3v2, for incompatible players
* 2019-07-08 - v0.2.4 - Matthias C. Hormann
* - add -s e mode, writes extra tags (REPLAYGAIN_REFERENCE_LOUDNESS,
* REPLAYGAIN_TRACK_RANGE and REPLAYGAIN_ALBUM_RANGE)
* - add "-s l" mode (like "-s e" but uses LU/LUFS instead of dB)
* 2019-07-09 - v0.2.6 - Matthias C. Hormann
* - Add "-L" mode to force lowercase tags in MP3/ID3v2.
* 2019-07-10 - v0.2.7 - Matthias C. Hormann
* - Add "-S" mode to strip ID3v1/APEv2 tags from MP3 files.
* - Add "-I 3"/"-I 4" modes to select ID3v2 version to write.
* 2019-07-31 - v0.40 - Matthias C. Hormann
* - Add MP4 handling
* 2019-08-02 - v0.5.1 - Matthias C. Hormann
* - avoid unneccessary double file write on deleting+writing tags
* - make tag delete/write functions return true on success, false otherwise
* 2019-08-06 - v0.5.3 - Matthias C. Hormann
* - Add support for Opus (.opus) files.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <taglib.h>
#define TAGLIB_VERSION (TAGLIB_MAJOR_VERSION * 10000 \
+ TAGLIB_MINOR_VERSION * 100 \
+ TAGLIB_PATCH_VERSION)
#include <textidentificationframe.h>
#include <mpegfile.h>
#include <id3v2tag.h>
#include <apetag.h>
#include <flacfile.h>
#include <vorbisfile.h>
#include <oggflacfile.h>
#include <speexfile.h>
#include <xiphcomment.h>
#include <mp4file.h>
#include <opusfile.h>
#include <asffile.h>
// #include <rifffile.h>
#include <wavfile.h>
#include <aifffile.h>
#include <wavpackfile.h>
#include <apefile.h>
#include "scan.h"
#include "tag.h"
#include "printf.h"
// define possible replaygain tags
enum RG_ENUM {
RG_TRACK_GAIN,
RG_TRACK_PEAK,
RG_TRACK_RANGE,
RG_ALBUM_GAIN,
RG_ALBUM_PEAK,
RG_ALBUM_RANGE,
RG_REFERENCE_LOUDNESS
};
static const char *RG_STRING_UPPER[] = {
"REPLAYGAIN_TRACK_GAIN",
"REPLAYGAIN_TRACK_PEAK",
"REPLAYGAIN_TRACK_RANGE",
"REPLAYGAIN_ALBUM_GAIN",
"REPLAYGAIN_ALBUM_PEAK",
"REPLAYGAIN_ALBUM_RANGE",
"REPLAYGAIN_REFERENCE_LOUDNESS"
};
static const char *RG_STRING_LOWER[] = {
"replaygain_track_gain",
"replaygain_track_peak",
"replaygain_track_range",
"replaygain_album_gain",
"replaygain_album_peak",
"replaygain_album_range",
"replaygain_reference_loudness"
};
// this is where we store the RG tags in MP4/M4A files
static const char *RG_ATOM = "----:com.apple.iTunes:";
/*** MP3 ****/
static void tag_add_txxx(TagLib::ID3v2::Tag *tag, char *name, char *value) {
TagLib::ID3v2::UserTextIdentificationFrame *frame =
new TagLib::ID3v2::UserTextIdentificationFrame;
frame -> setDescription(name);
frame -> setText(value);
tag -> addFrame(frame);
}
void tag_remove_mp3(TagLib::ID3v2::Tag *tag) {
TagLib::ID3v2::FrameList::Iterator it;
TagLib::ID3v2::FrameList frames = tag -> frameList("TXXX");
for (it = frames.begin(); it != frames.end(); ++it) {
TagLib::ID3v2::UserTextIdentificationFrame *frame =
dynamic_cast<TagLib::ID3v2::UserTextIdentificationFrame*>(*it);
// this removes all variants of upper-/lower-/mixed-case tags
if (frame && frame -> fieldList().size() >= 2) {
TagLib::String desc = frame -> description().upper();
// also remove (old) reference loudness, it might be wrong after recalc
if ((desc == RG_STRING_UPPER[RG_TRACK_GAIN]) ||
(desc == RG_STRING_UPPER[RG_TRACK_PEAK]) ||
(desc == RG_STRING_UPPER[RG_TRACK_RANGE]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_GAIN]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_PEAK]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_RANGE]) ||
(desc == RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]))
tag -> removeFrame(frame);
}
}
}
// Even if the ReplayGain 2 standard proposes replaygain tags to be uppercase,
// unfortunately some players only respect the lowercase variant (still).
// So we use the "lowercase" flag to switch.
bool tag_write_mp3(scan_result *scan, bool do_album, char mode, char *unit,
bool lowercase, bool strip, int id3v2version) {
char value[2048];
const char **RG_STRING = RG_STRING_UPPER;
if (lowercase) {
RG_STRING = RG_STRING_LOWER;
}
TagLib::MPEG::File f(scan -> file);
TagLib::ID3v2::Tag *tag = f.ID3v2Tag(true);
// remove old tags before writing new ones
tag_remove_mp3(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_GAIN]), value);
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_PEAK]), value);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_GAIN]), value);
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_PEAK]), value);
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_REFERENCE_LOUDNESS]), value);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_RANGE]), value);
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_RANGE]), value);
}
}
// work around bug taglib/taglib#913: strip APE before ID3v1
if (strip)
f.strip(TagLib::MPEG::File::APE);
#if TAGLIB_VERSION >= 11200
return f.save(TagLib::MPEG::File::ID3v2,
strip ? TagLib::MPEG::File::StripOthers : TagLib::MPEG::File::StripNone,
id3v2version == 3 ? TagLib::ID3v2::v3 : TagLib::ID3v2::v4);
#else
return f.save(TagLib::MPEG::File::ID3v2, strip, id3v2version);
#endif
}
bool tag_clear_mp3(scan_result *scan, bool strip, int id3v2version) {
TagLib::MPEG::File f(scan -> file);
TagLib::ID3v2::Tag *tag = f.ID3v2Tag(true);
tag_remove_mp3(tag);
// work around bug taglib/taglib#913: strip APE before ID3v1
if (strip)
f.strip(TagLib::MPEG::File::APE);
#if TAGLIB_VERSION >= 11200
return f.save(TagLib::MPEG::File::ID3v2,
strip ? TagLib::MPEG::File::StripOthers : TagLib::MPEG::File::StripNone,
id3v2version == 3 ? TagLib::ID3v2::v3 : TagLib::ID3v2::v4);
#else
return f.save(TagLib::MPEG::File::ID3v2, strip, id3v2version);
#endif
}
/*** FLAC ****/
void tag_remove_flac(TagLib::Ogg::XiphComment *tag) {
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_GAIN]);
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_PEAK]);
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_RANGE]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_GAIN]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_PEAK]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_RANGE]);
tag -> removeFields(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]);
}
bool tag_write_flac(scan_result *scan, bool do_album, char mode, char *unit) {
char value[2048];
TagLib::FLAC::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.xiphComment(true);
// remove old tags before writing new ones
tag_remove_flac(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag -> addField(RG_STRING_UPPER[RG_TRACK_GAIN], value);
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag -> addField(RG_STRING_UPPER[RG_TRACK_PEAK], value);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag -> addField(RG_STRING_UPPER[RG_ALBUM_GAIN], value);
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag -> addField(RG_STRING_UPPER[RG_ALBUM_PEAK], value);
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag -> addField(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS], value);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag -> addField(RG_STRING_UPPER[RG_TRACK_RANGE], value);
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag -> addField(RG_STRING_UPPER[RG_ALBUM_RANGE], value);
}
}
return f.save();
}
bool tag_clear_flac(scan_result *scan) {
TagLib::FLAC::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.xiphComment(true);
tag_remove_flac(tag);
return f.save();
}
/*** Ogg (Vorbis, FLAC, Speex, Opus) ****/
void tag_remove_ogg(TagLib::Ogg::XiphComment *tag) {
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_GAIN]);
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_PEAK]);
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_RANGE]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_GAIN]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_PEAK]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_RANGE]);
tag -> removeFields(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]);
}
void tag_make_ogg(scan_result *scan, bool do_album, char mode, char *unit,
TagLib::Ogg::XiphComment *tag) {
char value[2048];
// remove old tags before writing new ones
tag_remove_ogg(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag -> addField(RG_STRING_UPPER[RG_TRACK_GAIN], value);
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag -> addField(RG_STRING_UPPER[RG_TRACK_PEAK], value);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag -> addField(RG_STRING_UPPER[RG_ALBUM_GAIN], value);
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag -> addField(RG_STRING_UPPER[RG_ALBUM_PEAK], value);
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag -> addField(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS], value);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag -> addField(RG_STRING_UPPER[RG_TRACK_RANGE], value);
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag -> addField(RG_STRING_UPPER[RG_ALBUM_RANGE], value);
}
}
}
/*** Ogg: Ogg Vorbis ***/
bool tag_write_ogg_vorbis(scan_result *scan, bool do_album, char mode, char *unit) {
TagLib::Ogg::Vorbis::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
tag_make_ogg(scan, do_album, mode, unit, tag);
return f.save();
}
bool tag_clear_ogg_vorbis(scan_result *scan) {
TagLib::Ogg::Vorbis::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
tag_remove_ogg(tag);
return f.save();
}
/*** Ogg: Ogg FLAC ***/
bool tag_write_ogg_flac(scan_result *scan, bool do_album, char mode, char *unit) {
TagLib::Ogg::FLAC::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
tag_make_ogg(scan, do_album, mode, unit, tag);
return f.save();
}
bool tag_clear_ogg_flac(scan_result *scan) {
TagLib::Ogg::FLAC::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
tag_remove_ogg(tag);
return f.save();
}
/*** Ogg: Ogg Speex ***/
bool tag_write_ogg_speex(scan_result *scan, bool do_album, char mode, char *unit) {
TagLib::Ogg::Speex::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
tag_make_ogg(scan, do_album, mode, unit, tag);
return f.save();
}
bool tag_clear_ogg_speex(scan_result *scan) {
TagLib::Ogg::Speex::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
tag_remove_ogg(tag);
return f.save();
}
/*** Ogg: Opus ****/
// Opus Notes:
//
// 1. Opus ONLY uses R128_TRACK_GAIN and (optionally) R128_ALBUM_GAIN
// as an ADDITIONAL offset to the header's 'output_gain'.
// 2. Encoders and muxes set 'output_gain' to zero, so a non-zero 'output_gain' in
// the header i supposed to be a change AFTER encoding/muxing.
// 3. We assume that FFmpeg's avformat does already apply 'output_gain' (???)
// so we get get pre-gained data and only have to calculate the difference.
// 4. Opus adheres to EBU-R128, so the loudness reference is ALWAYS -23 LUFS.
// This means we have to adapt for possible `-d n` (`--pregain=n`) changes.
// This also means players have to add an extra +5 dB to reach the loudness
// ReplayGain 2.0 prescribes (-18 LUFS).
// 5. Opus R128_* tags use ASCII-encoded Q7.8 numbers with max. 6 places including
// the minus sign, and no unit.
// See https://en.wikipedia.org/wiki/Q_(number_format)
// 6. RFC 7845 states: "To avoid confusion with multiple normalization schemes, an
// Opus comment header SHOULD NOT contain any of the REPLAYGAIN_TRACK_GAIN,
// REPLAYGAIN_TRACK_PEAK, REPLAYGAIN_ALBUM_GAIN, or REPLAYGAIN_ALBUM_PEAK tags, […]"
// So we remove REPLAYGAIN_* tags if any are present.
// 7. RFC 7845 states: "Peak normalizations are difficult to calculate reliably
// for lossy codecs because of variation in excursion heights due to decoder
// differences. In the authors' investigations, they were not applied
// consistently or broadly enough to merit inclusion here."
// So there are NO "Peak" type tags. The (oversampled) true peak levels that
// libebur128 calculates for us are STILL used for clipping prevention if so
// requested. They are also shown in the output, just not stored into tags.
int gain_to_q78num(double gain) {
// convert float to Q7.8 number: Q = round(f * 2^8)
return (int) round(gain * 256.0); // 2^8 = 256
}
void tag_remove_ogg_opus(TagLib::Ogg::XiphComment *tag) {
// RFC 7845 states:
// To avoid confusion with multiple normalization schemes, an Opus
// comment header SHOULD NOT contain any of the REPLAYGAIN_TRACK_GAIN,
// REPLAYGAIN_TRACK_PEAK, REPLAYGAIN_ALBUM_GAIN, or
// REPLAYGAIN_ALBUM_PEAK tags, […]"
// so we remove these if present
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_GAIN]);
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_PEAK]);
tag -> removeFields(RG_STRING_UPPER[RG_TRACK_RANGE]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_GAIN]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_PEAK]);
tag -> removeFields(RG_STRING_UPPER[RG_ALBUM_RANGE]);
tag -> removeFields(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]);
tag -> removeFields("R128_TRACK_GAIN");
tag -> removeFields("R128_ALBUM_GAIN");
}
bool tag_write_ogg_opus(scan_result *scan, bool do_album, char mode, char *unit) {
char value[2048];
TagLib::Ogg::Opus::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
// remove old tags before writing new ones
tag_remove_ogg_opus(tag);
snprintf(value, sizeof(value), "%d", gain_to_q78num(scan -> track_gain));
tag -> addField("R128_TRACK_GAIN", value);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%d", gain_to_q78num(scan -> album_gain));
tag -> addField("R128_ALBUM_GAIN", value);
}
// extra tags mode -s e or -s l
// no extra tags allowed in Opus
return f.save();
}
bool tag_clear_ogg_opus(scan_result *scan) {
TagLib::Ogg::Opus::File f(scan -> file);
TagLib::Ogg::XiphComment *tag = f.tag();
tag_remove_ogg_opus(tag);
return f.save();
}
/*** MP4 ****/
// build tagging key from RG_ATOM and REPLAYGAIN_* string
TagLib::String tagname(TagLib::String key) {
TagLib::String res = RG_ATOM;
return res.append(key);
}
void tag_remove_mp4(TagLib::MP4::Tag *tag) {
TagLib::String desc;
#if TAGLIB_VERSION >= 11200
TagLib::MP4::ItemMap items = tag->itemMap();
for(TagLib::MP4::ItemMap::Iterator item = items.begin();
item != items.end(); ++item)
#else
TagLib::MP4::ItemListMap &items = tag->itemListMap();
for(TagLib::MP4::ItemListMap::Iterator item = items.begin();
item != items.end(); ++item)
#endif
{
desc = item->first.upper();
if ((desc == tagname(RG_STRING_UPPER[RG_TRACK_GAIN]).upper()) ||
(desc == tagname(RG_STRING_UPPER[RG_TRACK_PEAK]).upper()) ||
(desc == tagname(RG_STRING_UPPER[RG_TRACK_RANGE]).upper()) ||
(desc == tagname(RG_STRING_UPPER[RG_ALBUM_GAIN]).upper()) ||
(desc == tagname(RG_STRING_UPPER[RG_ALBUM_PEAK]).upper()) ||
(desc == tagname(RG_STRING_UPPER[RG_ALBUM_RANGE]).upper()) ||
(desc == tagname(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]).upper()))
tag -> removeItem(item->first);
}
}
bool tag_write_mp4(scan_result *scan, bool do_album, char mode, char *unit,
bool lowercase) {
char value[2048];
const char **RG_STRING = RG_STRING_UPPER;
if (lowercase) {
RG_STRING = RG_STRING_LOWER;
}
TagLib::MP4::File f(scan -> file);
TagLib::MP4::Tag *tag = f.tag();
// remove old tags before writing new ones
tag_remove_mp4(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag -> setItem(tagname(RG_STRING[RG_TRACK_GAIN]), TagLib::StringList(value));
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag -> setItem(tagname(RG_STRING[RG_TRACK_PEAK]), TagLib::StringList(value));
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag -> setItem(tagname(RG_STRING[RG_ALBUM_GAIN]), TagLib::StringList(value));
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag -> setItem(tagname(RG_STRING[RG_ALBUM_PEAK]), TagLib::StringList(value));
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag -> setItem(tagname(RG_STRING[RG_REFERENCE_LOUDNESS]), TagLib::StringList(value));
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag -> setItem(tagname(RG_STRING[RG_TRACK_RANGE]), TagLib::StringList(value));
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag -> setItem(tagname(RG_STRING[RG_ALBUM_RANGE]), TagLib::StringList(value));
}
}
return f.save();
}
bool tag_clear_mp4(scan_result *scan) {
TagLib::MP4::File f(scan -> file);
TagLib::MP4::Tag *tag = f.tag();
tag_remove_mp4(tag);
return f.save();
}
/*** ASF/WMA ****/
void tag_remove_asf(TagLib::ASF::Tag *tag) {
TagLib::String desc;
TagLib::ASF::AttributeListMap &items = tag->attributeListMap();
for(TagLib::ASF::AttributeListMap::Iterator item = items.begin();
item != items.end(); ++item)
{
desc = item->first.upper();
if ((desc == RG_STRING_UPPER[RG_TRACK_GAIN]) ||
(desc == RG_STRING_UPPER[RG_TRACK_PEAK]) ||
(desc == RG_STRING_UPPER[RG_TRACK_RANGE]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_GAIN]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_PEAK]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_RANGE]) ||
(desc == RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]))
tag -> removeItem(item->first);
}
}
bool tag_write_asf(scan_result *scan, bool do_album, char mode, char *unit,
bool lowercase) {
char value[2048];
const char **RG_STRING = RG_STRING_UPPER;
if (lowercase) {
RG_STRING = RG_STRING_LOWER;
}
TagLib::ASF::File f(scan -> file);
TagLib::ASF::Tag *tag = f.tag();
// remove old tags before writing new ones
tag_remove_asf(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag -> setAttribute(RG_STRING[RG_TRACK_GAIN], TagLib::String(value));
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag -> setAttribute(RG_STRING[RG_TRACK_PEAK], TagLib::String(value));
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag -> setAttribute(RG_STRING[RG_ALBUM_GAIN], TagLib::String(value));
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag -> setAttribute(RG_STRING[RG_ALBUM_PEAK], TagLib::String(value));
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag -> setAttribute(RG_STRING[RG_REFERENCE_LOUDNESS], TagLib::String(value));
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag -> setAttribute(RG_STRING[RG_TRACK_RANGE], TagLib::String(value));
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag -> setAttribute(RG_STRING[RG_ALBUM_RANGE], TagLib::String(value));
}
}
return f.save();
}
bool tag_clear_asf(scan_result *scan) {
TagLib::ASF::File f(scan -> file);
TagLib::ASF::Tag *tag = f.tag();
tag_remove_asf(tag);
return f.save();
}
/*** WAV ****/
void tag_remove_wav(TagLib::ID3v2::Tag *tag) {
TagLib::ID3v2::FrameList::Iterator it;
TagLib::ID3v2::FrameList frames = tag -> frameList("TXXX");
for (it = frames.begin(); it != frames.end(); ++it) {
TagLib::ID3v2::UserTextIdentificationFrame *frame =
dynamic_cast<TagLib::ID3v2::UserTextIdentificationFrame*>(*it);
// this removes all variants of upper-/lower-/mixed-case tags
if (frame && frame -> fieldList().size() >= 2) {
TagLib::String desc = frame -> description().upper();
// also remove (old) reference loudness, it might be wrong after recalc
if ((desc == RG_STRING_UPPER[RG_TRACK_GAIN]) ||
(desc == RG_STRING_UPPER[RG_TRACK_PEAK]) ||
(desc == RG_STRING_UPPER[RG_TRACK_RANGE]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_GAIN]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_PEAK]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_RANGE]) ||
(desc == RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]))
tag -> removeFrame(frame);
}
}
}
// Experimental WAV file tagging within an "ID3 " chunk
bool tag_write_wav(scan_result *scan, bool do_album, char mode, char *unit,
bool lowercase, bool strip, int id3v2version) {
char value[2048];
const char **RG_STRING = RG_STRING_UPPER;
if (lowercase) {
RG_STRING = RG_STRING_LOWER;
}
TagLib::RIFF::WAV::File f(scan -> file);
TagLib::ID3v2::Tag *tag = f.ID3v2Tag();
// remove old tags before writing new ones
tag_remove_wav(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_GAIN]), value);
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_PEAK]), value);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_GAIN]), value);
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_PEAK]), value);
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_REFERENCE_LOUDNESS]), value);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_RANGE]), value);
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_RANGE]), value);
}
}
// no stripping
#if TAGLIB_VERSION >= 11200
return f.save(TagLib::RIFF::WAV::File::AllTags,
TagLib::RIFF::WAV::File::StripNone,
id3v2version == 3 ? TagLib::ID3v2::v3 : TagLib::ID3v2::v4);
#else
return f.save(TagLib::RIFF::WAV::File::AllTags, false, id3v2version);
#endif
}
bool tag_clear_wav(scan_result *scan, bool strip, int id3v2version) {
TagLib::RIFF::WAV::File f(scan -> file);
TagLib::ID3v2::Tag *tag = f.ID3v2Tag();
tag_remove_wav(tag);
// no stripping
#if TAGLIB_VERSION >= 11200
return f.save(TagLib::RIFF::WAV::File::AllTags,
TagLib::RIFF::WAV::File::StripNone,
id3v2version == 3 ? TagLib::ID3v2::v3 : TagLib::ID3v2::v4);
#else
return f.save(TagLib::RIFF::WAV::File::AllTags, false, id3v2version);
#endif
}
/*** AIFF ****/
// id3v2version and strip currently unimplemented since no TagLib support
void tag_remove_aiff(TagLib::ID3v2::Tag *tag) {
TagLib::ID3v2::FrameList::Iterator it;
TagLib::ID3v2::FrameList frames = tag -> frameList("TXXX");
for (it = frames.begin(); it != frames.end(); ++it) {
TagLib::ID3v2::UserTextIdentificationFrame *frame =
dynamic_cast<TagLib::ID3v2::UserTextIdentificationFrame*>(*it);
// this removes all variants of upper-/lower-/mixed-case tags
if (frame && frame -> fieldList().size() >= 2) {
TagLib::String desc = frame -> description().upper();
// also remove (old) reference loudness, it might be wrong after recalc
if ((desc == RG_STRING_UPPER[RG_TRACK_GAIN]) ||
(desc == RG_STRING_UPPER[RG_TRACK_PEAK]) ||
(desc == RG_STRING_UPPER[RG_TRACK_RANGE]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_GAIN]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_PEAK]) ||
(desc == RG_STRING_UPPER[RG_ALBUM_RANGE]) ||
(desc == RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]))
tag -> removeFrame(frame);
}
}
}
// Experimental AIFF file tagging within an "ID3 " chunk
bool tag_write_aiff(scan_result *scan, bool do_album, char mode, char *unit,
bool lowercase, bool strip, int id3v2version) {
char value[2048];
const char **RG_STRING = RG_STRING_UPPER;
if (lowercase) {
RG_STRING = RG_STRING_LOWER;
}
TagLib::RIFF::AIFF::File f(scan -> file);
TagLib::ID3v2::Tag *tag = f.tag();
// remove old tags before writing new ones
tag_remove_aiff(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_GAIN]), value);
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_PEAK]), value);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_GAIN]), value);
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_PEAK]), value);
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_REFERENCE_LOUDNESS]), value);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_TRACK_RANGE]), value);
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag_add_txxx(tag, const_cast<char *>(RG_STRING[RG_ALBUM_RANGE]), value);
}
}
// no stripping
#if TAGLIB_VERSION >= 11200
return f.save(id3v2version == 3 ? TagLib::ID3v2::v3 : TagLib::ID3v2::v4);
#else
return f.save();
#endif
}
bool tag_clear_aiff(scan_result *scan, bool strip, int id3v2version) {
TagLib::RIFF::AIFF::File f(scan -> file);
TagLib::ID3v2::Tag *tag = f.tag();
tag_remove_aiff(tag);
// no stripping
#if TAGLIB_VERSION >= 11200
return f.save(id3v2version == 3 ? TagLib::ID3v2::v3 : TagLib::ID3v2::v4);
#else
return f.save();
#endif
}
/*** WavPack ***/
// We COULD also use ID3 tags, but we stick with APEv2 tags,
// since that is the native format.
// APEv2 tags can be mixed case, but they should be read case-insensitively,
// so we currently ignore -L (--lowercase) and only write uppercase tags.
// TagLib handles APE case-insensitively and uses only UPPERCASE keys.
// Existing ID3v2 tags can be removed by using -S (--striptags).
void tag_remove_wavpack(TagLib::APE::Tag *tag) {
tag -> removeItem(RG_STRING_UPPER[RG_TRACK_GAIN]);
tag -> removeItem(RG_STRING_UPPER[RG_TRACK_PEAK]);
tag -> removeItem(RG_STRING_UPPER[RG_TRACK_RANGE]);
tag -> removeItem(RG_STRING_UPPER[RG_ALBUM_GAIN]);
tag -> removeItem(RG_STRING_UPPER[RG_ALBUM_PEAK]);
tag -> removeItem(RG_STRING_UPPER[RG_ALBUM_RANGE]);
tag -> removeItem(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]);
}
bool tag_write_wavpack(scan_result *scan, bool do_album, char mode, char *unit,
bool lowercase, bool strip) {
char value[2048];
const char **RG_STRING = RG_STRING_UPPER;
// ignore lowercase for now: CAN be written but keys should be read case-insensitively
// if (lowercase) {
// RG_STRING = RG_STRING_LOWER;
// }
TagLib::WavPack::File f(scan -> file);
TagLib::APE::Tag *tag = f.APETag(true); // create if none exists
// remove old tags before writing new ones
tag_remove_wavpack(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag -> addValue(RG_STRING[RG_TRACK_GAIN], TagLib::String(value), true);
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag -> addValue(RG_STRING[RG_TRACK_PEAK], TagLib::String(value), true);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag -> addValue(RG_STRING[RG_ALBUM_GAIN], TagLib::String(value), true);
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag -> addValue(RG_STRING[RG_ALBUM_PEAK], TagLib::String(value), true);
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag -> addValue(RG_STRING[RG_REFERENCE_LOUDNESS], TagLib::String(value), true);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag -> addValue(RG_STRING[RG_TRACK_RANGE], TagLib::String(value), true);
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag -> addValue(RG_STRING[RG_ALBUM_RANGE], TagLib::String(value), true);
}
}
if (strip)
f.strip(TagLib::WavPack::File::TagTypes::ID3v1);
return f.save();
}
bool tag_clear_wavpack(scan_result *scan, bool strip) {
TagLib::WavPack::File f(scan -> file);
TagLib::APE::Tag *tag = f.APETag(true); // create if none exists
tag_remove_wavpack(tag);
if (strip)
f.strip(TagLib::WavPack::File::TagTypes::ID3v1);
return f.save();
}
/*** APE (Monkey’s Audio) ***/
// We COULD also use ID3 tags, but we stick with APEv2 tags,
// since that is the native format.
// APEv2 tags can be mixed case, but they should be read case-insensitively,
// so we currently ignore -L (--lowercase) and only write uppercase tags.
// TagLib handles APE case-insensitively and uses only UPPERCASE keys.
// Existing ID3 tags can be removed by using -S (--striptags).
void tag_remove_ape(TagLib::APE::Tag *tag) {
tag -> removeItem(RG_STRING_UPPER[RG_TRACK_GAIN]);
tag -> removeItem(RG_STRING_UPPER[RG_TRACK_PEAK]);
tag -> removeItem(RG_STRING_UPPER[RG_TRACK_RANGE]);
tag -> removeItem(RG_STRING_UPPER[RG_ALBUM_GAIN]);
tag -> removeItem(RG_STRING_UPPER[RG_ALBUM_PEAK]);
tag -> removeItem(RG_STRING_UPPER[RG_ALBUM_RANGE]);
tag -> removeItem(RG_STRING_UPPER[RG_REFERENCE_LOUDNESS]);
}
bool tag_write_ape(scan_result *scan, bool do_album, char mode, char *unit,
bool lowercase, bool strip) {
char value[2048];
const char **RG_STRING = RG_STRING_UPPER;
// ignore lowercase for now: CAN be written but keys should be read case-insensitively
// if (lowercase) {
// RG_STRING = RG_STRING_LOWER;
// }
TagLib::APE::File f(scan -> file);
TagLib::APE::Tag *tag = f.APETag(true); // create if none exists
// remove old tags before writing new ones
tag_remove_ape(tag);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_gain, unit);
tag -> addValue(RG_STRING[RG_TRACK_GAIN], TagLib::String(value), true);
snprintf(value, sizeof(value), "%.6f", scan -> track_peak);
tag -> addValue(RG_STRING[RG_TRACK_PEAK], TagLib::String(value), true);
// Only write album tags if in album mode (would be zero otherwise)
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_gain, unit);
tag -> addValue(RG_STRING[RG_ALBUM_GAIN], TagLib::String(value), true);
snprintf(value, sizeof(value), "%.6f", scan -> album_peak);
tag -> addValue(RG_STRING[RG_ALBUM_PEAK], TagLib::String(value), true);
}
// extra tags mode -s e or -s l
if (mode == 'e' || mode == 'l') {
snprintf(value, sizeof(value), "%.2f LUFS", scan -> loudness_reference);
tag -> addValue(RG_STRING[RG_REFERENCE_LOUDNESS], TagLib::String(value), true);
snprintf(value, sizeof(value), "%.2f %s", scan -> track_loudness_range, unit);
tag -> addValue(RG_STRING[RG_TRACK_RANGE], TagLib::String(value), true);
if (do_album) {
snprintf(value, sizeof(value), "%.2f %s", scan -> album_loudness_range, unit);
tag -> addValue(RG_STRING[RG_ALBUM_RANGE], TagLib::String(value), true);
}
}
if (strip)
f.strip(TagLib::APE::File::TagTypes::ID3v1);
return f.save();
}
bool tag_clear_ape(scan_result *scan, bool strip) {
TagLib::WavPack::File f(scan -> file);
TagLib::APE::Tag *tag = f.APETag(true); // create if none exists
tag_remove_ape(tag);
if (strip)
f.strip(TagLib::WavPack::File::TagTypes::ID3v1);
return f.save();
}
| 34.466019 | 89 | 0.68107 | mavit |
1c15e45d2310aaee410919816d445b997d345c38 | 990 | cpp | C++ | design_pattern/2_Structural_Patterns/2.3_CompositePattern/main.cpp | guangjung/linux_cplusplus | 3000303c6680db17715c4802fd05c84a4ce84c1e | [
"MIT"
] | null | null | null | design_pattern/2_Structural_Patterns/2.3_CompositePattern/main.cpp | guangjung/linux_cplusplus | 3000303c6680db17715c4802fd05c84a4ce84c1e | [
"MIT"
] | null | null | null | design_pattern/2_Structural_Patterns/2.3_CompositePattern/main.cpp | guangjung/linux_cplusplus | 3000303c6680db17715c4802fd05c84a4ce84c1e | [
"MIT"
] | null | null | null |
//https://blog.csdn.net/liang19890820/article/details/71240662
//main.cpp
#include "composite.h"
#include "leaf.h"
int main()
{
// 创建一个树形结构
// 创建根节点
Composite *pRoot = new Composite("江湖公司(任我行)");
// 创建分支
Composite *pDepart1 = new Composite("日月神教(东方不败)");
pDepart1->Add(new Leaf("光明左使(向问天)"));
pDepart1->Add(new Leaf("光明右使(曲洋)"));
pRoot->Add(pDepart1);
Composite *pDepart2 = new Composite("五岳剑派(左冷蝉)");
pDepart2->Add(new Leaf("嵩山(左冷蝉)"));
pDepart2->Add(new Leaf("衡山(莫大)"));
pDepart2->Add(new Leaf("华山(岳不群)"));
pDepart2->Add(new Leaf("泰山(天门道长)"));
pDepart2->Add(new Leaf("恒山(定闲师太)"));
pRoot->Add(pDepart2);
// 添加和删除叶子
pRoot->Add(new Leaf("少林(方证大师)"));
pRoot->Add(new Leaf("武当(冲虚道长)"));
Component *pLeaf = new Leaf("青城(余沧海)");
pRoot->Add(pLeaf);
// 小丑,直接裁掉
pRoot->Remove(pLeaf);
// 递归地显示组织架构
pRoot->Operation(1);
// 删除分配的内存
SAFE_DELETE(pRoot);
//getchar();
return 0;
}
| 21.521739 | 63 | 0.590909 | guangjung |
1c1dbe3a713c269519a286b0765fcf6c0b2034bc | 329 | cpp | C++ | test/Test.cpp | mzh19940817/MyAllocator | 5ff72b13775caf76cd30cc232dcd9542427f4ea3 | [
"MIT"
] | null | null | null | test/Test.cpp | mzh19940817/MyAllocator | 5ff72b13775caf76cd30cc232dcd9542427f4ea3 | [
"MIT"
] | null | null | null | test/Test.cpp | mzh19940817/MyAllocator | 5ff72b13775caf76cd30cc232dcd9542427f4ea3 | [
"MIT"
] | null | null | null | #include "MyAllocator.h"
#include <vector>
#include "gtest/gtest.h"
struct MyAllocatorTest : testing::Test
{
};
TEST_F(MyAllocatorTest, test_for_my_allocator)
{
int arr[3] {1, 2, 3};
std::vector<int, MA::allocator<int>> vec{arr, arr + 3};
ASSERT_EQ(1, vec[0]);
ASSERT_EQ(2, vec[1]);
ASSERT_EQ(3, vec[2]);
}
| 19.352941 | 59 | 0.644377 | mzh19940817 |
1c1edeb88af89469bc4a2daa83fc3fd7e244ed21 | 483 | cpp | C++ | Activities With Pointers/4.cpp | SauloCav/C-and-Cpp-Experiments | c71d9a4ace958eb1248ddd9daf288b5b8fb12d6d | [
"MIT"
] | null | null | null | Activities With Pointers/4.cpp | SauloCav/C-and-Cpp-Experiments | c71d9a4ace958eb1248ddd9daf288b5b8fb12d6d | [
"MIT"
] | null | null | null | Activities With Pointers/4.cpp | SauloCav/C-and-Cpp-Experiments | c71d9a4ace958eb1248ddd9daf288b5b8fb12d6d | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
int main(){
int *a, *b, *c, d=12, e=4, f=0;
a=&d;
b=&e;
c=&f;
*a=5;
*c=1;
++*c;
(*a)+=10;
*b=*a;
c=b;
*a=25;
*c=3;
printf("a=%d\n", a);
printf("b=%d\n", b);
printf("c=%d\n", c);
printf("d=%d\n", d);
printf("e=%d\n", e);
printf("f=%d\n\n", f);
printf("a=%d\n", &a);
printf("b=%d\n", &b);
printf("c=%d\n", &c);
printf("d=%d\n", &d);
printf("e=%d\n", &e);
printf("f=%d\n", &f);
}
| 13.416667 | 32 | 0.451346 | SauloCav |
1c1ee7480aa05d516af8d3e8eebbfd42381e8be6 | 2,691 | cpp | C++ | src/trap.cpp | prinsij/RogueReborn | 20e6ba4d2e61a47283747ba207a758e604fa89d9 | [
"BSD-3-Clause"
] | null | null | null | src/trap.cpp | prinsij/RogueReborn | 20e6ba4d2e61a47283747ba207a758e604fa89d9 | [
"BSD-3-Clause"
] | null | null | null | src/trap.cpp | prinsij/RogueReborn | 20e6ba4d2e61a47283747ba207a758e604fa89d9 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file trap.cpp
* @author Team Rogue++
* @date December 08, 2016
*
* @brief Member definitions for the Trap class
*/
#include "include/armor.h"
#include "include/coord.h"
#include "include/feature.h"
#include "include/level.h"
#include "include/playerchar.h"
#include "include/random.h"
#include "include/trap.h"
Trap::Trap(Coord location, unsigned char type, bool visible)
: Feature('^', location, visible)
, type(type)
{}
Level* Trap::activate(Mob* mob, Level* level) {
this->visible = true;
PlayerChar* player = dynamic_cast<PlayerChar*>(mob);
if (player) {
if (Generator::randPercent() <= player->getLevel() + player->getDexterity()) {
player->appendLog("The trap failed");
return level;
}
}
// Door Trap
if (this->type == 0) {
if (!player || player->hasCondition(PlayerChar::LEVITATING)) return level;
int currDepth = level->getDepth();
player->appendLog("You fell down a trap, you are now in level " + std::to_string(currDepth+1));
Level* l = new Level(currDepth+1, player);
l->registerMob(player);
l->generate();
return l;
// Rust Trap
} else if (this->type == 1) {
mob->hit(Generator::intFromRange(1, 6));
if (player) {
player->appendLog("A gush of water hits you on the head");
Armor* armor = player->getArmor();
if (armor == NULL || armor->getRating() == 1) return level;
if (!player->hasCondition(PlayerChar::MAINTAIN_ARMOR) && !armor->hasEffect(Item::PROTECTED)) {
armor->setEnchantment(armor->getEnchantment() - 1);
}
}
// Sleep Trap
} else if (this->type == 2) {
if (!player) return level;
player->appendLog("A strange white mist envelops you and you fall asleep");
player->applyCondition(PlayerChar::SLEEPING, Generator::intFromRange(2, 5));
// Bear Trap
} else if (this->type == 3) {
if (!player || player->hasCondition(PlayerChar::LEVITATING)) return level;
player->appendLog("You are caught in a bear trap");
player->applyCondition(PlayerChar::IMMOBILIZED, Generator::intFromRange(4, 7));
// Teleport Trap
} else if (this->type == 4) {
if (player) {
player->appendLog("You are suddenly taken aback");
}
player->setLocation(level->getRandomEmptyPosition());
// Dart Trap
} else if (this->type == 5) {
mob->hit(Generator::intFromRange(1, 6));
if (player) {
player->appendLog("A small dart just hit you in the shoulder");
if (!player->hasCondition(PlayerChar::SUSTAIN_STRENGTH) &&
Generator::randPercent() <= 40 &&
player->getStrength() >= 3) {
player->changeCurrentStrength(-1);
}
}
}
return level;
}
Trap* Trap::randomTrap(Coord location) {
return new Trap(location, Generator::intFromRange(1, Trap::MAX_TYPE), false);
}
| 26.126214 | 97 | 0.665552 | prinsij |
1c1fb1d5403fb66c37df0bc71ecaff089225c783 | 2,380 | cpp | C++ | cc/TextureCopierTest.cpp | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | 2 | 2020-06-10T07:15:26.000Z | 2020-12-13T19:44:12.000Z | cc/TextureCopierTest.cpp | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | cc/TextureCopierTest.cpp | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "TextureCopier.h"
#include "FakeWebGraphicsContext3D.h"
#include "GraphicsContext3D.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include <wtf/RefPtr.h>
using namespace cc;
using namespace WebKit;
using testing::InSequence;
using testing::Test;
using testing::_;
class MockContext : public FakeWebGraphicsContext3D {
public:
MOCK_METHOD2(bindFramebuffer, void(WGC3Denum, WebGLId));
MOCK_METHOD3(texParameteri, void(WGC3Denum target, WGC3Denum pname, WGC3Dint param));
MOCK_METHOD3(drawArrays, void(WGC3Denum mode, WGC3Dint first, WGC3Dsizei count));
};
TEST(TextureCopierTest, testDrawArraysCopy)
{
OwnPtr<MockContext> mockContext = adoptPtr(new MockContext);
{
InSequence sequence;
// Here we check just some essential properties of copyTexture() to avoid mirroring the full implementation.
EXPECT_CALL(*mockContext, bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, _));
// Make sure linear filtering is disabled during the copy.
EXPECT_CALL(*mockContext, texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::NEAREST));
EXPECT_CALL(*mockContext, texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::NEAREST));
EXPECT_CALL(*mockContext, drawArrays(_, _, _));
// Linear filtering should be restored.
EXPECT_CALL(*mockContext, texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR));
EXPECT_CALL(*mockContext, texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR));
// Default framebuffer should be restored
EXPECT_CALL(*mockContext, bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0));
}
int sourceTextureId = 1;
int destTextureId = 2;
IntSize size(256, 128);
OwnPtr<AcceleratedTextureCopier> copier(AcceleratedTextureCopier::create(mockContext.get(), false));
TextureCopier::Parameters copy = { sourceTextureId, destTextureId, size };
copier->copyTexture(copy);
}
| 39.666667 | 147 | 0.758403 | quisquous |
1c2076f3c2443d007c280d234ac4862564d868b5 | 2,305 | cpp | C++ | VulkanTutorials/Plugins/VulkanRendering/VulkanDynamicRenderBuilder.cpp | RichDavisonNCL/VulkanTutorialsRelease | a26b053b170fafa764dee6a575695ff9c3495640 | [
"MIT"
] | null | null | null | VulkanTutorials/Plugins/VulkanRendering/VulkanDynamicRenderBuilder.cpp | RichDavisonNCL/VulkanTutorialsRelease | a26b053b170fafa764dee6a575695ff9c3495640 | [
"MIT"
] | null | null | null | VulkanTutorials/Plugins/VulkanRendering/VulkanDynamicRenderBuilder.cpp | RichDavisonNCL/VulkanTutorialsRelease | a26b053b170fafa764dee6a575695ff9c3495640 | [
"MIT"
] | null | null | null | /******************************************************************************
This file is part of the Newcastle Vulkan Tutorial Series
Author:Rich Davison
Contact:richgdavison@gmail.com
License: MIT (see LICENSE file at the top of the source tree)
*//////////////////////////////////////////////////////////////////////////////
#include "Precompiled.h"
#include "VulkanDynamicRenderBuilder.h"
#include "Vulkan.h"
using namespace NCL;
using namespace Rendering;
VulkanDynamicRenderBuilder::VulkanDynamicRenderBuilder() {
usingStencil = false;
layerCount = 1;
}
VulkanDynamicRenderBuilder::~VulkanDynamicRenderBuilder() {
}
VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithColourAttachment(
vk::ImageView texture, vk::ImageLayout layout, bool clear, vk::ClearValue clearValue
)
{
vk::RenderingAttachmentInfoKHR colourAttachment;
colourAttachment.setImageView(texture)
.setImageLayout(layout)
.setLoadOp(clear ? vk::AttachmentLoadOp::eClear : vk::AttachmentLoadOp::eDontCare)
.setStoreOp(vk::AttachmentStoreOp::eStore)
.setClearValue(clearValue);
colourAttachments.push_back(colourAttachment);
return *this;
}
VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithDepthAttachment(
vk::ImageView texture, vk::ImageLayout layout, bool clear, vk::ClearValue clearValue, bool withStencil
)
{
depthAttachment.setImageView(texture)
.setImageLayout(layout)
.setLoadOp(clear ? vk::AttachmentLoadOp::eClear : vk::AttachmentLoadOp::eDontCare)
.setStoreOp(vk::AttachmentStoreOp::eStore)
.setClearValue(clearValue);
usingStencil = withStencil;
return *this;
}
VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithRenderArea(vk::Rect2D area) {
renderArea = area;
return *this;
}
VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithLayerCount(int count) {
layerCount = count;
return *this;
}
VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::Begin(vk::CommandBuffer buffer) {
vk::RenderingInfoKHR renderInfo;
renderInfo.setLayerCount(layerCount)
.setRenderArea(renderArea)
.setColorAttachments(colourAttachments)
.setPDepthAttachment(&depthAttachment);
if (usingStencil) {
renderInfo.setPStencilAttachment(&depthAttachment);
}
buffer.beginRenderingKHR(renderInfo, *NCL::Rendering::Vulkan::dispatcher);
return *this;
} | 29.177215 | 103 | 0.746204 | RichDavisonNCL |
1c215b01709cf6e871ea75c953a511b6e09fcfd8 | 378 | cpp | C++ | core/Source/CodaStringTransform.cpp | paxbun/dear-my-prof | a1e0032f17d9a62a58673b5dbe2de1446006e528 | [
"MIT"
] | 1 | 2020-01-19T14:14:13.000Z | 2020-01-19T14:14:13.000Z | core/Source/CodaStringTransform.cpp | paxbun/dear-my-prof | a1e0032f17d9a62a58673b5dbe2de1446006e528 | [
"MIT"
] | null | null | null | core/Source/CodaStringTransform.cpp | paxbun/dear-my-prof | a1e0032f17d9a62a58673b5dbe2de1446006e528 | [
"MIT"
] | 1 | 2020-11-18T05:24:38.000Z | 2020-11-18T05:24:38.000Z | // Copyright (c) 2019 Dear My Professor Authors
// Author: paxbun
#include <core/CodaStringTransform.hpp>
#include <boost/locale.hpp>
bool CodaStringTransform::_EndsWithCoda(std::string const& input)
{
auto conv = boost::locale::conv::utf_to_utf<wchar_t>(input);
auto back = conv.back();
return back >= 0xAC00 && back <= 0xD7A3 && ((back - 0xAC00) % 28 != 0);
}
| 25.2 | 75 | 0.679894 | paxbun |
1c26d8f2c8f8524fe4bfce4920a1b730f97794d8 | 432 | cpp | C++ | tests/server/TcpConnection/tests.cpp | batburger/Native-Backend | aaed26851e09f9e110061025fb2140aed1b4f9b5 | [
"Apache-2.0"
] | null | null | null | tests/server/TcpConnection/tests.cpp | batburger/Native-Backend | aaed26851e09f9e110061025fb2140aed1b4f9b5 | [
"Apache-2.0"
] | null | null | null | tests/server/TcpConnection/tests.cpp | batburger/Native-Backend | aaed26851e09f9e110061025fb2140aed1b4f9b5 | [
"Apache-2.0"
] | null | null | null | #define BOOST_TEST_MODULE server_TcpConnection_tests
#include <boost/test/unit_test.hpp>
#include <native-backend/server/Server.h>
BOOST_AUTO_TEST_SUITE(server_TcpConnection_tests)
/*There's no use full way of testing this class outside of the
* Server class, because one would require to mimic all behavior
* of the Server class at which point you may as well just use
* Server.*/
BOOST_AUTO_TEST_SUITE_END()
| 33.230769 | 68 | 0.773148 | batburger |
1c28030c10638c5d3e753a08b69b10f3acd790e4 | 2,755 | cpp | C++ | src/Server/REPL.cpp | wiltonlazary/Nidium | 2ed34f350115290e4fe67cbade6c7e2b7c9de430 | [
"Apache-2.0",
"BSD-2-Clause"
] | 1,223 | 2016-06-28T17:54:08.000Z | 2022-03-16T10:27:03.000Z | src/Server/REPL.cpp | wiltonlazary/Nidium | 2ed34f350115290e4fe67cbade6c7e2b7c9de430 | [
"Apache-2.0",
"BSD-2-Clause"
] | 84 | 2016-07-26T13:22:05.000Z | 2018-09-13T12:04:23.000Z | src/Server/REPL.cpp | wiltonlazary/Nidium | 2ed34f350115290e4fe67cbade6c7e2b7c9de430 | [
"Apache-2.0",
"BSD-2-Clause"
] | 77 | 2016-07-26T13:13:13.000Z | 2022-01-24T02:24:53.000Z | /*
Copyright 2016 Nidium Inc. All rights reserved.
Use of this source code is governed by a MIT license
that can be found in the LICENSE file.
*/
#include "Server/REPL.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pwd.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <linenoise.h>
#include "Binding/NidiumJS.h"
using Nidium::Core::SharedMessages;
namespace Nidium {
namespace Server {
enum ReplMessage
{
kReplMessage_Readline
};
static void *nidium_repl_thread(void *arg)
{
REPL *repl = static_cast<REPL *>(arg);
char *line;
const char *homedir;
char historyPath[PATH_MAX];
if ((homedir = getenv("HOME")) == NULL) {
homedir = getpwuid(getuid())->pw_dir;
}
sprintf(historyPath, "%s/%s", homedir, ".nidium-repl-history");
linenoiseInit();
linenoiseHistoryLoad(historyPath);
repl:
while ((line = linenoise(repl->isContinuing() ? "... " : "nidium> "))
!= NULL) {
repl->setExitCount(0);
linenoiseHistoryAdd(line);
linenoiseHistorySave(historyPath);
repl->postMessage(line, kReplMessage_Readline);
sem_wait(repl->getReadLineLock());
}
int exitcount = repl->getExitCount();
repl->setExitCount(exitcount + 1);
if (exitcount == 0) {
printf("(To exit, press ^C again)\n");
goto repl;
}
kill(getppid(), SIGINT);
return NULL;
}
// {{{ REPL
REPL::REPL(Nidium::Binding::NidiumJS *js)
: m_JS(js), m_Continue(false), m_ExitCount(0)
{
m_Buffer = buffer_new(512);
sem_init(&m_ReadLineLock, 0, 0);
pthread_create(&m_ThreadHandle, NULL, nidium_repl_thread, this);
}
void REPL::onMessage(const SharedMessages::Message &msg)
{
buffer_append_string(m_Buffer, static_cast<char *>(msg.dataPtr()));
JS::RootedObject rgbl(m_JS->m_Cx, JS::CurrentGlobalOrNull(m_JS->m_Cx));
if (JS_BufferIsCompilableUnit(m_JS->m_Cx, rgbl, (char *)m_Buffer->data,
m_Buffer->used)) {
m_Continue = false;
char *ret = m_JS->LoadScriptContentAndGetResult(
reinterpret_cast<char *>(m_Buffer->data), m_Buffer->used,
"commandline");
if (ret) {
printf("%s\n", ret);
free(ret);
}
m_Buffer->used = 0;
} else {
m_Continue = true;
}
free(msg.dataPtr());
sem_post(&m_ReadLineLock);
}
void REPL::onMessageLost(const SharedMessages::Message &msg)
{
free(msg.dataPtr());
}
REPL::~REPL()
{
/*
TODO : stop thread and pthread_join()
*/
buffer_destroy(m_Buffer);
}
// }}}
} // namespace Server
} // namespace Nidium
| 20.407407 | 75 | 0.618512 | wiltonlazary |
1c29af64cae69959b521a29b13c9a4d1321134eb | 5,217 | hpp | C++ | matrix_inverse.hpp | janezz55/vxl | 415bdcb7d5304c6229ac2c910fbdc2988103fdba | [
"Unlicense"
] | 28 | 2016-11-15T09:16:43.000Z | 2021-04-12T15:38:46.000Z | matrix_inverse.hpp | janezz55/vxl | 415bdcb7d5304c6229ac2c910fbdc2988103fdba | [
"Unlicense"
] | null | null | null | matrix_inverse.hpp | janezz55/vxl | 415bdcb7d5304c6229ac2c910fbdc2988103fdba | [
"Unlicense"
] | 1 | 2020-09-04T22:27:20.000Z | 2020-09-04T22:27:20.000Z | #ifndef VXL_MATRIX_INVERSE_HPP
# define VXL_MATRIX_INVERSE_HPP
# pragma once
#include "matrix_determinant.hpp"
namespace vxl
{
//////////////////////////////////////////////////////////////////////////////
template <class T>
//__attribute__ ((noinline))
inline matrix<T, 2, 2> inv(matrix<T, 2, 2> const& ma) noexcept
{
decltype(inv(ma)) mb;
#ifndef VXL_ROW_MAJOR
mb.template set_col<0>(vector<T, 2>{ma(1, 1), -ma(1, 0)});
mb.template set_col<1>(vector<T, 2>{-ma(0, 1), ma(0, 0)});
#else
mb.template set_row<0>(vector<T, 2>{ma(1, 1), -ma(0, 1)});
mb.template set_row<1>(vector<T, 2>{-ma(1, 0), ma(0, 0)});
#endif // VXL_ROW_MAJOR
return mb / det(ma);
}
//////////////////////////////////////////////////////////////////////////////
template <class T>
inline matrix<T, 3, 3> inv(matrix<T, 3, 3> const& ma) noexcept
{
decltype(inv(ma)) mb;
mb(0, 0, ma(1, 1) * ma(2, 2) - ma(1, 2) * ma(2, 1));
mb(0, 1, ma(0, 2) * ma(2, 1) - ma(0, 1) * ma(2, 2));
mb(0, 2, ma(0, 1) * ma(1, 2) - ma(0, 2) * ma(1, 1));
mb(1, 0, ma(1, 2) * ma(2, 0) - ma(1, 0) * ma(2, 2));
mb(1, 1, ma(0, 0) * ma(2, 2) - ma(0, 2) * ma(2, 0));
mb(1, 2, ma(0, 2) * ma(1, 0) - ma(0, 0) * ma(1, 2));
mb(2, 0, ma(1, 0) * ma(2, 1) - ma(1, 1) * ma(2, 0));
mb(2, 1, ma(0, 1) * ma(2, 0) - ma(0, 0) * ma(2, 1));
mb(2, 2, ma(0, 0) * ma(1, 1) - ma(0, 1) * ma(1, 0));
return mb / det(ma);
}
//////////////////////////////////////////////////////////////////////////////
template <class T>
inline matrix<T, 4, 4> inv(matrix<T, 4, 4> const& ma) noexcept
{
decltype(inv(ma)) mb;
mb(0, 0,
ma(1, 2) * ma(2, 3) * ma(3, 1) - ma(1, 3) * ma(2, 2) * ma(3, 1) +
ma(1, 3) * ma(2, 1) * ma(3, 2) - ma(1, 1) * ma(2, 3) * ma(3, 2) -
ma(1, 2) * ma(2, 1) * ma(3, 3) + ma(1, 1) * ma(2, 2) * ma(3, 3)
);
mb(0, 1,
ma(0, 3) * ma(2, 2) * ma(3, 1) - ma(0, 2) * ma(2, 3) * ma(3, 1) -
ma(0, 3) * ma(2, 1) * ma(3, 2) + ma(0, 1) * ma(2, 3) * ma(3, 2) +
ma(0, 2) * ma(2, 1) * ma(3, 3) - ma(0, 1) * ma(2, 2) * ma(3, 3)
);
mb(0, 2,
ma(0, 2) * ma(1, 3) * ma(3, 1) - ma(0, 3) * ma(1, 2) * ma(3, 1) +
ma(0, 3) * ma(1, 1) * ma(3, 2) - ma(0, 1) * ma(1, 3) * ma(3, 2) -
ma(0, 2) * ma(1, 1) * ma(3, 3) + ma(0, 1) * ma(1, 2) * ma(3, 3)
);
mb(0, 3,
ma(0, 3) * ma(1, 2) * ma(2, 1) - ma(0, 2) * ma(1, 3) * ma(2, 1) -
ma(0, 3) * ma(1, 1) * ma(2, 2) + ma(0, 1) * ma(1, 3) * ma(2, 2) +
ma(0, 2) * ma(1, 1) * ma(2, 3) - ma(0, 1) * ma(1, 2) * ma(2, 3)
);
mb(1, 0,
ma(1, 3) * ma(2, 2) * ma(3, 0) - ma(1, 2) * ma(2, 3) * ma(3, 0) -
ma(1, 3) * ma(2, 0) * ma(3, 2) + ma(1, 0) * ma(2, 3) * ma(3, 2) +
ma(1, 2) * ma(2, 0) * ma(3, 3) - ma(1, 0) * ma(2, 2) * ma(3, 3)
);
mb(1, 1,
ma(0, 2) * ma(2, 3) * ma(3, 0) - ma(0, 3) * ma(2, 2) * ma(3, 0) +
ma(0, 3) * ma(2, 0) * ma(3, 2) - ma(0, 0) * ma(2, 3) * ma(3, 2) -
ma(0, 2) * ma(2, 0) * ma(3, 3) + ma(0, 0) * ma(2, 2) * ma(3, 3)
);
mb(1, 2,
ma(0, 3) * ma(1, 2) * ma(3, 0) - ma(0, 2) * ma(1, 3) * ma(3, 0) -
ma(0, 3) * ma(1, 0) * ma(3, 2) + ma(0, 0) * ma(1, 3) * ma(3, 2) +
ma(0, 2) * ma(1, 0) * ma(3, 3) - ma(0, 0) * ma(1, 2) * ma(3, 3)
);
mb(1, 3,
ma(0, 2) * ma(1, 3) * ma(2, 0) - ma(0, 3) * ma(1, 2) * ma(2, 0) +
ma(0, 3) * ma(1, 0) * ma(2, 2) - ma(0, 0) * ma(1, 3) * ma(2, 2) -
ma(0, 2) * ma(1, 0) * ma(2, 3) + ma(0, 0) * ma(1, 2) * ma(2, 3)
);
mb(2, 0,
ma(1, 1) * ma(2, 3) * ma(3, 0) - ma(1, 3) * ma(2, 1) * ma(3, 0) +
ma(1, 3) * ma(2, 0) * ma(3, 1) - ma(1, 0) * ma(2, 3) * ma(3, 1) -
ma(1, 1) * ma(2, 0) * ma(3, 3) + ma(1, 0) * ma(2, 1) * ma(3, 3)
);
mb(2, 1,
ma(0, 3) * ma(2, 1) * ma(3, 0) - ma(0, 1) * ma(2, 3) * ma(3, 0) -
ma(0, 3) * ma(2, 0) * ma(3, 1) + ma(0, 0) * ma(2, 3) * ma(3, 1) +
ma(0, 1) * ma(2, 0) * ma(3, 3) - ma(0, 0) * ma(2, 1) * ma(3, 3)
);
mb(2, 2,
ma(0, 1) * ma(1, 3) * ma(3, 0) - ma(0, 3) * ma(1, 1) * ma(3, 0) +
ma(0, 3) * ma(1, 0) * ma(3, 1) - ma(0, 0) * ma(1, 3) * ma(3, 1) -
ma(0, 1) * ma(1, 0) * ma(3, 3) + ma(0, 0) * ma(1, 1) * ma(3, 3)
);
mb(2, 3,
ma(0, 3) * ma(1, 1) * ma(2, 0) - ma(0, 1) * ma(1, 3) * ma(2, 0) -
ma(0, 3) * ma(1, 0) * ma(2, 1) + ma(0, 0) * ma(1, 3) * ma(2, 1) +
ma(0, 1) * ma(1, 0) * ma(2, 3) - ma(0, 0) * ma(1, 1) * ma(2, 3)
);
mb(3, 0,
ma(1, 2) * ma(2, 1) * ma(3, 0) - ma(1, 1) * ma(2, 2) * ma(3, 0) -
ma(1, 2) * ma(2, 0) * ma(3, 1) + ma(1, 0) * ma(2, 2) * ma(3, 1) +
ma(1, 1) * ma(2, 0) * ma(3, 2) - ma(1, 0) * ma(2, 1) * ma(3, 2)
);
mb(3, 1,
ma(0, 1) * ma(2, 2) * ma(3, 0) - ma(0, 2) * ma(2, 1) * ma(3, 0) +
ma(0, 2) * ma(2, 0) * ma(3, 1) - ma(0, 0) * ma(2, 2) * ma(3, 1) -
ma(0, 1) * ma(2, 0) * ma(3, 2) + ma(0, 0) * ma(2, 1) * ma(3, 2)
);
mb(3, 2,
ma(0, 2) * ma(1, 1) * ma(3, 0) - ma(0, 1) * ma(1, 2) * ma(3, 0) -
ma(0, 2) * ma(1, 0) * ma(3, 1) + ma(0, 0) * ma(1, 2) * ma(3, 1) +
ma(0, 1) * ma(1, 0) * ma(3, 2) - ma(0, 0) * ma(1, 1) * ma(3, 2)
);
mb(3, 3,
ma(0, 1) * ma(1, 2) * ma(2, 0) - ma(0, 2) * ma(1, 1) * ma(2, 0) +
ma(0, 2) * ma(1, 0) * ma(2, 1) - ma(0, 0) * ma(1, 2) * ma(2, 1) -
ma(0, 1) * ma(1, 0) * ma(2, 2) + ma(0, 0) * ma(1, 1) * ma(2, 2)
);
return mb / det(ma);
}
}
#endif // VXL_MATRIX_INVERSE_HPP
| 36.739437 | 78 | 0.379337 | janezz55 |
1c2fccf62da3e58f82082e09b5e3398d05384f15 | 51,411 | hpp | C++ | glfw3_app/ignitor/wave_cap.hpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | 9 | 2015-09-22T21:36:57.000Z | 2021-04-01T09:16:53.000Z | glfw3_app/ignitor/wave_cap.hpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | null | null | null | glfw3_app/ignitor/wave_cap.hpp | hirakuni45/glfw3_app | d9ceeef6d398229fda4849afe27f8b48d1597fcf | [
"BSD-3-Clause"
] | 2 | 2019-02-21T04:22:13.000Z | 2021-03-02T17:24:32.000Z | #pragma once
//=====================================================================//
/*! @file
@brief 波形キャプチャー・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <array>
#include "core/glcore.hpp"
#include "utils/i_scene.hpp"
#include "utils/director.hpp"
#include "widgets/widget.hpp"
#include "widgets/widget_utils.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_sheet.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_filer.hpp"
#include "widgets/widget_terminal.hpp"
#include "widgets/widget_list.hpp"
#include "widgets/widget_view.hpp"
#include "widgets/widget_radio.hpp"
#include "widgets/widget_spinbox.hpp"
#include "widgets/widget_chip.hpp"
#include "gl_fw/render_waves.hpp"
#include "img_io/img_files.hpp"
#include "ign_client_tcp.hpp"
#include "interlock.hpp"
#include "test.hpp"
// #define TEST_SIN
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief wave_cap クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class wave_cap {
static constexpr const char* WAVE_DATA_EXT_ = "wad";
public:
//=================================================================//
/*!
@brief 情報構造体
*/
//=================================================================//
struct info_t {
double sample_org_; ///< サンプリング開始時間
double sample_width_; ///< サンプリング領域(時間)
double sig_[4]; ///< 各チャネル電圧
double min_[4]; ///< 領域の最低値
double max_[4]; ///< 領域の最大値
double average_[4]; ///< 領域のアベレージ
uint32_t id_; ///< 領域更新 ID
info_t() : sample_org_(0.0), sample_width_(0.0),
sig_{ 0.0 }, min_{ 0.0 }, max_{ 0.0 }, average_{ 0.0 },
id_(0)
{ }
};
//=================================================================//
/*!
@brief サンプリング・パラメーター構造体
*/
//=================================================================//
struct sample_param {
double rate;
double gain[4];
sample_param() : rate(1e-6) {
gain[0] = 1.0;
gain[1] = 1.0;
gain[2] = 1.0;
gain[3] = 1.0;
}
};
private:
typedef utils::director<core> DR;
DR& director_;
typedef net::ign_client_tcp CLIENT;
CLIENT& client_;
interlock& interlock_;
typedef view::render_waves<uint16_t, CLIENT::WAVE_BUFF_SIZE, 4> WAVES;
WAVES waves_;
gui::widget_frame* frame_;
gui::widget_view* core_;
gui::widget_frame* terminal_frame_;
gui::widget_terminal* terminal_core_;
gui::widget_frame* tools_;
gui::widget_check* smooth_;
gui::widget_button* load_;
gui::widget_button* save_;
gui::widget_list* mesa_type_;
gui::widget_label* mesa_filt_;
gui::widget_list* org_trg_;
gui::widget_spinbox* org_slope_;
gui::widget_check* org_ena_;
gui::widget_list* fin_trg_;
gui::widget_spinbox* fin_slope_;
gui::widget_check* fin_ena_;
gui::widget_list* time_mesa_ch_;
gui::widget_spinbox* time_delay_;
gui::widget_check* time_delay_ena_;
gui::widget_text* ch_to_time_;
gui::widget_button* wdm_exec_;
uint32_t meas_id_before_;
uint32_t meas_id_;
float org_value_;
float fin_value_;
gui::widget_sheet* share_frame_;
sample_param sample_param_;
uint32_t wdm_id_[4];
uint32_t treg_id_[2];
WAVES::analize_param treg_1st_;
WAVES::analize_param treg_2nd_;
float treg_value_;
float treg_value2_;
uint32_t treg_value_id_;
bool info_in_;
vtx::ipos info_org_;
info_t info_;
gui::widget_chip* chip_;
// チャネル補正ゲイン
static float get_optional_gain_(uint32_t ch) {
if(ch == 0) return 1.067f; // CH1 補正ゲイン
else if(ch == 1) return 1.029f; // CH2 補正ゲイン
// else if(ch == 2) return 1.111f; // CH3 補正ゲイン
// else if(ch == 2) return 1.0777f; // CH3 補正ゲイン
else if(ch == 2) return 1.0566f; // CH3 補正ゲイン
else return 1.0179f; // CH4 補正ゲイン
}
// チャネル毎の電圧スケールサイズ
static const uint32_t volt_scale_0_size_ = 8;
static const uint32_t volt_scale_1_size_ = 15;
static const uint32_t volt_scale_2_size_ = 10;
static const uint32_t volt_scale_3_size_ = 12;
static uint32_t get_volt_scale_size_(uint32_t ch) {
if(ch == 0) return volt_scale_0_size_;
else if(ch == 1) return volt_scale_1_size_;
else if(ch == 2) return volt_scale_2_size_;
else return volt_scale_3_size_;
}
static float get_volt_scale_value_(uint32_t ch, uint32_t idx) {
if(ch == 0) {
static const float tbl[volt_scale_0_size_] = {
0.25f, 0.5f, 1.0f, 2.0f, 2.5f, 5.0f, 7.5f, 10.0f
};
return tbl[idx % get_volt_scale_size_(ch)];
} else if(ch == 1) {
static const float tbl[volt_scale_1_size_] = {
0.125f, 0.25f, 0.5f, 1.0f, 2.5f, 5.0f, 10.0f, 20.0f, 25.0f, 50.0f, 75.0f,
100.0f, 125.0f, 150.0f, 200.0f
};
return tbl[idx % get_volt_scale_size_(ch)];
} else if(ch == 2) {
static const float tbl[volt_scale_2_size_] = {
0.05f, 0.1f, 0.2f, 0.25f, 0.5f, 1.0f, 1.5f, 2.0f, 2.5f, 5.0f
};
return tbl[idx % get_volt_scale_size_(ch)];
} else {
static const float tbl[volt_scale_3_size_] = {
0.0625f, 0.125f, 0.25f, 0.5f, 1.0f, 1.25f, 2.5f, 5.0f,
7.5f, 10.0f, 15.0f, 20.0f
};
return tbl[idx % get_volt_scale_size_(ch)];
}
}
static float get_volt_scale_limit_(uint32_t ch) {
if(ch == 0) return 32.768f;
else if(ch == 1) return 655.36f;
else if(ch == 2) return 16.384f;
else return 65.536f;
}
static const uint32_t time_unit_size_ = 20;
static double get_time_unit_(uint32_t idx) {
static const double tbl[time_unit_size_] = {
100e-9, 250e-9, 500e-9, 1e-6,
2.5e-6, 5e-6, 10e-6, 25e-6,
50e-6, 100e-6, 250e-6, 500e-6,
1e-3, 2.5e-3, 5e-3, 10e-3,
25e-3, 50e-3, 75e-3, 100e-3
};
return tbl[idx % time_unit_size_];
}
static float get_time_unit_base_(uint32_t idx) {
static const float tbl[time_unit_size_] = {
1e-9, 1e-9, 1e-9, 1e-6,
1e-6, 1e-6, 1e-6, 1e-6,
1e-6, 1e-6, 1e-6, 1e-6,
1e-3, 1e-3, 1e-3, 1e-3,
1e-3, 1e-3, 1e-3, 1e-3
};
return tbl[idx % time_unit_size_];
}
static const char* get_time_unit_str_(uint32_t idx) {
static const char* tbl[time_unit_size_] = {
"nS", "nS", "nS", "uS",
"uS", "uS", "uS", "uS",
"uS", "uS", "uS", "uS",
"mS", "mS", "mS", "mS",
"mS", "mS", "mS", "mS"
};
return tbl[idx % time_unit_size_];
}
static uint32_t get_time_scale_(uint32_t idx, uint32_t grid, float rate) {
float g = static_cast<float>(grid);
float step = get_time_unit_(idx) / g;
return static_cast<uint32_t>(65536.0f * step / rate);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief チャネル・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct chn_t {
WAVES& waves_; ///< 波形レンダリング
gui::widget_null* root_; ///< ルート
gui::widget_check* ena_; ///< チャネル有効、無効
gui::widget_check* gnd_; ///< GND 電位
gui::widget_spinbox* pos_; ///< 水平位置
gui::widget_spinbox* scale_; ///< 電圧スケール
gui::widget_check* mes_; ///< メジャー有効
gui::widget_spinbox* org_; ///< 計測開始位置
gui::widget_spinbox* len_; ///< 計測長さ
// fs: フルスケール電圧
chn_t(WAVES& waves, float fs) : waves_(waves), root_(nullptr),
ena_(nullptr), gnd_(nullptr), pos_(nullptr), scale_(nullptr),
mes_(nullptr), org_(nullptr), len_(nullptr)
{ }
void init(DR& dr, gui::widget_sheet* share, int ch)
{
using namespace gui;
auto& wd = dr.at().widget_director_;
{ // 仮想フレーム
widget::param wp(vtx::irect(0, 0, 0, 0), share);
widget_null::param wp_;
root_ = wd.add_widget<widget_null>(wp, wp_);
share->add((boost::format("CH%d") % (ch + 1)).str(), root_);
}
{ // 有効、無効
widget::param wp(vtx::irect(10, 30, 80, 40), root_);
widget_check::param wp_((boost::format("CH%d") % (ch + 1)).str());
ena_ = wd.add_widget<widget_check>(wp, wp_);
ena_->at_local_param().select_func_ = [=](bool f) {
waves_.at_param(ch).render_ = f;
};
}
{ // GND 電位
widget::param wp(vtx::irect(10 + 90, 30, 80, 40), root_);
widget_check::param wp_("GND");
gnd_ = wd.add_widget<widget_check>(wp, wp_);
}
{ // 電圧位置 (+-1.0)
widget::param wp(vtx::irect(10, 70, 130, 40), root_);
widget_spinbox::param wp_(-20, 0, 20); // grid 数の倍
pos_ = wd.add_widget<widget_spinbox>(wp, wp_);
pos_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
int wy = share->get_param().rect_.size.y;
float a = static_cast<float>(-newpos)
/ static_cast<float>(wy * 2 / waves_.get_info().grid_step_);
return (boost::format("%3.2f") % a).str();
};
}
{ // 電圧スケール
widget::param wp(vtx::irect(10 + 140, 70, 160, 40), root_);
widget_spinbox::param wp_(0, 0, (get_volt_scale_size_(ch) - 1));
scale_ = wd.add_widget<widget_spinbox>(wp, wp_);
scale_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
// グリッドに対する電圧表示
auto a = get_volt_scale_value_(ch, newpos);
static const char* unit[4] = { "A", "V", "V", "KV" };
org_->exec();
len_->exec();
return (boost::format("%3.2f %s") % a % unit[ch]).str();
};
}
{ // メジャー有効、無効
widget::param wp(vtx::irect(10, 120, 130, 40), root_);
widget_check::param wp_("Measure");
mes_ = wd.add_widget<widget_check>(wp, wp_);
}
{ // メジャー開始位置
widget::param wp(vtx::irect(10, 170, 145, 40), root_);
widget_spinbox::param wp_(0, 0, 100);
org_ = wd.add_widget<widget_spinbox>(wp, wp_);
org_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
float a = static_cast<float>(-newpos)
/ static_cast<float>(waves_.get_info().grid_step_)
* get_volt_scale_value_(ch, scale_->get_select_pos());
float b = static_cast<float>(-pos_->get_select_pos()) / 2.0f;
b *= get_volt_scale_value_(ch, scale_->get_select_pos());
return (boost::format("%3.2f") % (a - b)).str();
};
}
{ // メジャー長さ
widget::param wp(vtx::irect(10 + 155, 170, 145, 40), root_);
widget_spinbox::param wp_(0, 0, 100); // grid 数の倍
len_ = wd.add_widget<widget_spinbox>(wp, wp_);
len_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
// メジャーに対する電圧、電流表示
float a = static_cast<float>(-newpos)
/ static_cast<float>(waves_.get_info().grid_step_)
* get_volt_scale_value_(ch, scale_->get_select_pos());
return (boost::format("%3.2f") % a).str();
};
}
}
void update(uint32_t ch, const vtx::ipos& size, float gainrate)
{
if(pos_ == nullptr || scale_ == nullptr) return;
if(org_ == nullptr || len_ == nullptr) return;
int grid = waves_.get_info().grid_step_;
auto pos = (size.y / grid) * 3 / 2;
pos_->at_local_param().min_pos_ = -pos;
pos_->at_local_param().max_pos_ = pos;
int msofs = size.y / 2;
org_->at_local_param().min_pos_ = -msofs;
org_->at_local_param().max_pos_ = msofs;
org_->at_local_param().page_div_ = 0;
org_->at_local_param().page_step_ = -grid;
len_->at_local_param().min_pos_ = -size.y;
len_->at_local_param().max_pos_ = size.y;
len_->at_local_param().page_div_ = 0;
len_->at_local_param().page_step_ = -grid;
// 波形位置
waves_.at_param(ch).offset_.y = (size.y / 2)
+ pos_->get_select_pos() * (grid / 2);
// 波形拡大、縮小
float value = get_volt_scale_value_(ch, scale_->get_select_pos())
/ static_cast<float>(grid);
float u = get_volt_scale_limit_(ch) / static_cast<float>(32768);
if(gnd_->get_check()) u = 0.0f;
//////////////////////////////////////////////////////////
waves_.at_param(ch).gain_ = u / value / gainrate * get_optional_gain_(ch);
// 電圧計測設定
if(mes_->get_check()) {
waves_.at_info().volt_enable_[ch] = true;
waves_.at_info().volt_org_[ch] = org_->get_select_pos() + msofs;
waves_.at_info().volt_len_[ch] = len_->get_select_pos();
} else {
waves_.at_info().volt_enable_[ch] = false;
}
}
void load(sys::preference& pre)
{
if(ena_ != nullptr) {
ena_->load(pre);
}
if(gnd_ != nullptr) {
gnd_->load(pre);
}
if(pos_ != nullptr) {
pos_->load(pre);
pos_->exec();
}
if(scale_ != nullptr) {
scale_->load(pre);
scale_->exec();
}
if(mes_ != nullptr) {
mes_->load(pre);
}
if(org_ != nullptr) {
org_->load(pre);
org_->exec();
}
if(len_ != nullptr) {
len_->load(pre);
len_->exec();
}
ena_->exec();
gnd_->exec();
mes_->exec();
}
void save(sys::preference& pre)
{
if(ena_ != nullptr) {
ena_->save(pre);
}
if(gnd_ != nullptr) {
gnd_->save(pre);
}
if(pos_ != nullptr) {
pos_->save(pre);
}
if(scale_ != nullptr) {
scale_->save(pre);
}
if(mes_ != nullptr) {
mes_->save(pre);
}
if(org_ != nullptr) {
org_->save(pre);
}
if(len_ != nullptr) {
len_->save(pre);
}
}
};
chn_t chn0_;
chn_t chn1_;
chn_t chn2_;
chn_t chn3_;
chn_t& at_ch(uint32_t no) {
switch(no) {
case 0: return chn0_;
case 1: return chn1_;
case 2: return chn2_;
case 3: return chn3_;
default:
return chn0_;
}
}
const chn_t& get_ch(uint32_t no) const {
switch(no) {
case 0: return chn0_;
case 1: return chn1_;
case 2: return chn2_;
case 3: return chn3_;
default:
return chn0_;
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 時間軸計測クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct measure_t {
WAVES& waves_;
gui::widget_null* root_;
gui::widget_check* ena_;
gui::widget_spinbox* org_;
gui::widget_spinbox* len_;
gui::widget_text* frq_; ///< 周波数表示
uint32_t tbp_; ///< タイム・ベース位置
measure_t(WAVES& waves) : waves_(waves), root_(nullptr),
ena_(nullptr), org_(nullptr), len_(nullptr),
frq_(nullptr),
tbp_(0)
{ }
void init(DR& dr, gui::widget_sheet* share, const std::string& text)
{
using namespace gui;
widget_director& wd = dr.at().widget_director_;
{ // 仮想フレーム
widget::param wp(vtx::irect(0, 0, 0, 0), share);
widget_null::param wp_;
root_ = wd.add_widget<widget_null>(wp, wp_);
share->add(text, root_);
}
{ // メジャー有効、無効
widget::param wp(vtx::irect(10, 30, 140, 40), root_);
widget_check::param wp_("Enable");
ena_ = wd.add_widget<widget_check>(wp, wp_);
ena_->at_local_param().select_func_ = [=](bool f) {
waves_.at_info().time_enable_ = f;
};
}
{
widget::param wp(vtx::irect(10, 70, 200, 40), root_);
widget_spinbox::param wp_(0, 0, 100);
org_ = wd.add_widget<widget_spinbox>(wp, wp_);
org_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
float t = get_time_unit_(tbp_) * static_cast<float>(newpos)
/ waves_.get_info().grid_step_;
float a = t / get_time_unit_base_(tbp_);
return (boost::format("%2.1f %s") % a % get_time_unit_str_(tbp_)).str();
};
}
{
widget::param wp(vtx::irect(10, 120, 200, 40), root_);
widget_spinbox::param wp_(0, 0, 100);
len_ = wd.add_widget<widget_spinbox>(wp, wp_);
len_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
float t = get_time_unit_(tbp_) * static_cast<float>(newpos)
/ waves_.get_info().grid_step_;
float a = t / get_time_unit_base_(tbp_);
if(t > 0.0f) {
float f = 1.0f / t;
if(f >= 1000.0) {
f /= 1000.0;
frq_->set_text((boost::format("%4.3f KHz") % f).str());
} else if(f >= 1000000.0) {
f /= 1000000.0;
frq_->set_text((boost::format("%4.3f MHz") % f).str());
} else {
frq_->set_text((boost::format("%4.3f Hz") % f).str());
}
} else {
frq_->set_text("---");
}
return (boost::format("%3.2f %s") % a % get_time_unit_str_(tbp_)).str();
};
}
{
widget::param wp(vtx::irect(10, 170, 150, 40), root_);
widget_text::param wp_;
frq_ = wd.add_widget<widget_text>(wp, wp_);
}
}
void update(const vtx::ipos& size)
{
if(org_ == nullptr || len_ == nullptr) return;
auto grid = waves_.get_info().grid_step_;
org_->at_local_param().min_pos_ = 0;
org_->at_local_param().max_pos_ = size.x;
org_->at_local_param().page_div_ = 0;
org_->at_local_param().page_step_ = grid;
waves_.at_info().time_org_ = org_->get_select_pos();
len_->at_local_param().min_pos_ = 0;
len_->at_local_param().max_pos_ = size.x;
len_->at_local_param().page_div_ = 0;
len_->at_local_param().page_step_ = grid;
waves_.at_info().time_len_ = len_->get_select_pos();
}
void load(sys::preference& pre)
{
if(ena_ != nullptr) {
ena_->load(pre);
}
if(org_ != nullptr) {
org_->load(pre);
org_->exec();
}
if(len_ != nullptr) {
len_->load(pre);
len_->exec();
}
}
void save(sys::preference& pre)
{
if(ena_ != nullptr) {
ena_->save(pre);
}
if(org_ != nullptr) {
org_->save(pre);
}
if(len_ != nullptr) {
len_->save(pre);
}
}
};
measure_t measure_time_;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 時間軸クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct time_t {
WAVES& waves_;
gui::widget_null* root_;
gui::widget_spinbox* scale_; ///< 時間スケール
gui::widget_spinbox* offset_; ///< 時間オフセット
gui::widget_button* res_ofs_; ///< 時間オフセット、リセット
gui::widget_check* trg_gate_; ///< トリガー表示
uint32_t id_;
time_t(WAVES& waves) : waves_(waves),
root_(nullptr),
scale_(nullptr), offset_(nullptr), res_ofs_(nullptr), trg_gate_(nullptr),
id_(0)
{ }
void init(DR& dr, gui::widget_sheet* share)
{
using namespace gui;
auto& wd = dr.at().widget_director_;
{ // 仮想フレーム
widget::param wp(vtx::irect(0, 0, 0, 0), share);
widget_null::param wp_;
root_ = wd.add_widget<widget_null>(wp, wp_);
share->add("Time Scale", root_);
}
{ // タイム・スケール
widget::param wp(vtx::irect(10, 40, 200, 40), root_);
widget_spinbox::param wp_(0, 0, time_unit_size_ - 1);
scale_ = wd.add_widget<widget_spinbox>(wp, wp_);
scale_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
++id_;
float a = get_time_unit_(newpos) / get_time_unit_base_(newpos);
return (boost::format("%2.1f %s") % a % get_time_unit_str_(newpos)).str();
};
}
{ // タイム・オフセット(グリッド単位)
widget::param wp(vtx::irect(10, 90, 200, 40), root_);
widget_spinbox::param wp_(-50, 0, 50);
offset_ = wd.add_widget<widget_spinbox>(wp, wp_);
offset_->at_local_param().select_func_
= [=](widget_spinbox::state st, int before, int newpos) {
++id_;
float t = get_time_unit_(scale_->get_select_pos()) * newpos;
auto un = scale_->get_select_pos();
float a = t / get_time_unit_base_(un);
return (boost::format("%2.1f %s") % a % get_time_unit_str_(un)).str();
};
}
{ // オフセット・リセット
widget::param wp(vtx::irect(10 + 215, 95, 30, 30), root_);
widget_button::param wp_("R");
res_ofs_ = wd.add_widget<widget_button>(wp, wp_);
res_ofs_->at_local_param().select_func_ = [=](uint32_t id) {
++id_;
offset_->set_select_pos(0);
};
}
{ // トリガー・ゲート有効、無効
widget::param wp(vtx::irect(10, 140, 140, 40), root_);
widget_check::param wp_("Trigger");
trg_gate_ = wd.add_widget<widget_check>(wp, wp_);
trg_gate_->at_local_param().select_func_ = [=](bool ena) {
++id_;
};
}
}
void update(const vtx::ipos& size, float rate)
{
int grid = waves_.get_info().grid_step_;
auto ts = get_time_scale_(scale_->get_select_pos(), grid, rate);
int w = (waves_.size() / 2 * ts / 65536 - size.x) / grid;
offset_->at_local_param().min_pos_ = -w;
offset_->at_local_param().max_pos_ = w;
auto ofs = offset_->get_select_pos();
// 波形のトリガー先頭
waves_.at_param(0).offset_.x = ofs * grid;
waves_.at_param(1).offset_.x = ofs * grid;
waves_.at_param(2).offset_.x = ofs * grid;
waves_.at_param(3).offset_.x = ofs * grid;
if(trg_gate_->get_check()) {
waves_.at_info().trig_enable_ = true;
waves_.at_info().trig_pos_ = -offset_->get_select_pos() * grid;
} else {
waves_.at_info().trig_enable_ = false;
}
}
void load(sys::preference& pre)
{
if(scale_ != nullptr) {
scale_->load(pre);
scale_->exec();
}
if(offset_ != nullptr) {
offset_->load(pre);
offset_->exec();
}
if(trg_gate_ != nullptr) {
trg_gate_->load(pre);
}
}
void save(sys::preference& pre)
{
if(scale_ != nullptr) {
scale_->save(pre);
}
if(offset_ != nullptr) {
offset_->save(pre);
}
if(trg_gate_ != nullptr) {
trg_gate_->save(pre);
}
}
};
time_t time_;
uint32_t time_id_;
vtx::ipos size_;
double mesa_value_;
uint32_t mesa_id_;
double time_meas_delay_;
void volt_scale_conv_(uint32_t ch, const WAVES::analize_param& ap, info_t& t)
{
float gain = 1.0f / sample_param_.gain[ch];
t.min_[ch] = get_volt_scale_limit_(ch) * ap.min_ * gain;
t.max_[ch] = get_volt_scale_limit_(ch) * ap.max_ * gain;
t.average_[ch] = get_volt_scale_limit_(ch) * ap.average_ * gain;
}
// 波形描画
void update_view_()
{
if(core_->get_select_in()) {
info_in_ = true;
info_org_ = core_->get_param().in_point_;
}
if(core_->get_selected()) {
uint32_t n = 0;
if(time_.scale_ != nullptr) {
n = time_.scale_->get_select_pos();
}
auto msp = core_->get_param().in_point_;
info_in_ = false;
auto grid = waves_.get_info().grid_step_;
int32_t sta = info_org_.x + time_.offset_->get_select_pos() * grid;
int32_t fin = msp.x + time_.offset_->get_select_pos() * grid;
if(sta > fin) std::swap(sta, fin);
auto tu = get_time_unit_(n);
info_.sample_org_ = static_cast<double>(sta) * tu;
double org = static_cast<double>(sta) / static_cast<double>(grid) * tu;
double end = static_cast<double>(fin) / static_cast<double>(grid) * tu;
info_.sample_width_ = end - org;
for(uint32_t i = 0; i < 4; ++i) {
if(!get_ch(i).ena_->get_check()) continue;
auto a = waves_.get(i, sample_param_.rate, org);
a *= get_optional_gain_(i);
a *= get_volt_scale_limit_(i);
a /= sample_param_.gain[i];
if(get_ch(i).gnd_->get_check()) {
a = 0.0f;
}
info_.sig_[i] = a;
static const char* t[4] = { "A", "V", "V", "KV" };
double len = info_.sample_width_;
static const char* ut[4] = { "S", "mS", "uS", "nS" };
uint32_t uti = 0;
if(len < 1e-6) { len *= 1e9; uti = 3; }
else if(len < 1e-3) { len *= 1e6; uti = 2; }
else if(len < 1.0) { len *= 1e3; uti = 1; }
std::string s = (boost::format("CH%d: %4.3f %s, %4.3f %s\n")
% (i + 1) % a % t[i] % len % ut[uti]).str();
terminal_core_->output(s);
{ // 波形解析
double step = tu / static_cast<double>(grid);
auto ap = waves_.analize(i, sample_param_.rate, org, end - org, step);
volt_scale_conv_(i, ap, info_);
s = (boost::format("Min: %4.3f %s, ") % info_.min_[i] % t[i]).str();
terminal_core_->output(s);
s = (boost::format("Max: %4.3f %s\n") % info_.max_[i] % t[i]).str();
terminal_core_->output(s);
s = (boost::format("Ave: %4.3f %s\n") % info_.average_[i] % t[i]).str();
terminal_core_->output(s);
++info_.id_;
}
}
}
// フォーカスが外れたら、情報(IN) を強制終了
if(!core_->get_focus()) {
info_in_ = false;
}
}
void render_view_(const vtx::irect& clip)
{
glDisable(GL_TEXTURE_2D);
if(info_in_ && core_->get_select()) {
vtx::sposs r;
r.emplace_back(info_org_.x, info_org_.y);
auto msp = core_->get_param().in_point_;
r.emplace_back(msp.x, info_org_.y);
r.emplace_back(msp.x, msp.y);
r.emplace_back(info_org_.x, msp.y);
gl::glColor(img::rgba8(255, 255));
gl::draw_line_loop(r);
}
uint32_t n = 0;
if(time_.scale_ != nullptr) {
n = time_.scale_->get_select_pos();
}
waves_.render(clip.size, sample_param_.rate, get_time_unit_(n));
glEnable(GL_TEXTURE_2D);
size_ = clip.size;
}
void service_view_()
{
}
void meas_run_()
{
// スキャンする長さは、見えている範囲に制限する。
auto grid = waves_.get_info().grid_step_;
double unit = get_time_unit_(time_.scale_->get_select_pos());
double length = static_cast<double>(size_.x / grid) * unit;
double offset = static_cast<double>(time_.offset_->get_select_pos()) * unit;
WAVES::measure_param param;
double tm = 0.0;
switch(mesa_type_->get_select_pos()) {
case 0: // single
{
param.org_ch_ = org_trg_->get_select_pos() / 2;
float base = 100.0f;
if(org_trg_->get_select_pos() & 1) base = -100.0f;
param.org_slope_ = static_cast<float>(org_slope_->get_select_pos()) / base;
auto srate = sample_param_.rate;
tm = waves_.measure_org(srate, offset, 0.0, length, param);
uint32_t idx = time_.scale_->get_select_pos();
auto ofs = time_.offset_->get_select_pos() * -grid;
waves_.at_info().meas_pos_[0] = ofs + (tm / get_time_unit_(idx)) * grid;
waves_.at_info().meas_color_[0] = waves_.get_info().volt_color_[param.org_ch_];
}
break;
case 1: // multi
{
param.org_ch_ = org_trg_->get_select_pos() / 2;
float base = 100.0f;
if(org_trg_->get_select_pos() & 1) base = -100.0f;
param.org_slope_ = static_cast<float>(org_slope_->get_select_pos()) / base;
param.fin_ch_ = fin_trg_->get_select_pos() / 2;
base = 100.0f;
if(fin_trg_->get_select_pos() & 1) base = -100.0f;
param.fin_slope_ = static_cast<float>(fin_slope_->get_select_pos()) / base;
auto srate = sample_param_.rate;
auto a = waves_.measure_org(srate, offset, 0.0, length, param);
uint32_t idx = time_.scale_->get_select_pos();
auto ofs = time_.offset_->get_select_pos() * -grid;
waves_.at_info().meas_pos_[0] = ofs + (a / get_time_unit_(idx)) * grid;
waves_.at_info().meas_color_[0] = waves_.get_info().volt_color_[param.org_ch_];
auto b = waves_.measure_fin(srate, offset, a, length, param);
waves_.at_info().meas_pos_[1] = ofs + (b / get_time_unit_(idx)) * grid;
waves_.at_info().meas_color_[1] = waves_.get_info().volt_color_[param.fin_ch_];
tm = b - a;
}
break;
case 2: // トリガ電圧測定
{
auto srate = sample_param_.rate;
auto ch = time_mesa_ch_->get_select_pos();
tm = waves_.get(ch, srate, 0.0);
}
break;
case 3: // max
{
auto srate = sample_param_.rate;
auto ch = time_mesa_ch_->get_select_pos();
auto ana = waves_.analize(ch, srate, 0.0, time_meas_delay_ + srate, srate);
tm = ana.max_ / sample_param_.gain[ch];
waves_.at_info().delay_color_ = waves_.get_info().volt_color_[ch];
}
break;
case 4: // min
{
auto srate = sample_param_.rate;
auto ch = time_mesa_ch_->get_select_pos();
auto ana = waves_.analize(ch, srate, 0.0, time_meas_delay_ + srate, srate);
tm = ana.min_ / sample_param_.gain[ch];
waves_.at_info().delay_color_ = waves_.get_info().volt_color_[ch];
}
break;
case 5: // average
{
auto srate = sample_param_.rate;
auto ch = time_mesa_ch_->get_select_pos();
auto ana = waves_.analize(ch, srate, 0.0, time_meas_delay_ + srate, srate);
tm = ana.average_ / sample_param_.gain[ch];
waves_.at_info().delay_color_ = waves_.get_info().volt_color_[ch];
}
break;
default:
break;
}
if(mesa_type_->get_select_pos() < 2) {
uint32_t idx = time_.scale_->get_select_pos();
tm /= get_time_unit_base_(idx);
std::string un = get_time_unit_str_(idx);
ch_to_time_->set_text((boost::format("%5.4f [%s]") % tm % un).str());
} else {
auto ch = time_mesa_ch_->get_select_pos();
tm *= get_volt_scale_limit_(ch) * get_optional_gain_(ch);
static const char* unit[4] = { "A", "V", "V", "KV" };
auto str = (boost::format("%4.3f [%s]") % tm % unit[ch]).str();
if(mesa_type_->get_select_pos() >= 3) {
float t = time_meas_delay_
/ get_time_unit_base_(time_.scale_->get_select_pos());
auto u = get_time_unit_str_(time_.scale_->get_select_pos());
str += (boost::format(", %3.2f %s") % t % u).str();
}
ch_to_time_->set_text(str);
}
mesa_value_ = tm;
}
std::string proj_root_;
utils::select_file data_load_filer_;
utils::select_file data_save_filer_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
wave_cap(utils::director<core>& d, CLIENT& client, interlock& ilock) :
director_(d), client_(client), interlock_(ilock), waves_(),
frame_(nullptr), core_(nullptr),
terminal_frame_(nullptr), terminal_core_(nullptr),
tools_(nullptr), smooth_(nullptr), load_(nullptr), save_(nullptr),
mesa_type_(nullptr), mesa_filt_(nullptr),
org_trg_(nullptr), org_slope_(nullptr), org_ena_(nullptr),
fin_trg_(nullptr), fin_slope_(nullptr), fin_ena_(nullptr),
time_mesa_ch_(nullptr), time_delay_(nullptr), time_delay_ena_(nullptr),
ch_to_time_(nullptr), wdm_exec_(nullptr),
meas_id_before_(0), meas_id_(0), org_value_(0.0f), fin_value_(0.0f),
share_frame_(nullptr),
sample_param_(),
wdm_id_{ 0 }, treg_id_{ 0 },
treg_1st_(), treg_2nd_(), treg_value_(0.0f), treg_value2_(0.0f),
treg_value_id_(0),
info_in_(false), info_org_(0), info_(),
chn0_(waves_, 1.25f),
chn1_(waves_, 1.25f),
chn2_(waves_, 1.25f),
chn3_(waves_, 1.25f),
measure_time_(waves_),
time_(waves_), time_id_(0), size_(0),
mesa_value_(0.0), mesa_id_(0), time_meas_delay_(0.0),
proj_root_(), data_load_filer_(), data_save_filer_()
{ }
//-----------------------------------------------------------------//
/*!
@brief プロジェクト・ルートの設定
@param[in] root プロジェクト・ルート
*/
//-----------------------------------------------------------------//
void set_project_root(const std::string& root)
{
proj_root_ = root;
}
//-----------------------------------------------------------------//
/*!
@brief 計測結果の取得
@return 計測結果
*/
//-----------------------------------------------------------------//
uint32_t get_mesa_id() const {
return mesa_id_;
}
//-----------------------------------------------------------------//
/*!
@brief 計測結果の取得
@return 計測結果
*/
//-----------------------------------------------------------------//
double get_mesa_value() const {
return mesa_value_;
}
//-----------------------------------------------------------------//
/*!
@brief 時間スケール値を取得
@return 時間スケール値
*/
//-----------------------------------------------------------------//
double get_time_scale() const {
uint32_t newpos = time_.scale_->get_select_pos();
return get_time_unit_(newpos) / get_time_unit_base_(newpos);
}
//-----------------------------------------------------------------//
/*!
@brief 電圧スケール値を取得
@param[in] ch チャネル
@return 電圧スケール値
*/
//-----------------------------------------------------------------//
float get_volt_scale(uint32_t ch) const
{
uint32_t newpos = 0;
switch(ch) {
case 0:
newpos = chn0_.scale_->get_select_pos();
break;
case 1:
newpos = chn1_.scale_->get_select_pos();
break;
case 2:
newpos = chn2_.scale_->get_select_pos();
break;
case 3:
newpos = chn3_.scale_->get_select_pos();
break;
default:
break;
}
return get_volt_scale_value_(ch, newpos);
}
//-----------------------------------------------------------------//
/*!
@brief 波形情報の取得
@return 波形情報
*/
//-----------------------------------------------------------------//
const info_t& get_info() const { return info_; }
//-----------------------------------------------------------------//
/*!
@brief 転送ボタンを取得
@return 転送ボタン
*/
//-----------------------------------------------------------------//
gui::widget_button* get_exec_button() const { return wdm_exec_; }
//-----------------------------------------------------------------//
/*!
@brief 測定単位文字列の取得
@return 測定単位文字列
*/
//-----------------------------------------------------------------//
std::string get_unit_str() const {
std::string u;
auto n = mesa_type_->get_select_pos();
if(n == 0 || n == 1) { // 時間
return get_time_unit_str_(time_.scale_->get_select_pos());
} else { // 電圧
auto ch = time_mesa_ch_->get_select_pos();
static const char* unit[4] = { "A", "V", "V", "KV" };
return unit[ch];
}
return u;
}
float get_treg_value() const { return treg_value_; }
float get_treg_value2() const { return treg_value2_; }
uint32_t get_treg_value_id() const { return treg_value_id_; }
//-----------------------------------------------------------------//
/*!
@brief 許可、不許可
@param[in] ena 不許可の場合「false」
*/
//-----------------------------------------------------------------//
void enable(bool ena = true)
{
using namespace gui;
widget_director& wd = director_.at().widget_director_;
if(frame_->get_enable() != ena) {
wd.enable(frame_, ena, true);
wd.enable(tools_, ena, true);
wd.enable(terminal_frame_, ena, true);
}
}
//-----------------------------------------------------------------//
/*!
@brief サンプリング・パラメーターの設定
@param[in] rate サンプリング・パラメーター
*/
//-----------------------------------------------------------------//
void set_sample_param(const sample_param& sp) { sample_param_ = sp; }
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void initialize()
{
using namespace gui;
widget_director& wd = director_.at().widget_director_;
size_.set(930, 820);
{ // 波形描画フレーム
widget::param wp(vtx::irect(610, 5, size_.x, size_.y));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
wp_.color_param_.fore_color_ = img::rgba8(65, 100, 150);
wp_.color_param_.back_color_ = wp_.color_param_.fore_color_ * 0.7f;
frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{ // 波形描画ビュー
widget::param wp(vtx::irect(0), frame_);
widget_view::param wp_;
wp_.update_func_ = [=]() {
update_view_();
};
wp_.render_func_ = [=](const vtx::irect& clip) {
render_view_(clip);
};
wp_.service_func_ = [=]() {
service_view_();
};
core_ = wd.add_widget<widget_view>(wp, wp_);
}
{ // ターミナル
{
widget::param wp(vtx::irect(270, 610, 330, 220));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::irect(0), terminal_frame_);
widget_terminal::param wp_;
wp_.enter_func_ = [=](const utils::lstring& text) {
// term_enter_(text);
};
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
term_chaout::set_output(terminal_core_);
}
}
int mw = 330;
int mh = 600;
{ // 波形ツールフレーム
widget::param wp(vtx::irect(270, 5, mw, mh));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
tools_ = wd.add_widget<widget_frame>(wp, wp_);
tools_->set_state(gui::widget::state::SIZE_LOCK);
}
{ // スムース
widget::param wp(vtx::irect(10, 20, 110, 40), tools_);
widget_check::param wp_("Smooth");
smooth_ = wd.add_widget<widget_check>(wp, wp_);
}
{ // ロード
widget::param wp(vtx::irect(140, 20, 80, 40), tools_);
widget_button::param wp_("Load");
load_ = wd.add_widget<widget_button>(wp, wp_);
load_->at_local_param().select_func_ = [=](uint32_t id) {
std::string filter = "波形データ(*.";
filter += WAVE_DATA_EXT_;
filter += ")\t*.";
filter += WAVE_DATA_EXT_;
filter += "\t";
data_load_filer_.open(filter, false, proj_root_);
};
}
{ // セーブ
widget::param wp(vtx::irect(230, 20, 80, 40), tools_);
widget_button::param wp_("Save");
save_ = wd.add_widget<widget_button>(wp, wp_);
save_->at_local_param().select_func_ = [=](uint32_t id) {
std::string filter = "波形データ(*.";
filter += WAVE_DATA_EXT_;
filter += ")\t*.";
filter += WAVE_DATA_EXT_;
filter += "\t";
data_save_filer_.open(filter, true, proj_root_);
};
}
{ // 計測開始チャネルとスロープ
widget::param wp(vtx::irect(10, 120, 110, 40), tools_);
widget_list::param wp_;
wp_.init_list_.push_back("CH1 ↑");
wp_.init_list_.push_back("CH1 ↓");
wp_.init_list_.push_back("CH2 ↑");
wp_.init_list_.push_back("CH2 ↓");
wp_.init_list_.push_back("CH3 ↑");
wp_.init_list_.push_back("CH3 ↓");
wp_.init_list_.push_back("CH4 ↑");
wp_.init_list_.push_back("CH4 ↓");
org_trg_ = wd.add_widget<widget_list>(wp, wp_);
org_trg_->at_local_param().select_func_ = [=](const std::string& t, uint32_t p) {
++meas_id_;
};
}
{ // 計測開始トリガー・レベル
widget::param wp(vtx::irect(130, 120, 110, 40), tools_);
widget_spinbox::param wp_(0, 50, 100);
org_slope_ = wd.add_widget<widget_spinbox>(wp, wp_);
org_slope_->at_local_param().select_func_ =
[=](widget_spinbox::state st, int before, int newpos) {
++meas_id_;
return (boost::format("%d") % newpos).str();
};
}
{ // 計測終了チャネルとスロープ
widget::param wp(vtx::irect(10, 170, 110, 40), tools_);
widget_list::param wp_;
wp_.init_list_.push_back("CH1 ↑");
wp_.init_list_.push_back("CH1 ↓");
wp_.init_list_.push_back("CH2 ↑");
wp_.init_list_.push_back("CH2 ↓");
wp_.init_list_.push_back("CH3 ↑");
wp_.init_list_.push_back("CH3 ↓");
wp_.init_list_.push_back("CH4 ↑");
wp_.init_list_.push_back("CH4 ↓");
fin_trg_ = wd.add_widget<widget_list>(wp, wp_);
fin_trg_->at_local_param().select_func_ = [=](const std::string& t, uint32_t p) {
++meas_id_;
};
}
{ // 計測終了トリガー・レベル
widget::param wp(vtx::irect(130, 170, 110, 40), tools_);
widget_spinbox::param wp_(0, 50, 100);
fin_slope_ = wd.add_widget<widget_spinbox>(wp, wp_);
fin_slope_->at_local_param().select_func_ =
[=](widget_spinbox::state st, int before, int newpos) {
++meas_id_;
return (boost::format("%d") % newpos).str();
};
}
{ // 時間計測チャネル
widget::param wp(vtx::irect(10, 220, 110, 40), tools_);
widget_list::param wp_;
wp_.init_list_.push_back("CH1");
wp_.init_list_.push_back("CH2");
wp_.init_list_.push_back("CH3");
wp_.init_list_.push_back("CH4");
time_mesa_ch_ = wd.add_widget<widget_list>(wp, wp_);
time_mesa_ch_->at_local_param().select_func_ = [=](const std::string& t,
uint32_t p) {
++meas_id_;
};
}
{ // 計測ディレイ
widget::param wp(vtx::irect(10 + 120, 220, 110, 40), tools_);
wp.pre_group_ = widget::PRE_GROUP::_1;
auto grid = waves_.get_info().grid_step_;
widget_spinbox::param wp_(-size_.x / grid * 4, 0, size_.x / grid * 4);
time_delay_ = wd.add_widget<widget_spinbox>(wp, wp_);
time_delay_->at_local_param().select_func_ =
[=](widget_spinbox::state st, int before, int newpos) {
auto grid = waves_.get_info().grid_step_;
waves_.at_info().delay_pos_ = newpos * grid / 4
+ (-time_.offset_->get_select_pos() * grid);
float t = get_time_unit_(time_.scale_->get_select_pos());
time_meas_delay_ = t * static_cast<double>(newpos) / 4.0;
++meas_id_;
return (boost::format("%d") % newpos).str();
};
}
{ // 計測ディレイ、ライン描画
widget::param wp(vtx::irect(250, 220, 100, 40), tools_);
widget_check::param wp_("Del");
time_delay_ena_ = wd.add_widget<widget_check>(wp, wp_);
}
{ // 計測時間表示
widget::param wp(vtx::irect(10, 270, 260, 40), tools_);
widget_text::param wp_;
ch_to_time_ = wd.add_widget<widget_text>(wp, wp_);
}
{ // 共有フレーム(プロパティシート)
widget::param wp(vtx::irect(5, 310, mw - 10, mh - 310 - 5), tools_);
widget_sheet::param wp_;
share_frame_ = wd.add_widget<widget_sheet>(wp, wp_);
}
measure_time_.init(director_, share_frame_, "Time Measure");
chn0_.init(director_, share_frame_, 0);
chn1_.init(director_, share_frame_, 1);
chn2_.init(director_, share_frame_, 2);
chn3_.init(director_, share_frame_, 3);
time_.init(director_, share_frame_);
{ // 計測タイプ
widget::param wp(vtx::irect(10, 20 + 50, 140, 40), tools_);
widget_list::param wp_;
wp_.init_list_.push_back("SINGLE T");
wp_.init_list_.push_back("MULTI T");
wp_.init_list_.push_back("SINGLE V");
wp_.init_list_.push_back("Max");
wp_.init_list_.push_back("Min");
wp_.init_list_.push_back("Average");
mesa_type_ = wd.add_widget<widget_list>(wp, wp_);
mesa_type_->at_local_param().select_func_ = [=](const std::string& t, uint32_t p) {
};
}
{ // 計測フィルタ係数
widget::param wp(vtx::irect(10 + 150, 20 + 50, 110, 40), tools_);
widget_label::param wp_("1.0", false);
mesa_filt_ = wd.add_widget<widget_label>(wp, wp_);
}
{ // 計測開始ボタン
widget::param wp(vtx::irect(270, 270, 30, 30), tools_);
widget_button::param wp_(">");
wdm_exec_ = wd.add_widget<widget_button>(wp, wp_);
}
{ // 計測ライン描画 (org)
widget::param wp(vtx::irect(250, 120, 90, 40), tools_);
widget_check::param wp_("1st");
org_ena_ = wd.add_widget<widget_check>(wp, wp_);
}
{ // 計測ライン描画 (fin)
widget::param wp(vtx::irect(250, 170, 90, 40), tools_);
widget_check::param wp_("2nd");
fin_ena_ = wd.add_widget<widget_check>(wp, wp_);
}
{ // help message (widget_chip)
widget::param wp(vtx::irect(0, 0, 100, 40), tools_);
widget_chip::param wp_;
chip_ = wd.add_widget<widget_chip>(wp, wp_);
chip_->active(0);
}
waves_.create_buffer();
waves_.at_param(0).color_ = img::rgba8(255, 64, 255, 255);
waves_.at_info().volt_color_[0] = waves_.get_param(0).color_;
waves_.at_param(1).color_ = img::rgba8( 64, 255, 255, 255);
waves_.at_info().volt_color_[1] = waves_.get_param(1).color_;
waves_.at_param(2).color_ = img::rgba8(255, 255, 32, 255);
waves_.at_info().volt_color_[2] = waves_.get_param(2).color_;
waves_.at_param(3).color_ = img::rgba8( 64, 255, 64, 255);
waves_.at_info().volt_color_[3] = waves_.get_param(3).color_;
#ifdef TEST_SIN
waves_.build_sin(0, sample_param_.rate, 15000.0, 1.0f);
waves_.build_sin(1, sample_param_.rate, 10000.0, 0.75f);
#endif
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void update()
{
if(frame_ == nullptr) return;
if(share_frame_ == nullptr) return;
auto sheetpos = share_frame_->get_select_pos();
switch(sheetpos) {
case 1:
case 2:
case 3:
case 4:
share_frame_->at_local_param().text_param_.fore_color_
= waves_.get_param(sheetpos - 1).color_;
break;
default:
share_frame_->at_local_param().text_param_.fore_color_
= img::rgba8( 255, 255, 255, 255);
break;
}
switch(mesa_type_->get_select_pos()) {
case 0: // トリガーからの時間計測
org_trg_->set_stall(false);
org_slope_->set_stall(false);
org_ena_->set_stall(false);
fin_trg_->set_stall();
fin_slope_->set_stall();
fin_ena_->set_stall();
time_mesa_ch_->set_stall();
time_delay_->set_stall();
time_delay_ena_->set_stall();
break;
case 1: // チャネル間時間計測
org_trg_->set_stall(false);
org_slope_->set_stall(false);
org_ena_->set_stall(false);
fin_trg_->set_stall(false);
fin_slope_->set_stall(false);
fin_ena_->set_stall(false);
time_mesa_ch_->set_stall();
time_delay_->set_stall();
time_delay_ena_->set_stall();
break;
case 2: // トリガーからの電圧
org_trg_->set_stall();
org_slope_->set_stall();
org_ena_->set_stall();
fin_trg_->set_stall();
fin_slope_->set_stall();
fin_ena_->set_stall();
time_mesa_ch_->set_stall(false);
time_delay_->set_stall();
time_delay_ena_->set_stall();
break;
case 3: // Max
case 4: // Min
case 5: // Average
org_trg_->set_stall();
org_slope_->set_stall();
org_ena_->set_stall();
fin_trg_->set_stall();
fin_slope_->set_stall();
fin_ena_->set_stall();
time_mesa_ch_->set_stall(false);
time_delay_->set_stall(false);
time_delay_ena_->set_stall(false);
break;
default:
break;
}
if(org_ena_->get_enable() && !org_ena_->get_stall()) {
waves_.at_info().meas_enable_[0] = org_ena_->get_check();
} else {
waves_.at_info().meas_enable_[0] = false;
}
if(fin_ena_->get_enable() && !fin_ena_->get_stall()) {
waves_.at_info().meas_enable_[1] = fin_ena_->get_check();
} else {
waves_.at_info().meas_enable_[1] = false;
}
if(time_delay_ena_->get_enable() && !time_delay_ena_->get_stall()) {
waves_.at_info().delay_enable_ = time_delay_ena_->get_check();
} else {
waves_.at_info().delay_enable_ = false;
}
wdm_exec_->set_stall(!client_.probe());
waves_.enable_smooth(smooth_->get_check());
measure_time_.tbp_ = time_.scale_->get_select_pos();
measure_time_.update(size_);
chn0_.update(0, size_, sample_param_.gain[0]);
chn1_.update(1, size_, sample_param_.gain[1]);
chn2_.update(2, size_, sample_param_.gain[2]);
chn3_.update(3, size_, sample_param_.gain[3]);
time_.update(size_, sample_param_.rate);
// 波形のコピー(中間位置がトリガーポイント)
{
uint32_t nnn = wdm_id_[3];
for(uint32_t i = 0; i < 4; ++i) {
auto id = client_.get_mod_status().wdm_id_[i];
if(wdm_id_[i] != id) {
auto sz = waves_.size();
waves_.copy(i, client_.get_wdm(i), sz, sz / 2);
wdm_id_[i] = id;
}
}
if(wdm_id_[3] != nnn) {
meas_run_();
++mesa_id_;
}
}
if(time_id_ != time_.id_) {
time_id_ = time_.id_;
++meas_id_;
}
// 時間計測 (single, multi)
if(meas_id_before_ != meas_id_) {
meas_run_();
meas_id_before_ = meas_id_;
}
// 仮熱抵抗表示
for(uint32_t i = 0; i < 2; ++i) {
auto id = client_.get_mod_status().treg_id_[i];
if(treg_id_[i] != id) {
auto sz = waves_.size();
if(i == 0) {
waves_.copy(1, client_.get_treg(i) + sz / 2, sz / 2, sz / 2);
} else {
waves_.copy(1, client_.get_treg(i) + sz / 2, sz / 2, 0);
// treg_2nd_ = waves_.analize(1, 1.0, (800.0 - 50.0), 100.0, 1.0);
// treg_1st_ = waves_.analize(1, 1.0, (1024.0 + 800.0 - 50.0), 100.0, 1.0);
treg_2nd_ = waves_.analize(1, 1.0, (800.0 - 100.0), 128.0 + 64.0, 1.0);
treg_1st_ = waves_.analize(1, 1.0, (1024.0 + 800.0 - 100.0), 128.0 + 64.0, 1.0);
// std::cout << "1ST: " << treg_1st_.average_ << std::endl;
// std::cout << "2ND: " << treg_2nd_.average_ << std::endl;
float a = treg_1st_.average_ - treg_2nd_.average_;
// std::cout << " D: " << a << std::endl;
float u = get_volt_scale_limit_(1);
treg_value_ = a * u / 64.0;
auto b = waves_.analize(1, 1.0, (256.0 - 32.0), 64.0, 1.0);
// std::cout << "3RD: " << b.average_ << std::endl;
treg_value2_ = b.average_ * u / 64.0;
++treg_value_id_;
}
treg_id_[i] = id;
}
}
{
uint32_t act = 60 * 3;
if(org_slope_->get_focus()) {
std::string s;
// tools::set_help(chip_, org_slope_, s);
} else if(fin_slope_->get_focus()) {
std::string s;
// tools::set_help(chip_, fin_slope_, s);
} else {
act = 0;
}
// chip_->active(act);
}
if(data_load_filer_.state()) {
auto path = data_load_filer_.get();
if(!path.empty()) {
if(utils::get_file_ext(path).empty()) {
path += '.';
path += WAVE_DATA_EXT_;
}
if(waves_.load(path)) {
++meas_id_;
}
}
}
if(data_save_filer_.state()) {
auto path = data_save_filer_.get();
if(!path.empty()) {
if(utils::get_file_ext(path).empty()) {
path += '.';
path += WAVE_DATA_EXT_;
}
if(waves_.save(path)) {
}
}
}
}
//-----------------------------------------------------------------//
/*!
@brief ロード
*/
//-----------------------------------------------------------------//
void load(sys::preference& pre)
{
if(frame_ != nullptr) {
frame_->load(pre);
}
if(terminal_frame_ != nullptr) {
terminal_frame_->load(pre);
}
if(tools_ != nullptr) {
tools_->load(pre);
}
if(smooth_ != nullptr) {
smooth_->load(pre);
smooth_->exec();
}
if(share_frame_ != nullptr) {
share_frame_->load(pre);
}
chn0_.load(pre);
chn1_.load(pre);
chn2_.load(pre);
chn3_.load(pre);
time_.load(pre);
measure_time_.load(pre);
mesa_type_->load(pre);
mesa_filt_->load(pre);
org_trg_->load(pre);
org_slope_->load(pre);
org_slope_->exec();
org_ena_->load(pre);
fin_trg_->load(pre);
fin_slope_->load(pre);
fin_slope_->exec();
fin_ena_->load(pre);
time_mesa_ch_->load(pre);
time_delay_->load(pre);
time_delay_->exec();
time_delay_ena_->load(pre);
}
//-----------------------------------------------------------------//
/*!
@brief セーブ
*/
//-----------------------------------------------------------------//
void save(sys::preference& pre)
{
if(frame_ != nullptr) {
frame_->save(pre);
}
if(terminal_frame_ != nullptr) {
terminal_frame_->save(pre);
}
if(tools_ != nullptr) {
tools_->save(pre);
}
if(smooth_ != nullptr) {
smooth_->save(pre);
}
if(share_frame_ != nullptr) {
share_frame_->save(pre);
}
chn0_.save(pre);
chn1_.save(pre);
chn2_.save(pre);
chn3_.save(pre);
time_.save(pre);
measure_time_.save(pre);
mesa_type_->save(pre);
mesa_filt_->save(pre);
org_trg_->save(pre);
org_slope_->save(pre);
org_ena_->save(pre);
fin_trg_->save(pre);
fin_slope_->save(pre);
fin_ena_->save(pre);
time_mesa_ch_->save(pre);
time_delay_->save(pre);
time_delay_ena_->save(pre);
}
//-----------------------------------------------------------------//
/*!
@brief 波形画像のセーブ
@param[in] path セーブ・パス
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool save_image(const std::string& path) const
{
bool ret = false;
if(path.empty()) return ret;
if(core_ == nullptr) return ret;
vtx::ipos pos;
gui::final_position(core_, pos);
const auto& size = core_->get_param().rect_.size;
auto simg = gl::get_frame_buffer(pos.x , pos.y, size.x, size.y);
img::img_files imfs;
imfs.set_image(simg);
ret = imfs.save(path);
return ret;
}
};
}
| 29.128045 | 87 | 0.570053 | hirakuni45 |
1c335d8ac66d30a5efbf1793619b536b257d977d | 4,640 | cc | C++ | cpp/common/protocol-extension-manager_test.cc | nathanawmk/SPARTA | 6eeb28b2dd147088b6e851876b36eeba3e700f16 | [
"BSD-2-Clause"
] | 37 | 2017-06-09T13:55:23.000Z | 2022-01-28T12:51:17.000Z | cpp/common/protocol-extension-manager_test.cc | nathanawmk/SPARTA | 6eeb28b2dd147088b6e851876b36eeba3e700f16 | [
"BSD-2-Clause"
] | null | null | null | cpp/common/protocol-extension-manager_test.cc | nathanawmk/SPARTA | 6eeb28b2dd147088b6e851876b36eeba3e700f16 | [
"BSD-2-Clause"
] | 5 | 2017-06-09T13:55:26.000Z | 2021-11-11T03:51:56.000Z | //*****************************************************************
// Copyright 2015 MIT Lincoln Laboratory
// Project: SPAR
// Authors: OMD
// Description: Unit tests for ProtocolExtensionManager
//
// Modifications:
// Date Name Modification
// ---- ---- ------------
// 08 May 2012 omd Original Version
//*****************************************************************
#define BOOST_TEST_MODULE ProtocolExtensionManagerTest
#include <boost/thread.hpp>
#include <string>
#include <sstream>
#include <unistd.h>
#include "line-raw-parser.h"
#include "protocol-extension-manager.h"
#include "statics.h"
#include "test-init.h"
#include "types.h"
using std::string;
using std::ostream;
using std::istream;
using std::endl;
// Define a few simple protocol extensions.
// This extension doesn't do any further parsing - when it's command is received
// it simply increments num_times_called_ and returns.
class DoCommandExtension : public ProtocolExtension {
public:
DoCommandExtension() : num_times_called_(0) {
}
virtual void OnProtocolStart(Knot start_line) {
BOOST_CHECK_EQUAL(start_line, "DO");
++num_times_called_;
Done();
}
int num_times_called() {
return num_times_called_;
}
private:
int num_times_called_;
};
// This extension expects to be triggered by "LINE" and then recieve one line of
// data and one chunk of RAW data.
class BufferExtension : public ProtocolExtension {
public:
BufferExtension() : got_line_(false) {}
virtual void OnProtocolStart(Knot start_line) {
BOOST_CHECK_EQUAL(start_line, "LINE");
}
virtual void LineReceived(Knot data) {
BOOST_CHECK_EQUAL(got_line_, false);
line_received_ = data;
got_line_ = true;
}
virtual void RawReceived(Knot data) {
BOOST_CHECK_EQUAL(got_line_, true);
raw_received_ = data;
Done();
}
Knot line_received_;
Knot raw_received_;
private:
bool got_line_;
};
// This extension tests that we are in fact triggering on the 1st word on the
// line. It will be registered with "NUMBER" and it expects to have
// OnProtocolStart called with "NUMBER 1", "NUMBER 2", etc. and will use
// BOOST_CHECK_EQUAL to ensure that is, in fact, what is received.
class NumberExtension : public ProtocolExtension {
public:
NumberExtension() : next_number_(1) {}
virtual void OnProtocolStart(Knot start_line) {
std::stringstream expected_line;
expected_line << "NUMBER " << next_number_;
++next_number_;
BOOST_CHECK_EQUAL(start_line, expected_line.str());
Done();
}
int GetLastNumberReceived() const {
return next_number_ - 1;
}
private:
int next_number_;
};
Strand* GetStrand(const char* data) {
return new StringStrand(new string(data));
}
// Create a ProtocolExtensionManager using the DoCommandExtension and
// BufferLineExtension as extensions. Send it appropriate data and make sure it
// is processed as expected.
BOOST_AUTO_TEST_CASE(TestBasicFunctionality) {
ProtocolExtensionManager* manager = new ProtocolExtensionManager;
DoCommandExtension* do_extension = new DoCommandExtension;
BufferExtension* buffer_extension = new BufferExtension;
manager->AddHandler("DO", do_extension);
manager->AddHandler("LINE", buffer_extension);
LineRawParser parser(manager);
parser.DataReceived(GetStrand("DO\n"));
BOOST_CHECK_EQUAL(do_extension->num_times_called(), 1);
parser.DataReceived(GetStrand("LINE\n"));
parser.DataReceived(GetStrand("This should get buffered\n"));
parser.DataReceived(GetStrand("RAW\n3\nabcENDRAW\n"));
// As above, the CHECK_EQUAL is redundant as the test will deadlock if this is
// false.
BOOST_CHECK_EQUAL(buffer_extension->line_received_,
"This should get buffered");
BOOST_CHECK_EQUAL(buffer_extension->raw_received_, "abc");
parser.DataReceived(GetStrand("DO\n"));
BOOST_CHECK_EQUAL(do_extension->num_times_called(), 2);
parser.DataReceived(GetStrand("DO\n"));
BOOST_CHECK_EQUAL(do_extension->num_times_called(), 3);
}
// Test that it's the *start* of the line that triggers the sub-protocol and
// that the full line that triggered is passed to the extension.
BOOST_AUTO_TEST_CASE(TestTokenIsLineStart) {
ProtocolExtensionManager* manager = new ProtocolExtensionManager;
NumberExtension* number_extension = new NumberExtension;
manager->AddHandler("NUMBER", number_extension);
LineRawParser parser(manager);
parser.DataReceived(GetStrand("NUMBER 1\n"));
parser.DataReceived(GetStrand("NUMBER 2\n"));
BOOST_CHECK_EQUAL(number_extension->GetLastNumberReceived(), 2);
}
| 29.935484 | 80 | 0.706466 | nathanawmk |
1c35877c5304425b196fab15bcc321748b2c5c27 | 1,186 | cpp | C++ | 3rd-party/gloox/src/tests/vcard/vcard_test.cpp | ForNeVeR/cthulhu-bot | bee022cf03c17c75d01cbc8c2cdb5c888859fbc0 | [
"MIT"
] | null | null | null | 3rd-party/gloox/src/tests/vcard/vcard_test.cpp | ForNeVeR/cthulhu-bot | bee022cf03c17c75d01cbc8c2cdb5c888859fbc0 | [
"MIT"
] | 1 | 2017-07-22T04:10:51.000Z | 2017-07-22T04:10:51.000Z | 3rd-party/gloox/src/tests/vcard/vcard_test.cpp | ForNeVeR/cthulhu-bot | bee022cf03c17c75d01cbc8c2cdb5c888859fbc0 | [
"MIT"
] | null | null | null | #include "../../tag.h"
#define VCARD_TEST
#include "../../vcard.h"
#include "../../iq.h"
#include "../../stanzaextensionfactory.h"
using namespace gloox;
#include <stdio.h>
#include <locale.h>
#include <string>
#include <cstdio> // [s]print[f]
int main( int /*argc*/, char** /*argv*/ )
{
int fail = 0;
std::string name;
Tag *t;
// -------
{
name = "empty vcard request";
VCard v;
t = v.tag();
if( !t || t->xml() != "<vCard xmlns='" + XMLNS_VCARD_TEMP + "' version='3.0'/>" )
{
++fail;
printf( "test '%s' failed\n", name.c_str() );
}
delete t;
t = 0;
}
// -------
name = "VCard/SEFactory test";
StanzaExtensionFactory sef;
sef.registerExtension( new VCard() );
Tag* f = new Tag( "iq" );
new Tag( f, "vCard", "xmlns", XMLNS_VCARD_TEMP );
IQ iq( IQ::Set, JID(), "" );
sef.addExtensions( iq, f );
const VCard* se = iq.findExtension<VCard>( ExtVCard );
if( se == 0 )
{
++fail;
printf( "test '%s' failed\n", name.c_str() );
}
delete f;
printf( "VCard: " );
if( fail == 0 )
{
printf( "OK\n" );
return 0;
}
else
{
printf( "%d test(s) failed\n", fail );
return 1;
}
}
| 18.825397 | 85 | 0.524452 | ForNeVeR |
1c40415d373b86ce2e000fe8d3cd0e1c51117f3c | 977 | cpp | C++ | UnitTests/TestApp/ActionCreateData.cpp | lmj0591/mygui | 311fb9d07089f64558eb7f77e9b37c4cb91e3559 | [
"MIT"
] | 590 | 2015-01-06T09:22:06.000Z | 2022-03-21T18:23:02.000Z | UnitTests/TestApp/ActionCreateData.cpp | lmj0591/mygui | 311fb9d07089f64558eb7f77e9b37c4cb91e3559 | [
"MIT"
] | 159 | 2015-01-07T03:34:23.000Z | 2022-02-21T21:28:51.000Z | UnitTests/TestApp/ActionCreateData.cpp | lmj0591/mygui | 311fb9d07089f64558eb7f77e9b37c4cb91e3559 | [
"MIT"
] | 212 | 2015-01-05T07:33:33.000Z | 2022-03-28T22:11:51.000Z | /*!
@file
@author Albert Semenov
@date 07/2012
*/
#include "ActionCreateData.h"
#include "DataManager.h"
#include "DataInfoManager.h"
namespace tools
{
ActionCreateData::ActionCreateData() :
mData(nullptr),
mComplete(false)
{
}
ActionCreateData::~ActionCreateData()
{
if (mData != nullptr && !mComplete)
{
delete mData;
mData = nullptr;
}
}
void ActionCreateData::doAction()
{
if (mData == nullptr)
{
mData = new Data();
mData->setType(DataInfoManager::getInstance().getData("ResourceImageSet"));
mData->setPropertyValue("Name", mName);
}
DataManager::getInstance().getRoot()->addChild(mData);
DataManager::getInstance().invalidateDatas();
mComplete = true;
}
void ActionCreateData::undoAction()
{
DataManager::getInstance().getRoot()->removeChild(mData);
DataManager::getInstance().invalidateDatas();
mComplete = false;
}
void ActionCreateData::setName(const std::string& _value)
{
mName = _value;
}
}
| 17.446429 | 78 | 0.685773 | lmj0591 |
1c411dcc0af191b98cd80279397079a8023804be | 1,889 | hh | C++ | third_party/gst-plugins-bad/ext/soundtouch/gstbpmdetect.hh | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 6 | 2020-09-22T18:07:15.000Z | 2021-10-21T01:34:04.000Z | third_party/gst-plugins-bad/ext/soundtouch/gstbpmdetect.hh | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 2 | 2020-11-10T13:17:39.000Z | 2022-03-30T11:22:14.000Z | third_party/gst-plugins-bad/ext/soundtouch/gstbpmdetect.hh | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 3 | 2020-09-26T08:40:35.000Z | 2021-10-21T01:33:56.000Z | /* GStreamer
* Copyright (C) 2008 Sebastian Dröge <slomo@circular-chaos.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef __GST_BPM_DETECT_H__
#define __GST_BPM_DETECT_H__
#include <gst/gst.h>
#include <gst/base/gstbasetransform.h>
#include <gst/audio/gstaudiofilter.h>
G_BEGIN_DECLS
#define GST_TYPE_BPM_DETECT (gst_bpm_detect_get_type())
#define GST_BPM_DETECT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_BPM_DETECT,GstBPMDetect))
#define GST_IS_BPM_DETECT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_BPM_DETECT))
#define GST_BPM_DETECT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), GST_TYPE_BPM_DETECT,GstBPMDetectClass))
#define GST_IS_BPM_DETECT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), GST_TYPE_BPM_DETECT))
typedef struct _GstBPMDetect GstBPMDetect;
typedef struct _GstBPMDetectClass GstBPMDetectClass;
typedef struct _GstBPMDetectPrivate GstBPMDetectPrivate;
struct _GstBPMDetect {
GstAudioFilter element;
gfloat bpm;
GstBPMDetectPrivate *priv;
};
struct _GstBPMDetectClass {
GstAudioFilterClass parent_class;
};
GType gst_bpm_detect_get_type (void);
G_END_DECLS
#endif /* __GST_BPM_DETECT_H__ */
| 32.016949 | 112 | 0.779248 | isabella232 |
1c4334b8a676fe4fac0b81940104cb3ec6a43d1a | 1,930 | cpp | C++ | example/op_zip_iterator.cpp | aguinet/llvm-intptrcleanup | 9b1267dc9752922143965f1103288f6899f9415f | [
"BSD-3-Clause"
] | null | null | null | example/op_zip_iterator.cpp | aguinet/llvm-intptrcleanup | 9b1267dc9752922143965f1103288f6899f9415f | [
"BSD-3-Clause"
] | null | null | null | example/op_zip_iterator.cpp | aguinet/llvm-intptrcleanup | 9b1267dc9752922143965f1103288f6899f9415f | [
"BSD-3-Clause"
] | null | null | null | #include <algorithm>
#include <iterator>
#define RANDOM_IT
#ifdef RANDOM_IT
struct add_zip_iterator: public std::iterator<std::random_access_iterator_tag, int>
#else
struct add_zip_iterator: public std::iterator<std::forward_iterator_tag, int>
#endif
{
int* a;
int* b;
using traits = std::iterator_traits<add_zip_iterator>;
add_zip_iterator() { }
add_zip_iterator(int* a_, int* b_):
a(a_), b(b_)
{ }
add_zip_iterator(add_zip_iterator const&) = default;
add_zip_iterator(add_zip_iterator&&) = default;
inline int operator*() const { return *a + *b; }
inline add_zip_iterator& operator++() {
++a; ++b;
return *this;
}
inline add_zip_iterator operator++(int) const {
add_zip_iterator ret;
ret.a = a+1;
ret.b = b+1;
return ret;
}
inline bool operator==(add_zip_iterator const& o) const
{
return (o.a == a) && (o.b == b);
}
inline bool operator!=(add_zip_iterator const& o) const
{
return !(*this == o);
}
#ifdef RANDOM_IT
inline add_zip_iterator& operator+=(traits::difference_type n)
{
a += n; b += n;
return *this;
}
inline add_zip_iterator operator+(traits::difference_type n) const
{
return add_zip_iterator{a+n, b+n};
}
inline add_zip_iterator& operator-=(traits::difference_type n)
{
a -= n; b -= n;
return *this;
}
inline add_zip_iterator operator-(traits::difference_type n) const
{
return add_zip_iterator{a-n, b-n};
}
inline int operator[](traits::difference_type n) const
{
return *(a+n) + *(b+n);
}
inline difference_type operator-(add_zip_iterator const& o) const
{
return o.a - a;
}
#endif
};
void op_distance(int* res, add_zip_iterator const it, add_zip_iterator const it_end)
{
const size_t n = std::distance(it, it_end);
std::copy_n(it, n, res);
}
void op(int* res, add_zip_iterator const it, add_zip_iterator const it_end)
{
std::copy(it, it_end, res);
}
| 21.685393 | 84 | 0.665803 | aguinet |
1c440155b03beee5ee8039970d6cad6fe77ce1a8 | 792 | hpp | C++ | book/not_so_basics/testing/Dealer.hpp | luanics/cpp-illustrated | 6049de2119a53d656a63b65d9441e680355ef196 | [
"MIT"
] | null | null | null | book/not_so_basics/testing/Dealer.hpp | luanics/cpp-illustrated | 6049de2119a53d656a63b65d9441e680355ef196 | [
"MIT"
] | null | null | null | book/not_so_basics/testing/Dealer.hpp | luanics/cpp-illustrated | 6049de2119a53d656a63b65d9441e680355ef196 | [
"MIT"
] | null | null | null | #pragma once
#include "Action.hpp"
#include "Hand.hpp"
namespace luanics::cards::blackjack {
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
///
/// @class Dealer
///
/// @brief Following standard rules, hits until 17 reached.
///
/// Dealer takes action based on own hand only.
///
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
class Dealer {
public:
static constexpr int minScore = 17;
Action nextActionGiven(Hand const & dealers) {
if (dealers.score() < minScore) {
return Action::HIT;
}
else {
return Action::STAND;
}
}
}; // class Dealer
} // namespace luanics::cards::blackjack
| 23.294118 | 69 | 0.431818 | luanics |
1c44630469d3718b7cca2a5836a6ccebe4c1ea7c | 304 | cpp | C++ | Tasks/year3-demo-workspace/Lecture01-PortOut/main.cpp | ConnorD02/Embedded-Systems | 3e42b3da487fbe3bf7cfa897a6dd4cdb568d97e1 | [
"Apache-2.0"
] | 33 | 2020-08-05T12:58:51.000Z | 2022-03-28T12:00:20.000Z | Tasks/year3-demo-workspace/Lecture01-PortOut/main.cpp | ConnorD02/Embedded-Systems | 3e42b3da487fbe3bf7cfa897a6dd4cdb568d97e1 | [
"Apache-2.0"
] | 37 | 2020-08-05T12:53:22.000Z | 2022-03-04T10:24:47.000Z | Tasks/year3-demo-workspace/Lecture01-PortOut/main.cpp | ConnorD02/Embedded-Systems | 3e42b3da487fbe3bf7cfa897a6dd4cdb568d97e1 | [
"Apache-2.0"
] | 51 | 2020-10-06T11:04:40.000Z | 2022-03-28T12:00:11.000Z | #include "mbed.h"
//BusOut leds(PC_2, PC_3, PC_6, PB_0, PB_7, PB_14);
PortOut portc(PortC, 0b0000000001001100);
PortOut portb(PortB, 0b0100000010000001);
int main() {
while (true) {
portb = 0;
portc = 0xFFFF;
wait_us(500000);
portb = 0xFFFF;
portc = 0;
wait_us(500000);
}
}
| 17.882353 | 51 | 0.634868 | ConnorD02 |
1c4bd5c65e452ac1098540af96b4d75f1d6b1ef9 | 41,013 | cxx | C++ | inetsrv/query/web/dll/ida.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/query/web/dll/ida.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/query/web/dll/ida.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1996 - 2001.
//
// File: ida.cxx
//
// Contents: Parser for an IDQ file
//
// History: 96/Jan/3 DwightKr Created
//
//----------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include <fsciexps.hxx>
//
// Constants
//
static WCHAR const wcsPRootVar[] = L"PROOT_";
unsigned const ccPRootVar = sizeof(wcsPRootVar)/sizeof(WCHAR) - 1;
static WCHAR const wcsIndexVar[] = L"INDEX_";
unsigned const ccIndexVar = sizeof(wcsIndexVar)/sizeof(WCHAR) - 1;
static WCHAR const wcsNNTP[] = L"NNTP_";
unsigned const ccNNTP = sizeof(wcsNNTP)/sizeof(WCHAR) - 1;
static WCHAR const wcsIMAP[] = L"IMAP_";
unsigned const ccIMAP = sizeof(wcsIMAP)/sizeof(WCHAR) - 1;
static WCHAR const wcsScanVar[] = L"SCAN_";
unsigned const ccScanVar = sizeof(wcsScanVar)/sizeof(WCHAR) - 1;
unsigned const ccStringizedGuid = 36;
BOOL ParseGuid( WCHAR const * pwcsGuid, GUID & guid );
//+---------------------------------------------------------------------------
//
// Member: CIDAFile::CIDAFile - public constructor
//
// Synopsis: Builds a CIDAFile object, initializes values
//
// Arguments: [wcsFileName] -- full path to IDQ file
//
// History: 13-Apr-96 KyleP Created.
//
//----------------------------------------------------------------------------
CIDAFile::CIDAFile( WCHAR const * wcsFileName, UINT codePage )
: _eOperation( CIDAFile::CiState ),
_wcsCatalog(0),
_wcsHTXFileName( 0 ),
_wcsLocale(0),
_cReplaceableParameters(0),
_refCount(0),
_codePage(codePage)
{
ULONG cwc = wcslen(wcsFileName);
if ( cwc >= sizeof(_wcsIDAFileName)/sizeof(WCHAR) )
{
ciGibDebugOut(( DEB_WARN, "Too long a path (%ws)\n", wcsFileName ));
THROW( CException( STATUS_INVALID_PARAMETER ));
}
RtlCopyMemory( _wcsIDAFileName, wcsFileName, (cwc+1) * sizeof(WCHAR) );
}
//+---------------------------------------------------------------------------
//
// Member: CIDAFile::~CIDAFile - public destructor
//
// History: 13-Apr-96 KyleP Created.
//
//----------------------------------------------------------------------------
CIDAFile::~CIDAFile()
{
Win4Assert( _refCount == 0 );
delete [] _wcsCatalog;
delete [] _wcsHTXFileName;
delete [] _wcsLocale;
}
//+---------------------------------------------------------------------------
//
// Member: CIDAFile::ParseFile, private
//
// Synopsis: Parses the given file and sets up the necessary variables
//
// History: 13-Apr-96 KyleP Created.
// 23-Jul-96 DwightKr Use mapped file I/O which checks
// ACLs and throws ACCESS_DENIED if
// not available.
//
//----------------------------------------------------------------------------
void CIDAFile::ParseFile()
{
//
// Parse the query parameters
//
XPtr<CFileMapView> xMapView;
TRY
{
xMapView.Set( new CFileMapView( _wcsIDAFileName ) );
xMapView->Init();
}
CATCH( CException, e )
{
if ( HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND ) == e.GetErrorCode() )
{
THROW( CIDQException( MSG_CI_IDQ_NOT_FOUND, 0 ) );
}
else
{
RETHROW();
}
}
END_CATCH
CFileBuffer idaFile( xMapView.GetReference(), _codePage );
//
// Process a line at a time, look for the [Admin] section and
// process lines within that section.
//
BOOL fAdminSection = FALSE;
int iLine = 0; // Start counting at line #1
for( ;; )
{
iLine++;
XGrowable<WCHAR> xLine;
ULONG cwcChar = idaFile.fgetsw( xLine );
if( 0 == cwcChar )
{
break;
}
WCHAR *pwcLine = xLine.Get();
//
// Skip ahead until we find a [Admin] section
//
if ( L'[' == *pwcLine )
{
if ( _wcsnicmp(pwcLine+1, L"Admin]", 6) == 0 )
fAdminSection = TRUE;
else
fAdminSection = FALSE;
continue;
}
//
// Ignore comments.
//
else if ( L'#' == *pwcLine )
continue;
if ( fAdminSection )
{
CQueryScanner scanner( pwcLine, FALSE );
ParseOneLine( scanner, iLine );
}
}
//
// Verify that the minimum set of parameters are specified.
//
//
// We must have all of the following:
//
// - a HTX file name
//
if ( 0 == _wcsHTXFileName )
{
// Report an error
ciGibDebugOut(( DEB_IERROR, "Template not found in IDA file.\n" ));
THROW( CIDQException(MSG_CI_IDQ_MISSING_TEMPLATEFILE, 0) );
}
//
// If no catalog was specified, use the default catalog in the registry
//
if ( 0 == _wcsCatalog )
{
ciGibDebugOut(( DEB_ITRACE, "Using default catalog\n" ));
WCHAR awcTmp[ MAX_PATH ];
ULONG cwcRequired = TheIDQRegParams.GetISDefaultCatalog( awcTmp,
MAX_PATH );
if ( cwcRequired > MAX_PATH )
THROW( CException(STATUS_INVALID_PARAMETER) );
cwcRequired++; // make room for termination
_wcsCatalog = new WCHAR[ cwcRequired ];
RtlCopyMemory( _wcsCatalog, awcTmp, cwcRequired * sizeof WCHAR );
}
}
//+---------------------------------------------------------------------------
//
// Member: CIDAFile::ParseOneLine, private
//
// Synopsis: Parses one line of the IDQ file
//
// Arguments: [scan] -- scanner initialized with the current line
// [iLine] -- current line number
//
// History: 13-Apr-96 KyleP Created.
//
//----------------------------------------------------------------------------
void CIDAFile::ParseOneLine( CQueryScanner & scan, unsigned iLine )
{
//
// Is this a comment line (does it start with #) or an empty line?
//
if ( scan.LookAhead() == PROP_REGEX_TOKEN || scan.LookAhead() == EOS_TOKEN )
{
return;
}
if ( scan.LookAhead() != TEXT_TOKEN ) // Better be a word
{
// Report an error
THROW( CIDQException( MSG_CI_IDQ_EXPECTING_NAME, iLine ) );
}
XPtrST<WCHAR> wcsAttribute( scan.AcqWord() );
if( wcsAttribute.GetPointer() == 0 ) // Better find a word
{
THROW( CIDQException( MSG_CI_IDQ_EXPECTING_TYPE, iLine ) );
}
scan.Accept();
if ( scan.LookAhead() != EQUAL_TOKEN )
{
// Report an error
THROW( CIDQException( MSG_CI_IDQ_EXPECTING_EQUAL, iLine ) );
}
scan.Accept();
if ( 0 == _wcsicmp( wcsAttribute.GetPointer(), ISAPI_CI_CATALOG ) )
GetStringValue( scan, iLine, &_wcsCatalog );
else if ( 0 == _wcsicmp( wcsAttribute.GetPointer(), ISAPI_CI_TEMPLATE ) )
GetStringValue( scan, iLine, &_wcsHTXFileName );
else if ( 0 == _wcsicmp( wcsAttribute.GetPointer(), ISAPI_CI_ADMIN_OPERATION ) )
{
WCHAR * pwcsTemp = 0;
GetStringValue( scan, iLine, &pwcsTemp );
XPtrST<WCHAR> xwcsTemp( pwcsTemp );
if ( 0 == pwcsTemp )
{
THROW( CIDQException( MSG_CI_IDA_INVALID_OPERATION, iLine ) );
}
else if ( 0 == _wcsicmp( pwcsTemp, wcsOpGetState ) )
_eOperation = CIDAFile::CiState;
else if ( 0 == _wcsicmp( pwcsTemp, wcsOpForceMerge ) )
_eOperation = CIDAFile::ForceMerge;
else if ( 0 == _wcsicmp( pwcsTemp, wcsOpScanRoots ) )
_eOperation = CIDAFile::ScanRoots;
else if ( 0 == _wcsicmp( pwcsTemp, wcsOpUpdateCache ) )
_eOperation = CIDAFile::UpdateCache;
else
{
THROW( CIDQException( MSG_CI_IDA_INVALID_OPERATION, iLine ) );
}
}
else if ( 0 == _wcsicmp( wcsAttribute.GetPointer(), ISAPI_CI_LOCALE ) )
{
GetStringValue( scan, iLine, &_wcsLocale );
}
else
{
//
// We've found a keyword/attribute that we don't support.
// Don't report an error. This will allow this version of the
// parser to work with newer .IDA file versions with new parameters.
//
ciGibDebugOut(( DEB_ERROR, "Invalid string in IDQ file: %ws\n", wcsAttribute.GetPointer() ));
}
}
//+---------------------------------------------------------------------------
//
// Member: CIDAFile::GetStringValue - private
//
// Synopsis: Gets the string value on the currenct line
//
// Arguments: [scan] -- scanner initialized with the current line
// [iLine] -- current line number
// [pwcsStringValue] -- value to put string into
//
// History: 13-Apr-96 KyleP Created.
//
//----------------------------------------------------------------------------
void CIDAFile::GetStringValue( CQueryScanner & scan,
unsigned iLine,
WCHAR ** pwcsStringValue )
{
if ( 0 != *pwcsStringValue )
{
ciGibDebugOut(( DEB_IWARN,
"Duplicate CiXX=value in IDA file on line #%d\n",
iLine ));
THROW( CIDQException(MSG_CI_IDQ_DUPLICATE_ENTRY, iLine) );
}
*pwcsStringValue = scan.AcqLine();
if ( IsAReplaceableParameter( *pwcsStringValue ) != eIsSimpleString )
{
_cReplaceableParameters++;
}
}
//+---------------------------------------------------------------------------
//
// Function: FindEntry, public
//
// Synopsis: Helper function for admin variable parsing.
//
// Arguments: [pwcsName] -- Variable name
// [fScan] -- TRUE for SCAN, FALSE for INDEX
// [pwcsBuf] -- Buffer for search token
//
// History: 10-Oct-96 KyleP Created.
//
//----------------------------------------------------------------------------
BOOL FindEntry( WCHAR const * * ppwcsName, BOOL fScan, WCHAR * pwcsBuf )
{
if ( 0 != _wcsnicmp( *ppwcsName, wcsPRootVar, ccPRootVar ) )
return FALSE;
//
// Scan or Index?
//
WCHAR const * pwcsOutputTag;
unsigned ccOutputTag;
if ( fScan )
{
pwcsOutputTag = wcsScanVar;
ccOutputTag = ccScanVar;
}
else
{
pwcsOutputTag = wcsIndexVar;
ccOutputTag = ccIndexVar;
}
//
// IMAP, NNTP or W3?
//
unsigned ccPrefix = ccOutputTag;
BOOL fW3 = FALSE;
BOOL fNNTP = FALSE;
BOOL fIMAP = FALSE;
if ( 0 == _wcsnicmp( *ppwcsName + ccPRootVar, wcsNNTP, ccNNTP ) )
{
fNNTP = TRUE;
*ppwcsName += ccNNTP;
ccPrefix += ccNNTP;
}
else if ( 0 == _wcsnicmp( *ppwcsName + ccPRootVar, wcsIMAP, ccIMAP ) )
{
fIMAP = TRUE;
*ppwcsName += ccIMAP;
ccPrefix += ccIMAP;
}
else
{
fW3 = TRUE;
}
*ppwcsName += ccPRootVar;
//
// Length check.
//
unsigned ccName = wcslen( *ppwcsName ) + 1;
if ( ccName + ccPrefix > (MAX_PATH + ccIndexVar + ccNNTP + 1) )
{
ciGibDebugOut(( DEB_WARN, "Path %ws too long for admin\n", *ppwcsName ));
return FALSE;
}
if ( ccName + ccPrefix > (MAX_PATH + ccIndexVar + ccIMAP + 1) )
{
ciGibDebugOut(( DEB_WARN, "Path %ws too long for admin\n", *ppwcsName ));
return FALSE;
}
//
// Build output name
//
RtlCopyMemory( pwcsBuf, pwcsOutputTag, ccOutputTag * sizeof(WCHAR) );
if ( fNNTP )
RtlCopyMemory( pwcsBuf + ccOutputTag, wcsNNTP, ccNNTP * sizeof(WCHAR) );
else if ( fIMAP )
RtlCopyMemory( pwcsBuf + ccOutputTag, wcsIMAP, ccIMAP * sizeof(WCHAR) );
RtlCopyMemory( pwcsBuf + ccPrefix, *ppwcsName, ccName * sizeof(WCHAR) );
return TRUE;
}
//+---------------------------------------------------------------------------
//
// Function: DoAdmin, public
//
// Synopsis: Executes an administrative change.
//
// Arguments: [wcsIDAFile] -- Virtual path to .IDA file
// [VarSet] -- Query variables
// [OutputFormat] -- Output format
// [vsResults] -- On success (non exception) result page
// written here.
//
// History: 13-Apr-96 KyleP Created.
// 22-Jul-96 DwightKr Make CiLocale replaceable & visible
// in HTX files
// 11-Jun-97 KyleP Use web server in Output Format
//
//----------------------------------------------------------------------------
void DoAdmin( WCHAR const * wcsIDAFile,
CVariableSet & VarSet,
COutputFormat & OutputFormat,
CVirtualString & vsResults )
{
//
// Parse .IDA file. We don't bother to cache these.
//
XPtr<CIDAFile> xIDAFile( new CIDAFile(wcsIDAFile, OutputFormat.CodePage()) );
xIDAFile->ParseFile();
ULONG cwcOut;
XPtrST<WCHAR> wcsLocaleID( ReplaceParameters( xIDAFile->GetLocale(),
VarSet,
OutputFormat,
cwcOut ) );
XArray<WCHAR> wcsLocale;
LCID locale = GetQueryLocale( wcsLocaleID.GetPointer(),
VarSet,
OutputFormat,
wcsLocale );
if ( OutputFormat.GetLCID() != locale )
{
ciGibDebugOut(( DEB_ITRACE,
"Wrong codePage used for loading IDA file, used 0x%x retrying with 0x%x\n",
OutputFormat.CodePage(),
LocaleToCodepage(locale) ));
//
// We've parsed the IDA file with the wrong locale.
//
delete xIDAFile.Acquire();
OutputFormat.LoadNumberFormatInfo( locale );
xIDAFile.Set( new CIDAFile(wcsIDAFile, OutputFormat.CodePage()) );
xIDAFile->ParseFile();
}
SetupDefaultCiVariables( VarSet );
SetupDefaultISAPIVariables( VarSet );
SetCGIVariables( VarSet, OutputFormat );
//
// Get the catalog.
//
XPtrST<WCHAR> wcsCiCatalog( ReplaceParameters( xIDAFile->GetCatalog(),
VarSet,
OutputFormat,
cwcOut ) );
//
// Verify that the wcsCatalog is valid
//
if ( !IsAValidCatalog( wcsCiCatalog.GetPointer(), cwcOut ) )
{
THROW( CIDQException(MSG_CI_IDQ_NO_SUCH_CATALOG, 0) );
}
//
// Get the catalog and machine from the URL style catalog.
//
XPtrST<WCHAR> wcsMachine( 0 );
XPtrST<WCHAR> wcsCatalog( 0 );
SCODE sc = ParseCatalogURL( wcsCiCatalog.GetPointer(),
wcsCatalog,
wcsMachine );
if (FAILED(sc))
{
THROW( CException(sc) );
}
Win4Assert ( 0 != wcsMachine.GetPointer() );
//
// Check that the client is allowed to perform administration
//
CheckAdminSecurity( wcsMachine.GetPointer() );
//
// Build the HTX page for [success] output
//
XPtrST<WCHAR> wcsTemplate( ReplaceParameters( xIDAFile->GetHTXFileName(),
VarSet,
OutputFormat,
cwcOut ) );
WCHAR wcsPhysicalName[_MAX_PATH];
if ( OutputFormat.IsValid() )
{
OutputFormat.GetPhysicalPath( wcsTemplate.GetPointer(),
wcsPhysicalName,
_MAX_PATH );
}
else
{
if ( !GetFullPathName( wcsTemplate.GetPointer(),
MAX_PATH,
wcsPhysicalName,
0 ) )
{
THROW( CException() );
}
}
//
// Note: Parsing of HTX file needs to be done in different locations
// to ensure variables added to variable set by admin operations
// are added before parse. But we also don't want to fail the
// parse *after* doing a dangerous operation (like force merge).
//
CSecurityIdentity securityStub;
CHTXFile SuccessHTX( wcsTemplate,
OutputFormat.CodePage(),
securityStub,
OutputFormat.GetServerInstance() );
switch ( xIDAFile->Operation() )
{
case CIDAFile::ScanRoots:
{
SuccessHTX.ParseFile( wcsPhysicalName, VarSet, OutputFormat );
if ( SuccessHTX.DoesDetailSectionExist() )
{
THROW( CIDQException(MSG_CI_IDA_TEMPLATE_DETAIL_SECTION, 0) );
}
//
// Execute the changes. 'Entries' have the following format:
// Variable: P<virtual root> = physical root for <virtual root>
// Variable: S<virtual root> = "on" / existence means root is scanned
// Variable: T<virtual root> = "on" / existence means full scan
//
CVariableSetIter iter( VarSet );
while ( !iter.AtEnd() )
{
CVariable * pVar = iter.Get();
WCHAR const * pwcsName = pVar->GetName();
WCHAR wcsScanName[MAX_PATH + ccScanVar + __max( ccNNTP, ccIMAP ) + 10 ];
if ( FindEntry( &pwcsName, // Starting variable
TRUE, // SCAN
wcsScanName )) // Matching search string returned here
{
PROPVARIANT * ppvPRoot = pVar->GetValue();
CVariable * pScanVar = VarSet.Find( wcsScanName );
if ( 0 != pScanVar )
{
WCHAR const * pwszScanType = pScanVar->GetStringValueRAW();
if ( 0 != pwszScanType &&
( 0 == _wcsicmp( pwszScanType, L"FullScan" ) ||
0 == _wcsicmp( pwszScanType, L"IncrementalScan")
) )
{
BOOL fFull = (0 == _wcsicmp( pwszScanType, L"FullScan" ));
SCODE sc = UpdateContentIndex( ppvPRoot->pwszVal,
wcsCatalog.GetPointer(),
wcsMachine.GetPointer(),
fFull );
if ( FAILED(sc) )
{
ciGibDebugOut(( DEB_ERROR,
"Error 0x%x scanning virtual scope %ws\n",
pwcsName ));
THROW( CException( sc ) );
}
}
}
}
iter.Next();
}
break;
}
case CIDAFile::UpdateCache:
{
SuccessHTX.ParseFile( wcsPhysicalName, VarSet, OutputFormat );
if ( SuccessHTX.DoesDetailSectionExist() )
{
THROW( CIDQException(MSG_CI_IDA_TEMPLATE_DETAIL_SECTION, 0) );
}
//
// Execute the changes. 'Entries' have the following format:
// Variable: CACHESIZE_<guid>_NAME_<name> = Size for named entry
// Variable: CACHESIZE_<guid>_PROPID_<propid> = Size for numbered entry
// Variable: CACHETYPE_<guid>_NAME_<name> = Type for named entry
// Variable: CACHETYPE_<guid>_PROPID_<propid> = Type for numbered entry
//
CVariableSetIter iter( VarSet );
BOOL fSawOne = FALSE;
ULONG_PTR ulToken;
SCODE sc = BeginCacheTransaction( &ulToken,
wcsCatalog.GetPointer(),
wcsCatalog.GetPointer(),
wcsMachine.GetPointer() );
if ( FAILED(sc) )
{
ciGibDebugOut(( DEB_ERROR, "Error 0x%x setting up cache transaction.\n", sc ));
THROW( CException( sc ) );
}
while ( !iter.AtEnd() )
{
CVariable * pVar = iter.Get();
WCHAR const * pwcsName = pVar->GetName();
//
// We write out last prop twice, 2nd time to commit everything.
//
//
// Constants.
//
static WCHAR const wcsSizeVar[] = L"CACHESIZE_";
unsigned ccSizeVar = sizeof(wcsSizeVar)/sizeof(WCHAR) - 1;
static WCHAR const wcsTypeVar[] = L"CACHETYPE_";
unsigned ccTypeVar = sizeof(wcsTypeVar)/sizeof(WCHAR) - 1;
if ( 0 == _wcsnicmp( pwcsName, wcsSizeVar, ccSizeVar ) )
{
CFullPropSpec ps;
//
// Parse the GUID.
//
unsigned cc = wcslen( pwcsName );
GUID guid;
if ( cc <= ccSizeVar || !ParseGuid( pwcsName + ccSizeVar, guid ) )
{
ciGibDebugOut(( DEB_WARN, "Improperly formatted CACHESIZE entry %ws\n", pwcsName ));
iter.Next();
continue;
}
ps.SetPropSet( guid );
//
// PROPID or string?
//
static WCHAR const wcsName[] = L"_NAME_";
unsigned ccName = sizeof(wcsName)/sizeof(WCHAR) - 1;
static WCHAR const wcsPropid[] = L"_PROPID_";
unsigned ccPropid = sizeof(wcsPropid)/sizeof(WCHAR) - 1;
if ( 0 == _wcsnicmp( pwcsName + ccSizeVar + ccStringizedGuid, wcsPropid, ccPropid ) )
{
CQueryScanner scan( pwcsName + ccSizeVar + ccStringizedGuid + ccPropid, FALSE );
PROPID propid;
BOOL fEnd;
if ( !scan.GetNumber( propid, fEnd ) )
{
ciGibDebugOut(( DEB_WARN, "Improperly formatted CACHESIZE entry %ws\n", pwcsName ));
iter.Next();
continue;
}
ps.SetProperty( propid );
}
else if ( 0 == _wcsnicmp( pwcsName + ccSizeVar + ccStringizedGuid, wcsName, ccName ) )
{
ps.SetProperty( pwcsName + ccSizeVar + ccStringizedGuid + ccName );
}
else
{
ciGibDebugOut(( DEB_WARN, "Improperly formatted CACHESIZE entry %ws\n", pwcsName ));
iter.Next();
continue;
}
//
// Get value.
//
PROPVARIANT * ppvSize = pVar->GetValue();
ULONG cb;
if ( ppvSize->vt == VT_LPWSTR )
{
CQueryScanner scan( ppvSize->pwszVal, FALSE );
BOOL fEnd;
if ( !scan.GetNumber( cb, fEnd ) )
{
ciGibDebugOut(( DEB_WARN, "Improper CACHESIZE size: \"%ws\".\n", ppvSize->pwszVal ));
iter.Next();
continue;
}
}
else
{
ciGibDebugOut(( DEB_IWARN, "Improper CACHESIZE size (type = %d).\n", ppvSize->vt ));
iter.Next();
continue;
}
if ( 0 == cb )
{
//
// Delete property from cache (if it was even there).
//
//
// If IDA were the future...
// Need to allow primary or secondary store to be chosen!
// Also allow the ability to set true/false for prop meta info
// modifiability.
//
SCODE sc = SetupCacheEx( ps.CastToStruct(),
0,
0,
ulToken,
TRUE,
PRIMARY_STORE,
wcsCatalog.GetPointer(),
wcsCatalog.GetPointer(),
wcsMachine.GetPointer() );
if ( FAILED(sc) )
{
ciGibDebugOut(( DEB_ERROR, "Error 0x%x modifying cache\n", sc ));
THROW( CException( sc ) );
}
fSawOne = TRUE;
iter.Next();
continue;
}
//
// At this point, we have a non-zero size. The property will
// be added to the cache.
//
//
// Fetch data type
//
XArray<WCHAR> xVar(cc+1);
RtlCopyMemory( xVar.GetPointer(), pwcsName, (cc+1) * sizeof(WCHAR) );
RtlCopyMemory( xVar.GetPointer(), wcsTypeVar, ccTypeVar * sizeof(WCHAR) );
CVariable * pVarType = VarSet.Find( xVar.GetPointer() );
if ( 0 == pVarType )
{
ciGibDebugOut(( DEB_WARN, "Missing CACHETYPE value.\n" ));
iter.Next();
continue;
}
PROPVARIANT * ppvType = pVarType->GetValue();
ULONG type;
if ( ppvType->vt == VT_LPWSTR )
{
CQueryScanner scan( ppvType->pwszVal, FALSE );
BOOL fEnd;
if ( !scan.GetNumber( type, fEnd ) )
{
ciGibDebugOut(( DEB_WARN, "Improper CACHETYPE type: \"%ws\".\n", ppvType->pwszVal ));
iter.Next();
continue;
}
}
else
{
ciGibDebugOut(( DEB_WARN, "Improper CACHETYPE size (type = %d).\n", ppvType->vt ));
iter.Next();
continue;
}
ciGibDebugOut(( DEB_WARN, "Add/change %ws\n", pwcsName ));
//
// If IDA were the future...
// Need to allow primary or secondary store to be chosen!
// Also allow the ability to set true/false for prop meta info
// modifiability.
//
SCODE sc = SetupCacheEx( ps.CastToStruct(),
type,
cb,
ulToken,
TRUE,
SECONDARY_STORE,
wcsCatalog.GetPointer(),
wcsCatalog.GetPointer(),
wcsMachine.GetPointer() );
if ( FAILED(sc) )
{
ciGibDebugOut(( DEB_ERROR, "Error 0x%x modifying cache\n", sc ));
THROW( CException( sc ) );
}
fSawOne = TRUE;
}
iter.Next();
}
sc = EndCacheTransaction( ulToken,
fSawOne,
wcsCatalog.GetPointer(),
wcsCatalog.GetPointer(),
wcsMachine.GetPointer() );
if ( FAILED(sc) )
{
ciGibDebugOut(( DEB_ERROR, "Error 0x%x completing cache transaction.\n", sc ));
THROW( CException( sc ) );
}
break;
}
case CIDAFile::CiState:
{
//
// Populate the variable set.
//
CStorageVariant var;
var.SetUI4( TheWebQueryCache.Hits() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_HITS, var, 0 );
var.SetUI4( TheWebQueryCache.Misses() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_MISSES, var, 0 );
var.SetUI4( TheWebQueryCache.Running() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_ACTIVE, var, 0 );
var.SetUI4( TheWebQueryCache.Cached() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_COUNT, var, 0 );
var.SetUI4( TheWebPendingRequestQueue.Count() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_PENDING, var, 0 );
var.SetUI4( TheWebQueryCache.Rejected() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_REJECTED, var, 0 );
var.SetUI4( TheWebQueryCache.Total() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_TOTAL, var, 0 );
var.SetUI4( TheWebQueryCache.QPM() );
VarSet.SetVariable( ISAPI_CI_ADMIN_CACHE_QPM, var, 0 );
//
// Fetch CI state.
//
CI_STATE sState;
sState.cbStruct = sizeof(sState);
SCODE sc = CIState ( wcsCatalog.GetPointer(),
wcsMachine.GetPointer(),
&sState );
if ( FAILED(sc) )
{
ciGibDebugOut(( DEB_ERROR, "Error 0x%x getting CI state.\n", sc ));
THROW( CException( sc ) );
}
var.SetUI4( sState.cWordList );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_WORDLISTS, var, 0 );
var.SetUI4( sState.cPersistentIndex );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_PERSINDEX, var, 0 );
var.SetUI4( sState.cQueries );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_QUERIES, var, 0 );
var.SetUI4( sState.cDocuments );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_TOFILTER, var, 0 );
var.SetUI4( sState.cFreshTest );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_FRESHTEST, var, 0 );
var.SetUI4( sState.dwMergeProgress );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_MERGE_PROGRESS, var, 0 );
var.SetUI4( sState.cPendingScans );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_PENDINGSCANS, var, 0 );
var.SetUI4( sState.cFilteredDocuments );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_FILTERED, var, 0 );
var.SetUI4( sState.cTotalDocuments );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_TOTAL, var, 0 );
var.SetUI4( sState.cUniqueKeys );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_COUNT_UNIQUE, var, 0 );
var.SetUI4( sState.dwIndexSize );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_SIZE, var, 0 );
if ( sState.eState & CI_STATE_SHADOW_MERGE )
var.SetBOOL( VARIANT_TRUE );
else
var.SetBOOL( VARIANT_FALSE );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_STATE_SHADOWMERGE, var, 0 );
if ( sState.eState & CI_STATE_MASTER_MERGE )
var.SetBOOL( VARIANT_TRUE );
else
var.SetBOOL( VARIANT_FALSE );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_STATE_MASTERMERGE, var, 0 );
if ( sState.eState & CI_STATE_ANNEALING_MERGE )
var.SetBOOL( VARIANT_TRUE );
else
var.SetBOOL( VARIANT_FALSE );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_STATE_ANNEALINGMERGE, var, 0 );
if ( sState.eState & CI_STATE_CONTENT_SCAN_REQUIRED )
var.SetBOOL( VARIANT_TRUE );
else
var.SetBOOL( VARIANT_FALSE );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_STATE_SCANREQUIRED, var, 0 );
if ( sState.eState & CI_STATE_SCANNING )
var.SetBOOL( VARIANT_TRUE );
else
var.SetBOOL( VARIANT_FALSE );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_STATE_SCANNING, var, 0 );
if ( sState.eState & CI_STATE_RECOVERING )
var.SetBOOL( VARIANT_TRUE );
else
var.SetBOOL( VARIANT_FALSE );
VarSet.SetVariable( ISAPI_CI_ADMIN_INDEX_STATE_RECOVERING, var, 0 );
//
// Now that we've got the variables, we can parse the file.
//
SuccessHTX.ParseFile( wcsPhysicalName, VarSet, OutputFormat );
if ( SuccessHTX.DoesDetailSectionExist() )
{
THROW( CIDQException(MSG_CI_IDA_TEMPLATE_DETAIL_SECTION, 0) );
}
break;
}
case CIDAFile::ForceMerge:
{
SuccessHTX.ParseFile( wcsPhysicalName, VarSet, OutputFormat );
if ( SuccessHTX.DoesDetailSectionExist() )
{
THROW( CIDQException(MSG_CI_IDA_TEMPLATE_DETAIL_SECTION, 0) );
}
SCODE sc = ForceMasterMerge( wcsCatalog.GetPointer(), // Drive
wcsCatalog.GetPointer(), // Catalog
wcsMachine.GetPointer(), // Machine
1 ); // Partition
if ( FAILED(sc) )
{
ciGibDebugOut(( DEB_ERROR, "Error 0x%x calling ForceMerge for %ws\n",
sc, wcsCatalog.GetPointer() ));
THROW( CException( sc ) );
}
break;
}
}
//
// Set CiQueryTime
//
ULONG cwcQueryTime = 40;
SYSTEMTIME QueryTime;
GetLocalTime( &QueryTime );
XArray<WCHAR> wcsQueryTime(cwcQueryTime+1);
cwcQueryTime = OutputFormat.FormatTime( QueryTime,
wcsQueryTime.GetPointer(),
cwcQueryTime );
//
// SetCiQueryDate
//
ULONG cwcQueryDate = 40;
XArray<WCHAR> wcsQueryDate(cwcQueryDate+1);
cwcQueryDate = OutputFormat.FormatDate( QueryTime,
wcsQueryDate.GetPointer(),
cwcQueryDate );
VarSet.AcquireStringValue( ISAPI_CI_QUERY_TIME, wcsQueryTime.GetPointer(), 0 );
wcsQueryTime.Acquire();
VarSet.AcquireStringValue( ISAPI_CI_QUERY_DATE, wcsQueryDate.GetPointer(), 0 );
wcsQueryDate.Acquire();
//
// Set CiQueryTimeZone
//
TIME_ZONE_INFORMATION TimeZoneInformation;
DWORD dwResult = GetTimeZoneInformation( &TimeZoneInformation );
LPWSTR pwszTimeZoneName = 0;
if ( TIME_ZONE_ID_DAYLIGHT == dwResult )
{
pwszTimeZoneName = TimeZoneInformation.DaylightName;
}
else if ( 0xFFFFFFFF == dwResult )
{
# if CIDBG == 1
DWORD dwError = GetLastError();
ciGibDebugOut(( DEB_ERROR, "Error %d from GetTimeZoneInformation.\n", dwError ));
THROW(CException( HRESULT_FROM_WIN32(dwError) ));
# else
THROW( CException() );
# endif
}
else
{
pwszTimeZoneName = TimeZoneInformation.StandardName;
}
VarSet.CopyStringValue( ISAPI_CI_QUERY_TIMEZONE, pwszTimeZoneName, 0);
//
// Set CiCatalog, CiLocale and CiTemplate
//
VarSet.AcquireStringValue( ISAPI_CI_CATALOG, wcsCiCatalog.GetPointer(), 0 );
wcsCiCatalog.Acquire();
VarSet.AcquireStringValue( ISAPI_CI_LOCALE, wcsLocale.GetPointer(), 0 );
wcsLocale.Acquire();
VarSet.CopyStringValue( ISAPI_CI_TEMPLATE, SuccessHTX.GetVirtualName(), 0 );
//
// If we got here, then all changes succeeded and we build success page.
//
SuccessHTX.GetHeader( vsResults, VarSet, OutputFormat );
SuccessHTX.GetFooter( vsResults, VarSet, OutputFormat );
}
BOOL ParseGuid( WCHAR const * pwcsGuid, GUID & guid )
{
unsigned cc = wcslen( pwcsGuid );
if ( cc < ccStringizedGuid ||
L'-' != pwcsGuid[8] ||
L'-' != pwcsGuid[13] ||
L'-' != pwcsGuid[18] ||
L'-' != pwcsGuid[23] )
{
ciGibDebugOut(( DEB_WARN, "Improperly formatted guid %ws\n", pwcsGuid ));
return FALSE;
}
//
// Copy into local, editable, storage
//
WCHAR wcsGuid[ccStringizedGuid + 1];
RtlCopyMemory( wcsGuid, pwcsGuid, (ccStringizedGuid + 1) * sizeof(WCHAR) );
wcsGuid[ccStringizedGuid] = 0;
wcsGuid[8] = 0;
WCHAR * pwcStart = &wcsGuid[0];
WCHAR * pwcEnd;
guid.Data1 = wcstoul( pwcStart, &pwcEnd, 16 );
if ( (pwcEnd-pwcStart) != 8 ) // The 1st number MUST be 8 digits long
return FALSE;
wcsGuid[13] = 0;
pwcStart = &wcsGuid[9];
guid.Data2 = (USHORT)wcstoul( pwcStart, &pwcEnd, 16 );
if ( (pwcEnd-pwcStart) != 4 ) // The 2nd number MUST be 4 digits long
return FALSE;
wcsGuid[18] = 0;
pwcStart = &wcsGuid[14];
guid.Data3 = (USHORT)wcstoul( pwcStart, &pwcEnd, 16 );
if ( (pwcEnd-pwcStart) != 4 ) // The 3rd number MUST be 4 digits long
return FALSE;
WCHAR wc = wcsGuid[21];
wcsGuid[21] = 0;
pwcStart = &wcsGuid[19];
guid.Data4[0] = (unsigned char)wcstoul( pwcStart, &pwcEnd, 16 );
if ( (pwcEnd-pwcStart) != 2 ) // The 4th number MUST be 4 digits long
return FALSE;
wcsGuid[21] = wc;
wcsGuid[23] = 0;
pwcStart = &wcsGuid[21];
guid.Data4[1] = (unsigned char)wcstoul( pwcStart, &pwcEnd, 16 );
if ( (pwcEnd-pwcStart) != 2 ) // The 4th number MUST be 4 digits long
return FALSE;
for ( unsigned i = 0; i < 6; i++ )
{
wc = wcsGuid[26+i*2];
wcsGuid[26+i*2] = 0;
pwcStart = &wcsGuid[24+i*2];
guid.Data4[2+i] = (unsigned char)wcstoul( pwcStart, &pwcEnd, 16 );
if ( pwcStart == pwcEnd )
return FALSE;
wcsGuid[26+i*2] = wc;
}
return TRUE;
}
//+---------------------------------------------------------------------------
//
// Function: CheckAdminSecurity, public
//
// Synopsis: Checks to see if the client has administrative access.
//
// Arguments: [pwszMachine] - machine name
//
// Returns: Nothing, throws if access is denied.
//
// Notes: The ACL on the HKEY_CURRENT_MACHINE\system\CurrentControlSet\
// Control\ContentIndex registry key is used to determine if
// access is permitted.
//
// The access check is only done when the administrative operation
// is local. Otherwise, it will be checked in the course of doing
// the administrative operation.
//
// History: 26 Jun 96 AlanW Created.
//
//----------------------------------------------------------------------------
void CheckAdminSecurity( WCHAR const * pwszMachine )
{
HKEY hNewKey = (HKEY) INVALID_HANDLE_VALUE;
if ( 0 != wcscmp( pwszMachine, CATURL_LOCAL_MACHINE ) )
return;
LONG dwError = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
wcsRegAdminSubKey,
0,
KEY_WRITE,
&hNewKey );
if ( ERROR_SUCCESS == dwError )
{
RegCloseKey( hNewKey );
}
else if ( ERROR_ACCESS_DENIED == dwError )
{
THROW(CException( STATUS_ACCESS_DENIED ) );
}
else
{
ciGibDebugOut(( DEB_ERROR,
"Can not open reg key %ws, error %d\n",
wcsRegAdminSubKey, dwError ));
THROW(CException( HRESULT_FROM_WIN32( dwError ) ) );
}
}
| 31.891913 | 110 | 0.481896 | npocmaka |
1c53515e3246478705be1230553cd8c4a047ce17 | 11,666 | cc | C++ | NS3-master/src/traffic-control/test/cobalt-queue-disc-test-suite.cc | legendPerceptor/blockchain | 615ba331ae5ec53c683dfe6a16992a5181be0fea | [
"Apache-2.0"
] | 1 | 2021-09-20T07:05:25.000Z | 2021-09-20T07:05:25.000Z | NS3-master/src/traffic-control/test/cobalt-queue-disc-test-suite.cc | legendPerceptor/blockchain | 615ba331ae5ec53c683dfe6a16992a5181be0fea | [
"Apache-2.0"
] | null | null | null | NS3-master/src/traffic-control/test/cobalt-queue-disc-test-suite.cc | legendPerceptor/blockchain | 615ba331ae5ec53c683dfe6a16992a5181be0fea | [
"Apache-2.0"
] | 2 | 2021-09-02T08:25:16.000Z | 2022-01-03T08:48:38.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2019 NITK Surathkal
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Ported to ns-3 by: Vignesh Kannan <vignesh2496@gmail.com>
* Harsh Lara <harshapplefan@gmail.com>
* Jendaipou Palmei <jendaipoupalmei@gmail.com>
* Shefali Gupta <shefaligups11@gmail.com>
* Mohit P. Tahiliani <tahiliani@nitk.edu.in>
*/
#include "ns3/test.h"
#include "ns3/cobalt-queue-disc.h"
#include "ns3/packet.h"
#include "ns3/uinteger.h"
#include "ns3/string.h"
#include "ns3/double.h"
#include "ns3/log.h"
#include "ns3/simulator.h"
using namespace ns3;
/**
* \ingroup traffic-control-test
* \ingroup tests
*
* \brief Cobalt Queue Disc Test Item
*/
class CobaltQueueDiscTestItem : public QueueDiscItem
{
public:
/**
* Constructor
*
* \param p packet
* \param addr address
* \param protocol
*/
CobaltQueueDiscTestItem (Ptr<Packet> p, const Address & addr,uint16_t protocol, bool ecnCapable);
virtual ~CobaltQueueDiscTestItem ();
virtual void AddHeader (void);
virtual bool Mark (void);
private:
CobaltQueueDiscTestItem ();
/**
* \brief Copy constructor
* Disable default implementation to avoid misuse
*/
CobaltQueueDiscTestItem (const CobaltQueueDiscTestItem &);
/**
* \brief Assignment operator
* \return this object
* Disable default implementation to avoid misuse
*/
CobaltQueueDiscTestItem &operator = (const CobaltQueueDiscTestItem &);
bool m_ecnCapablePacket; ///< ECN capable packet?
};
CobaltQueueDiscTestItem::CobaltQueueDiscTestItem (Ptr<Packet> p, const Address & addr,uint16_t protocol, bool ecnCapable)
: QueueDiscItem (p, addr, ecnCapable),
m_ecnCapablePacket (ecnCapable)
{
}
CobaltQueueDiscTestItem::~CobaltQueueDiscTestItem ()
{
}
void
CobaltQueueDiscTestItem::AddHeader (void)
{
}
bool
CobaltQueueDiscTestItem::Mark (void)
{
if (m_ecnCapablePacket)
{
return true;
}
return false;
}
/**
* \ingroup traffic-control-test
* \ingroup tests
*
* \brief Test 1: simple enqueue/dequeue with no drops
*/
class CobaltQueueDiscBasicEnqueueDequeue : public TestCase
{
public:
/**
* Constructor
*
* \param mode the mode
*/
CobaltQueueDiscBasicEnqueueDequeue (QueueSizeUnit mode);
virtual void DoRun (void);
/**
* Queue test size function
* \param queue the queue disc
* \param size the size
* \param error the error string
*
*/
private:
QueueSizeUnit m_mode; ///< mode
};
CobaltQueueDiscBasicEnqueueDequeue::CobaltQueueDiscBasicEnqueueDequeue (QueueSizeUnit mode)
: TestCase ("Basic enqueue and dequeue operations, and attribute setting" + std::to_string (mode))
{
m_mode = mode;
}
void
CobaltQueueDiscBasicEnqueueDequeue::DoRun (void)
{
Ptr<CobaltQueueDisc> queue = CreateObject<CobaltQueueDisc> ();
uint32_t pktSize = 1000;
uint32_t modeSize = 0;
Address dest;
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MinBytes", UintegerValue (pktSize)), true,
"Verify that we can actually set the attribute MinBytes");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Interval", StringValue ("50ms")), true,
"Verify that we can actually set the attribute Interval");
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Target", StringValue ("4ms")), true,
"Verify that we can actually set the attribute Target");
if (m_mode == QueueSizeUnit::BYTES)
{
modeSize = pktSize;
}
else if (m_mode == QueueSizeUnit::PACKETS)
{
modeSize = 1;
}
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxSize", QueueSizeValue (QueueSize (m_mode, modeSize * 1500))),
true, "Verify that we can actually set the attribute MaxSize");
queue->Initialize ();
Ptr<Packet> p1, p2, p3, p4, p5, p6;
p1 = Create<Packet> (pktSize);
p2 = Create<Packet> (pktSize);
p3 = Create<Packet> (pktSize);
p4 = Create<Packet> (pktSize);
p5 = Create<Packet> (pktSize);
p6 = Create<Packet> (pktSize);
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 0 * modeSize, "There should be no packets in queue");
queue->Enqueue (Create<CobaltQueueDiscTestItem> (p1, dest,0, false));
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 1 * modeSize, "There should be one packet in queue");
queue->Enqueue (Create<CobaltQueueDiscTestItem> (p2, dest,0, false));
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 2 * modeSize, "There should be two packets in queue");
queue->Enqueue (Create<CobaltQueueDiscTestItem> (p3, dest,0, false));
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 3 * modeSize, "There should be three packets in queue");
queue->Enqueue (Create<CobaltQueueDiscTestItem> (p4, dest,0, false));
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 4 * modeSize, "There should be four packets in queue");
queue->Enqueue (Create<CobaltQueueDiscTestItem> (p5, dest,0, false));
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 5 * modeSize, "There should be five packets in queue");
queue->Enqueue (Create<CobaltQueueDiscTestItem> (p6, dest,0, false));
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 6 * modeSize, "There should be six packets in queue");
NS_TEST_EXPECT_MSG_EQ (queue->GetStats ().GetNDroppedPackets (CobaltQueueDisc::OVERLIMIT_DROP), 0, "There should be no packets being dropped due to full queue");
Ptr<QueueDiscItem> item;
item = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the first packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 5 * modeSize, "There should be five packets in queue");
NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p1->GetUid (), "was this the first packet ?");
item = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the second packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 4 * modeSize, "There should be four packets in queue");
NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p2->GetUid (), "Was this the second packet ?");
item = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the third packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 3 * modeSize, "There should be three packets in queue");
NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p3->GetUid (), "Was this the third packet ?");
item = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the forth packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 2 * modeSize, "There should be two packets in queue");
NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p4->GetUid (), "Was this the fourth packet ?");
item = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the fifth packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 1 * modeSize, "There should be one packet in queue");
NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p5->GetUid (), "Was this the fifth packet ?");
item = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the last packet");
NS_TEST_EXPECT_MSG_EQ (queue->GetCurrentSize ().GetValue (), 0 * modeSize, "There should be zero packet in queue");
NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p6->GetUid (), "Was this the sixth packet ?");
item = queue->Dequeue ();
NS_TEST_EXPECT_MSG_EQ ((item == 0), true, "There are really no packets in queue");
NS_TEST_EXPECT_MSG_EQ (queue->GetStats ().GetNDroppedPackets (CobaltQueueDisc::TARGET_EXCEEDED_DROP), 0, "There should be no packet drops according to Cobalt algorithm");
}
/**
* \ingroup traffic-control-test
* \ingroup tests
*
* \brief Test 2: Cobalt Queue Disc Drop Test Item
*/
class CobaltQueueDiscDropTest : public TestCase
{
public:
CobaltQueueDiscDropTest ();
virtual void DoRun (void);
/**
* Enqueue function
* \param queue the queue disc
* \param size the size
* \param nPkt the number of packets
*/
void Enqueue (Ptr<CobaltQueueDisc> queue, uint32_t size, uint32_t nPkt);
/**
* Run Cobalt test function
* \param mode the mode
*/
void RunDropTest (QueueSizeUnit mode);
void EnqueueWithDelay (Ptr<CobaltQueueDisc> queue, uint32_t size, uint32_t nPkt);
};
CobaltQueueDiscDropTest::CobaltQueueDiscDropTest ()
: TestCase ("Drop tests verification for both packets and bytes mode")
{
}
void
CobaltQueueDiscDropTest::RunDropTest (QueueSizeUnit mode)
{
uint32_t pktSize = 1500;
uint32_t modeSize = 0;
Ptr<CobaltQueueDisc> queue = CreateObject<CobaltQueueDisc> ();
if (mode == QueueSizeUnit::BYTES)
{
modeSize = pktSize;
}
else if (mode == QueueSizeUnit::PACKETS)
{
modeSize = 1;
}
queue = CreateObject<CobaltQueueDisc> ();
NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxSize", QueueSizeValue (QueueSize (mode, modeSize * 100))),
true, "Verify that we can actually set the attribute MaxSize");
queue->Initialize ();
if (mode == QueueSizeUnit::BYTES)
{
EnqueueWithDelay (queue, pktSize, 200);
}
else
{
EnqueueWithDelay (queue, 1, 200);
}
Simulator::Stop (Seconds (8.0));
Simulator::Run ();
QueueDisc::Stats st = queue->GetStats ();
// The Pdrop value should increase, from it's default value of zero
NS_TEST_EXPECT_MSG_NE (queue->GetPdrop (), 0, "Pdrop should be non-zero");
NS_TEST_EXPECT_MSG_NE (st.GetNDroppedPackets (CobaltQueueDisc::OVERLIMIT_DROP), 0, "Drops due to queue overflow should be non-zero");
}
void
CobaltQueueDiscDropTest::EnqueueWithDelay (Ptr<CobaltQueueDisc> queue, uint32_t size, uint32_t nPkt)
{
Address dest;
double delay = 0.01; // enqueue packets with delay
for (uint32_t i = 0; i < nPkt; i++)
{
Simulator::Schedule (Time (Seconds ((i + 1) * delay)), &CobaltQueueDiscDropTest::Enqueue, this, queue, size, 1);
}
}
void
CobaltQueueDiscDropTest::Enqueue (Ptr<CobaltQueueDisc> queue, uint32_t size, uint32_t nPkt)
{
Address dest;
for (uint32_t i = 0; i < nPkt; i++)
{
queue->Enqueue (Create<CobaltQueueDiscTestItem> (Create<Packet> (size), dest, 0, true));
}
}
void
CobaltQueueDiscDropTest::DoRun (void)
{
RunDropTest (QueueSizeUnit::PACKETS);
RunDropTest (QueueSizeUnit::BYTES);
Simulator::Destroy ();
}
static class CobaltQueueDiscTestSuite : public TestSuite
{
public:
CobaltQueueDiscTestSuite ()
: TestSuite ("cobalt-queue-disc", UNIT)
{
// Test 1: simple enqueue/dequeue with no drops
AddTestCase (new CobaltQueueDiscBasicEnqueueDequeue (PACKETS), TestCase::QUICK);
AddTestCase (new CobaltQueueDiscBasicEnqueueDequeue (BYTES), TestCase::QUICK);
// Test 2: Drop test
AddTestCase (new CobaltQueueDiscDropTest (), TestCase::QUICK);
}
} g_cobaltQueueTestSuite; ///< the test suite
| 34.211144 | 172 | 0.698097 | legendPerceptor |
1c5896613fd7ca847a9e50fb748a1504eea02048 | 4,459 | cpp | C++ | test/plugins/where.cpp | tkerola/chainer-trt | 4e1adc0370e11ad7736a5fafdfd5aeca168c700e | [
"MIT"
] | null | null | null | test/plugins/where.cpp | tkerola/chainer-trt | 4e1adc0370e11ad7736a5fafdfd5aeca168c700e | [
"MIT"
] | null | null | null | test/plugins/where.cpp | tkerola/chainer-trt | 4e1adc0370e11ad7736a5fafdfd5aeca168c700e | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 Preferred Networks, Inc. All rights reserved.
*/
#include <fstream>
#include <cuda_runtime_api.h>
#include "chainer_trt/chainer_trt.hpp"
#include "include/chainer_trt_impl.hpp"
#include "include/cuda/cuda_kernels.hpp"
#include "test_helper.hpp"
// TODO: Merge to run_plugin_assert_core (need to let it accept multiple inputs)
template <typename FloatType, typename PluginType>
void run_plugin_assert_core_n(PluginType& plugin_src, int n, int batch_size,
const nvinfer1::Dims& in_dims,
const std::string& dir, float allowed_err = 0) {
cudaSetDevice(0);
std::vector<FloatType> in_cpu[n];
for(int i = 0; i < n; i++)
in_cpu[i] = repeat_array(
load_values<FloatType>(dir + "/in" + std::to_string(i + 1) + ".csv"),
batch_size);
const std::vector<FloatType> expected_out_cpu =
repeat_array(load_values<FloatType>(dir + "/out.csv"), batch_size);
const int n_in = chainer_trt::internal::calc_n_elements(in_dims);
// Make a plugin (and serialize, deserialize)
std::unique_ptr<unsigned char[]> buf(
new unsigned char[plugin_src.getSerializationSize()]);
plugin_src.serialize(buf.get());
PluginType plugin(buf.get(), plugin_src.getSerializationSize());
plugin.initialize();
const nvinfer1::Dims out_dims = plugin.getOutputDimensions(0, &in_dims, 1);
const int n_out = chainer_trt::internal::calc_n_elements(out_dims);
for(int i = 0; i < n; i++)
ASSERT_EQ(in_cpu[i].size(), n_in * batch_size);
ASSERT_EQ(expected_out_cpu.size(), n_out * batch_size);
// Prepare data
FloatType *in_gpu[n], *out_gpu;
for(int i = 0; i < n; i++) {
cudaMalloc((void**)&in_gpu[i], sizeof(FloatType) * in_cpu[i].size());
cudaMemcpy(in_gpu[i], in_cpu[i].data(),
sizeof(FloatType) * in_cpu[i].size(),
cudaMemcpyHostToDevice);
}
cudaMalloc((void**)&out_gpu, sizeof(FloatType) * expected_out_cpu.size());
// Run inference
void **ins_gpu = (void**)in_gpu, *outs_gpu[] = {out_gpu};
plugin.enqueue(batch_size, ins_gpu, outs_gpu, NULL, 0);
// Get result and assert
std::vector<FloatType> out_cpu(expected_out_cpu.size());
cudaMemcpy(out_cpu.data(), out_gpu, sizeof(FloatType) * out_cpu.size(),
cudaMemcpyDeviceToHost);
if(allowed_err < 1e-3)
assert_vector_eq(out_cpu, expected_out_cpu);
else
assert_vector_near(out_cpu, expected_out_cpu, allowed_err);
for(int i = 0; i < n; i++)
cudaFree(in_gpu[i]);
cudaFree(out_gpu);
}
template <typename PluginType>
void run_plugin_assert_n(PluginType& plugin_src, int n, int batch_size,
nvinfer1::DataType data_type,
const nvinfer1::Dims& in_dims, const std::string& dir,
float allowed_err = 0) {
const auto out_dim = plugin_src.getOutputDimensions(0, &in_dims, 1);
plugin_src.configureWithFormat(&in_dims, 1, &out_dim, 1, data_type,
nvinfer1::PluginFormat::kNCHW, batch_size);
if(data_type == nvinfer1::DataType::kFLOAT)
run_plugin_assert_core_n<float>(plugin_src, n, batch_size, in_dims, dir,
allowed_err);
else if(data_type == nvinfer1::DataType::kHALF)
run_plugin_assert_core_n<__half>(plugin_src, n, batch_size, in_dims,
dir, allowed_err);
}
using TestParams = std::tuple<int, nvinfer1::DataType>;
class WhereKernelParameterizedTest
: public ::testing::TestWithParam<TestParams> {};
TEST_P(WhereKernelParameterizedTest, CheckValues) {
auto param = GetParam();
const int batch_size = std::get<0>(param);
const nvinfer1::DataType data_type = std::get<1>(param);
const nvinfer1::Dims dims = chainer_trt::internal::make_dims(2, 3, 4);
const std::string dir = "test/fixtures/plugins/where";
chainer_trt::plugin::where where_src(dims);
run_plugin_assert_n(where_src, 3, batch_size, data_type, dims, dir, 0.001);
}
INSTANTIATE_TEST_CASE_P(
CheckOutputValue, WhereKernelParameterizedTest,
::testing::Values(TestParams(1, nvinfer1::DataType::kFLOAT),
TestParams(1, nvinfer1::DataType::kHALF),
TestParams(65535, nvinfer1::DataType::kFLOAT),
TestParams(65535, nvinfer1::DataType::kHALF)));
| 38.773913 | 80 | 0.647006 | tkerola |
1c62982fa529dc9f0dd8cee2272f4cded59f225d | 1,795 | cpp | C++ | leetcode/_236_lowest_common_ancestor_of_a_binary_tree_2.cpp | WindyDarian/OJ_Submissions | a323595c3a32ed2e07af65374ef90c81d5333f96 | [
"Apache-2.0"
] | 3 | 2017-02-19T14:38:32.000Z | 2017-07-22T17:06:55.000Z | leetcode/_236_lowest_common_ancestor_of_a_binary_tree_2.cpp | WindyDarian/OJ_Submissions | a323595c3a32ed2e07af65374ef90c81d5333f96 | [
"Apache-2.0"
] | null | null | null | leetcode/_236_lowest_common_ancestor_of_a_binary_tree_2.cpp | WindyDarian/OJ_Submissions | a323595c3a32ed2e07af65374ef90c81d5333f96 | [
"Apache-2.0"
] | null | null | null | //==============================================================================
// Copyright 2016 Windy Darian (Ruoyu Fan)
//
// 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.
//==============================================================================
//
// Created on Nov 28, 2016
// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* findOneOrLca(TreeNode* root, TreeNode* p, TreeNode* q)
{
if (!root) {return nullptr;}
if (root == p || root == q)
{
return root;
}
auto lfound = findOneOrLca(root->left, p, q);
auto rfound = findOneOrLca(root->right, p, q);
if (lfound && rfound)
{
return root;
}
if (!lfound && rfound)
{
return rfound;
}
else if (lfound && !rfound)
{
return lfound;
}
return nullptr;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
return findOneOrLca(root, p, q);
}
};
| 28.046875 | 80 | 0.545404 | WindyDarian |
1c642e5240299f7957100128a66766d7a36ff332 | 639 | cc | C++ | src/ui/views/win/hwnd_util_win.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | src/ui/views/win/hwnd_util_win.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | null | null | null | src/ui/views/win/hwnd_util_win.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/win/hwnd_util.h"
#include "ui/views/widget/widget.h"
namespace views {
HWND HWNDForView(View* view) {
return view->GetWidget() ? HWNDForWidget(view->GetWidget()) : NULL;
}
// Returns the HWND associated with the specified widget.
HWND HWNDForWidget(Widget* widget) {
return widget->GetNativeView();
}
HWND HWNDForNativeView(gfx::NativeView view) {
return view;
}
HWND HWNDForNativeWindow(gfx::NativeWindow window) {
return window;
}
}
| 22.034483 | 73 | 0.735524 | jxjnjjn |
1c69f258ce1678b411fbd075d2a9e588dd6cd5e1 | 2,515 | cpp | C++ | uva/11743 - Credit Check.cpp | taufique71/sports-programming | c29a92b5e5424c7de6f94e302fc6783561de9b3d | [
"MIT"
] | null | null | null | uva/11743 - Credit Check.cpp | taufique71/sports-programming | c29a92b5e5424c7de6f94e302fc6783561de9b3d | [
"MIT"
] | null | null | null | uva/11743 - Credit Check.cpp | taufique71/sports-programming | c29a92b5e5424c7de6f94e302fc6783561de9b3d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
char credit_no[20];
int dbl[10];
int non_dbl[10];
int count = 0;
char gar[5];
int n_case;
int i,j,k;
cin >> n_case;
gets(gar);
while(n_case--)
{
gets(credit_no);
j = 0;
k = 0;
count = 0;
for(i = 0 ; credit_no[i] ; i++)
{
switch(i)
{
case 0:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 1:
non_dbl[k++] = (credit_no[i] - 48);
break;
case 2:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 3:
non_dbl[k++] = (credit_no[i] - 48);
break;
case 5:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 6:
non_dbl[k++] = (credit_no[i] - 48);
break;
case 7:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 8:
non_dbl[k++] = (credit_no[i] - 48);
break;
case 10:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 11:
non_dbl[k++] = (credit_no[i] - 48);
break;
case 12:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 13:
non_dbl[k++] = (credit_no[i] - 48);
break;
case 15:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 16:
non_dbl[k++] = (credit_no[i] - 48);
break;
case 17:
dbl[j++] = (credit_no[i] - 48) * 2;
break;
case 18:
non_dbl[k++] = (credit_no[i] - 48);
break;
}
}
for(i = 0 ; i < 8 ; i++)
{
count += non_dbl[i];
if(dbl[i] >= 10)
{
count += dbl[i] % 10;
count += dbl[i] / 10;
}
else count += dbl[i];
}
if((count % 10) == 0) cout << "Valid" << endl;
else cout << "Invalid" << endl;
}
return 0;
}
| 23.287037 | 55 | 0.300596 | taufique71 |
1c6acf7ce271c21eb9918c68cce3d24bd9d1333f | 3,130 | hpp | C++ | library/inc/argo/action/Callback.hpp | phforest/Argo | bd45b2bf53f88fbd9f6215dc6293bbb3614e37d8 | [
"MIT"
] | null | null | null | library/inc/argo/action/Callback.hpp | phforest/Argo | bd45b2bf53f88fbd9f6215dc6293bbb3614e37d8 | [
"MIT"
] | null | null | null | library/inc/argo/action/Callback.hpp | phforest/Argo | bd45b2bf53f88fbd9f6215dc6293bbb3614e37d8 | [
"MIT"
] | null | null | null | #ifndef HEADER_argo_action_Callback_hpp_INCLUDE_GUARD
#define HEADER_argo_action_Callback_hpp_INCLUDE_GUARD
#include "argo/Context.hpp"
#include "argo/action/IAction.hpp"
#include "argo/details/log.hpp"
#include "argo/details/mss.hpp"
#include "argo/details/optional.hpp"
#include "argo/traits/conversion.hpp"
#include "argo/utility.hpp"
#include <functional>
namespace argo { namespace action {
template<typename Type, typename ConversionTraits = traits::conversion<Type>>
class Callback: public IAction
{
public:
using callback_type = std::function<bool(const Type &)>;
using callback_with_context_type = std::function<bool(Context &, const Type &)>;
explicit Callback(const callback_type &callback): simple_(callback) {}
explicit Callback(const callback_with_context_type &callback): extended_(callback) {}
virtual Ptr clone() const override
{
if (!!simple_) return details::make_unique<Callback>(*simple_);
assert(!!extended_);
return details::make_unique<Callback>(*extended_);
}
virtual bool apply(Context &context, const std::string &value) override
{
MSS_BEGIN(bool);
//if (!!simple_) L("Invoking simple callback");
//else trace("Invoking extended callback");
//trace(C(value));
const auto res = convert<Type, ConversionTraits>(context, value);
MSS(!!res);
MSS(!!simple_ ? (*simple_)(*res) : (*extended_)(context, *res),
{
std::ostringstream os;
os << "Could not process '" << context.option() << "'";
context.error(os.str());
});
MSS_END();
}
private:
details::optional<callback_type> simple_;
details::optional<callback_with_context_type> extended_;
};
template<typename Type, typename ConversionTraits = traits::conversion<Type>>
Callback<Type, ConversionTraits> callback(typename Callback<Type, ConversionTraits>::callback_type &cb) { return Callback<Type, ConversionTraits>{cb}; }
inline Callback<std::string> callback(const std::function<bool(const std::string &)> &cb) { return Callback<std::string>{cb}; }
inline Callback<std::string> callback(const std::function<bool()> &cb)
{
auto wrapper = [cb](const std::string &){ return cb(); };
return Callback<std::string>{wrapper};
}
template<typename Type, typename ConversionTraits = traits::conversion<Type>>
Callback<Type, ConversionTraits> callback(typename Callback<Type, ConversionTraits>::callback_type_with_context &cb) { return Callback<Type, ConversionTraits>{cb}; }
inline Callback<std::string> callback(const std::function<bool(Context &, const std::string &)> &cb) { return Callback<std::string>{cb}; }
inline Callback<std::string> callback(const std::function<bool(Context &)> &cb)
{
auto wrapper = [cb](Context &context, const std::string &) { return cb(context); };
return Callback<std::string>{wrapper};
}
} }
#endif
| 41.733333 | 169 | 0.650799 | phforest |
1c6b0464f5d4891666abda68087b97aec4fdcefa | 2,618 | cpp | C++ | src/hypro/representations/Box/intervalMethods.cpp | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 22 | 2016-10-05T12:19:01.000Z | 2022-01-23T09:14:41.000Z | src/hypro/representations/Box/intervalMethods.cpp | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 23 | 2017-05-08T15:02:39.000Z | 2021-11-03T16:43:39.000Z | src/hypro/representations/Box/intervalMethods.cpp | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 12 | 2017-06-07T23:51:09.000Z | 2022-01-04T13:06:21.000Z | #include "intervalMethods.h"
namespace hypro {
void reduceIntervalsNumberRepresentation( std::vector<carl::Interval<mpq_class>>& intervals, unsigned limit ) {
mpq_class limit2 = mpq_class( limit ) * mpq_class( limit );
for ( unsigned d = 0; d < intervals.size(); ++d ) {
//std::cout << "(Upper Bound) mpq_class: " << intervals[d].upper() << std::endl;
if ( intervals[d].upper() != 0 ) {
mpq_class numerator = carl::getNum( intervals[d].upper() );
mpq_class denominator = carl::getDenom( intervals[d].upper() );
mpq_class largest = carl::abs( numerator ) > carl::abs( denominator ) ? carl::abs( numerator ) : carl::abs( denominator );
if ( largest > limit2 ) {
mpq_class dividend = largest / mpq_class( limit );
assert( largest / dividend == limit );
mpq_class val = mpq_class( carl::ceil( numerator / dividend ) );
mpq_class newDenom;
if ( intervals[d].upper() > 0 ) {
newDenom = mpq_class( carl::floor( denominator / dividend ) );
} else {
newDenom = mpq_class( carl::ceil( denominator / dividend ) );
}
if ( newDenom != 0 ) {
val = val / newDenom;
assert( val >= intervals[d].upper() );
intervals[d].setUpper( mpq_class( val ) );
}
//std::cout << "Assert: " << val << " >= " << intervals[d].upper() << std::endl;
//std::cout << "(Upper bound) Rounding Error: " << carl::convert<mpq_class,double>(val - intervals[d].upper()) << std::endl;
}
}
//std::cout << "(Lower Bound) mpq_class: " << intervals[d].lower() << std::endl;
if ( intervals[d].lower() != 0 ) {
mpq_class numerator = carl::getNum( intervals[d].lower() );
mpq_class denominator = carl::getDenom( intervals[d].lower() );
mpq_class largest = carl::abs( numerator ) > carl::abs( denominator ) ? carl::abs( numerator ) : carl::abs( denominator );
if ( largest > limit2 ) {
mpq_class dividend = largest / mpq_class( limit );
assert( largest / dividend == limit );
mpq_class val = mpq_class( carl::floor( numerator / dividend ) );
mpq_class newDenom;
if ( intervals[d].lower() > 0 ) {
newDenom = mpq_class( carl::ceil( denominator / dividend ) );
} else {
newDenom = mpq_class( carl::floor( denominator / dividend ) );
}
if ( newDenom != 0 ) {
val = val / newDenom;
assert( val <= intervals[d].lower() );
intervals[d].setLower( val );
}
//std::cout << "Assert: " << val << " <= " << intervals[d].lower() << std::endl;
//std::cout << "(Lower bound) Rounding Error: " << carl::convert<mpq_class,double>(val - intervals[d].lower()) << std::endl;
}
}
}
}
} // namespace hypro
| 42.918033 | 128 | 0.606188 | hypro |
1c6b174fe3f09f24791256d816f186d05fa4c68e | 2,513 | cpp | C++ | phxqueue/config/utils/consumer_group_util.cpp | huayl/phxqueue | 733ada547a3b483b536cc3d401766af7b4c17dbe | [
"Apache-2.0"
] | 2,032 | 2017-09-12T02:29:42.000Z | 2022-03-23T07:14:56.000Z | phxqueue/config/utils/consumer_group_util.cpp | huayl/phxqueue | 733ada547a3b483b536cc3d401766af7b4c17dbe | [
"Apache-2.0"
] | 57 | 2017-09-12T03:36:39.000Z | 2020-12-16T08:59:09.000Z | phxqueue/config/utils/consumer_group_util.cpp | huayl/phxqueue | 733ada547a3b483b536cc3d401766af7b4c17dbe | [
"Apache-2.0"
] | 370 | 2017-09-12T03:09:04.000Z | 2022-03-13T14:01:55.000Z | #include <string>
#include "phxqueue/comm.h"
#include "phxqueue/config/globalconfig.h"
#include "phxqueue/config/storeconfig.h"
#include "phxqueue/config/topicconfig.h"
namespace phxqueue {
namespace config {
namespace utils {
using namespace std;
comm::RetCode GetConsumerGroupIDsByConsumerAddr(const int topic_id, const comm::proto::Addr &addr, std::set<int> &consumer_group_ids) {
consumer_group_ids.clear();
comm::RetCode ret;
shared_ptr<const config::ConsumerConfig> consumer_config;
if (comm::RetCode::RET_OK != (ret = config::GlobalConfig::GetThreadInstance()->GetConsumerConfig(topic_id, consumer_config))) {
NLErr("GetConsumerConfig ret %d", comm::as_integer(ret));
return ret;
}
shared_ptr<const config::proto::Consumer> consumer;
if (comm::RetCode::RET_OK != (ret = consumer_config->GetConsumerByAddr(addr, consumer))) {
NLErr("GetConsumerByAddr ret %d addr(%s:%d)", comm::as_integer(ret), addr.ip().c_str(), addr.port());
return ret;
}
shared_ptr<const config::TopicConfig> topic_config;
if (comm::RetCode::RET_OK != (ret = config::GlobalConfig::GetThreadInstance()->GetTopicConfigByTopicID(topic_id, topic_config))) {
NLErr("GetTopicConfigByTopicID ret %d", comm::as_integer(ret));
return ret;
}
set<int> ignore_consumer_group_ids;
for (int i{0}; i < topic_config->GetProto().topic().consumer_ignore_consumer_group_ids_size(); ++i) {
ignore_consumer_group_ids.insert(topic_config->GetProto().topic().consumer_ignore_consumer_group_ids(i));
}
if (consumer->consumer_group_ids_size()) {
for (int i{0}; i < consumer->consumer_group_ids_size(); ++i) {
auto consumer_group_id = consumer->consumer_group_ids(i);
if (topic_config->IsValidConsumerGroupID(consumer_group_id) && ignore_consumer_group_ids.end() == ignore_consumer_group_ids.find(consumer_group_id)) {
consumer_group_ids.insert(consumer_group_id);
}
}
return comm::RetCode::RET_OK;
}
if (comm::RetCode::RET_OK != (ret = topic_config->GetAllConsumerGroupID(consumer_group_ids))) {
NLErr("GetAllConsumerGroupID ret %d", comm::as_integer(ret));
return ret;
}
for (auto &&ignore_consumer_group_id : ignore_consumer_group_ids) {
consumer_group_ids.erase(ignore_consumer_group_id);
}
return comm::RetCode::RET_OK;
}
} // namespace utils
} // namespace config
} // namespace phxqueue
| 32.217949 | 162 | 0.691604 | huayl |
1c6cd514bbb1e87b74a40651a751a12f92307405 | 3,332 | hh | C++ | src/Xi-Crypto/include/Xi/Crypto/Hash/Sha2.hh | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/Xi-Crypto/include/Xi/Crypto/Hash/Sha2.hh | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/Xi-Crypto/include/Xi/Crypto/Hash/Sha2.hh | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | /* ============================================================================================== *
* *
* Galaxia Blockchain *
* *
* ---------------------------------------------------------------------------------------------- *
* This file is part of the Xi framework. *
* ---------------------------------------------------------------------------------------------- *
* *
* Copyright 2018-2019 Xi Project Developers <support.xiproject.io> *
* *
* This program is free software: you can redistribute it and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; *
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with this program. *
* If not, see <https://www.gnu.org/licenses/>. *
* *
* ============================================================================================== */
#pragma once
#include <Xi/Global.hh>
#include <Xi/Byte.hh>
#include "Xi/Crypto/Hash/Hash.hh"
#if defined(__cplusplus)
extern "C" {
#endif
#include <stdio.h>
int xi_crypto_hash_sha2_224(const xi_byte_t *data, size_t length, xi_crypto_hash_224 out);
int xi_crypto_hash_sha2_256(const xi_byte_t *data, size_t length, xi_crypto_hash_256 out);
int xi_crypto_hash_sha2_384(const xi_byte_t *data, size_t length, xi_crypto_hash_384 out);
int xi_crypto_hash_sha2_512(const xi_byte_t *data, size_t length, xi_crypto_hash_512 out);
#if defined(__cplusplus)
}
#endif
#if defined(__cplusplus)
namespace Xi {
namespace Crypto {
namespace Hash {
namespace Sha2 {
XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash224, 224)
XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash256, 256)
XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash384, 384)
XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash512, 512)
void compute(ConstByteSpan data, Hash224 &out);
void compute(ConstByteSpan data, Hash256 &out);
void compute(ConstByteSpan data, Hash384 &out);
void compute(ConstByteSpan data, Hash512 &out);
} // namespace Sha2
} // namespace Hash
} // namespace Crypto
} // namespace Xi
#endif
| 49.731343 | 100 | 0.444778 | ElSamaritan |
1c6decced6b95828faadcfa02c3abc1cb3df1155 | 2,854 | cpp | C++ | modules/SofaPreconditioner/JacobiPreconditioner.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaPreconditioner/JacobiPreconditioner.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/SofaPreconditioner/JacobiPreconditioner.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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 program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
// Author: Hadrien Courtecuisse
//
// Copyright: See COPYING file that comes with this distribution
#include <SofaPreconditioner/JacobiPreconditioner.inl>
#include <sofa/core/ObjectFactory.h>
namespace sofa
{
namespace component
{
namespace linearsolver
{
SOFA_DECL_CLASS(JacobiPreconditioner)
int JacobiPreconditionerClass = core::RegisterObject("Linear solver based on a diagonal matrix (i.e. Jacobi preconditioner)")
//.add< JacobiPreconditioner<GraphScatteredMatrix,GraphScatteredVector> >(true)
.add< JacobiPreconditioner<DiagonalMatrix<double>, FullVector<double> > >(true)
//.add< JacobiPreconditioner<SparseMatrix<double>, FullVector<double> > >()
// .add< JacobiPreconditioner<NewMatBandMatrix,NewMatVector> >()
// .add< JacobiPreconditioner<NewMatMatrix,NewMatVector> >()
// .add< JacobiPreconditioner<NewMatSymmetricMatrix,NewMatVector> >()
// .add< JacobiPreconditioner<NewMatSymmetricBandMatrix,NewMatVector> >()
//.add< JacobiPreconditioner<FullMatrix<double>, FullVector<double> > >()
.addAlias("JacobiLinearSolver")
.addAlias("JacobiSolver")
;
} // namespace linearsolver
} // namespace component
} // namespace sofa
| 49.206897 | 125 | 0.55431 | sofa-framework |
1c6dfcba405fcbc6ada048b7837745a2a6b620f1 | 201 | cpp | C++ | examples/s3/boo.cpp | Costallat/hunter | dc0d79cb37b30cad6d6472d7143fe27be67e26d5 | [
"BSD-2-Clause"
] | 2,146 | 2015-01-10T07:26:58.000Z | 2022-03-21T02:28:01.000Z | examples/s3/boo.cpp | koinos/hunter | fc17bc391210bf139c55df7f947670c5dff59c57 | [
"BSD-2-Clause"
] | 1,778 | 2015-01-03T11:50:30.000Z | 2019-12-26T05:31:20.000Z | examples/s3/boo.cpp | koinos/hunter | fc17bc391210bf139c55df7f947670c5dff59c57 | [
"BSD-2-Clause"
] | 734 | 2015-03-05T19:52:34.000Z | 2022-02-22T23:18:54.000Z | #include <libs3.h>
int main() {
const char *userAgentInfo = "";
int flags = 0;
const char *defaultS3HostName = "";
S3Status result = S3_initialize(userAgentInfo, flags, defaultS3HostName);
}
| 20.1 | 75 | 0.691542 | Costallat |
1c711df3cda5e748049a893729f39a16bfcf6ab8 | 920 | cpp | C++ | Lydsy/P2705 [SDOI2012]Longge的问题/P2705.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 22 | 2018-08-07T06:55:10.000Z | 2021-06-12T02:12:19.000Z | Lydsy/P2705 [SDOI2012]Longge的问题/P2705.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 28 | 2020-03-04T23:47:22.000Z | 2022-02-26T18:50:00.000Z | Lydsy/P2705 [SDOI2012]Longge的问题/P2705.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 4 | 2019-11-09T15:41:26.000Z | 2021-10-10T08:56:57.000Z | #include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#define Clr(x, t) memset(x,t,sizeof(x))
typedef long long ll;
using namespace std;
const int N = 1e5 + 10;
const int Inf = 0x3f3f3f3f;
ll read()
{
ll x = 0,f = 1;char ch = getchar();
while (ch < '0' || '9' < ch) {if (ch == '-') f = -1; ch = getchar();}
while ('0' <= ch && ch <= '9') x = x * 10 + ch - 48,ch = getchar();
return x * f;
}
//Struct
//Code
ll n, m;
ll phi(ll x)
{
ll res = x, lim = sqrt(x);
for (int i = 2; i <= lim; ++i)
if (x % i == 0)
{
res = res / i * (i - 1);
while (x % i == 0)
x /= i;
}
if (x > 1)
res = res / x * (x - 1);
return res;
}
int main()
{
m = sqrt(n = read());
ll ans = 0;
for (int i = 1; i <= m; ++i)
if (n % i == 0)
{
ans += (ll)i * phi(n / i);
ans += (ll)(n / i) * phi(i);
}
cout << ans << endl;
return 0;
}
| 17.037037 | 73 | 0.476087 | Wycers |
1c713bf86cd2476cd6b5989c4f99cac1d348ef4b | 4,053 | cc | C++ | src/vw/Camera/Extrinsics.cc | digimatronics/ComputerVision | 2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24 | [
"NASA-1.3"
] | 1 | 2021-05-16T23:57:32.000Z | 2021-05-16T23:57:32.000Z | src/vw/Camera/Extrinsics.cc | rkrishnasanka/visionworkbench | 2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24 | [
"NASA-1.3"
] | null | null | null | src/vw/Camera/Extrinsics.cc | rkrishnasanka/visionworkbench | 2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24 | [
"NASA-1.3"
] | 2 | 2017-03-18T04:06:32.000Z | 2019-01-17T10:34:39.000Z | // __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Core/Log.h>
#include <vw/Camera/Extrinsics.h>
using namespace vw;
using namespace vw::camera;
Curve3DPositionInterpolation::Curve3DPositionInterpolation(
std::vector<Vector3> const& position_samples,
double t0, double dt) {
Matrix<double> Z(position_samples.size()*3, 9);
Vector<double> p(position_samples.size() * 3);
// Reshape the position_samples matrix into a column vector
for (size_t i = 0; i < position_samples.size(); i++) {
p(3*i) = position_samples[i][0];
p(3*i+1) = position_samples[i][1];
p(3*i+2) = position_samples[i][2];
}
Vector<double> t(position_samples.size());
for (size_t i = 0; i < t.size(); i++) {
t(i) = t0 + dt*i;
}
// Populate the Z matrix
for (size_t i = 0; i < position_samples.size(); i++) {
Z(3*i , 0) = 1.0;
Z(3*i , 1) = t(i);
Z(3*i , 2) = t(i)*t(i);
Z(3*i+1, 3) = 1.0;
Z(3*i+1, 4) = t(i);
Z(3*i+1, 5) = t(i)*t(i);
Z(3*i+2, 6) = 1.0;
Z(3*i+2, 7) = t(i);
Z(3*i+2, 8) = t(i)*t(i);
}
Vector<double> x = least_squares(Z,p);
Matrix3x3 coeff;
coeff(0,0) = x(0); coeff(0,1) = x(1); coeff(0,2) = x(2);
coeff(1,0) = x(3); coeff(1,1) = x(4); coeff(1,2) = x(5);
coeff(2,0) = x(6); coeff(2,1) = x(7); coeff(2,2) = x(8);
m_cached_fit = coeff;
}
Quat SLERPPoseInterpolation::slerp(double alpha, Quat const& a,
Quat const& b, int spin) const {
const double SLERP_EPSILON = 1.0E-6; // a tiny number
double beta; // complementary interp parameter
double theta; // angle between A and B
double sin_t, cos_t; // sine, cosine of theta
double phi; // theta plus spins
int bflip; // use negation of B?
// cosine theta = dot product of A and B
cos_t = a(1)*b(1) + a(2)*b(2) + a(3)*b(3) + a(0)*b(0);
// if B is on opposite hemisphere from A, use -B instead
if (cos_t < 0.0) {
cos_t = -cos_t;
bflip = true;
} else {
bflip = false;
}
// if B is (within precision limits) the same as A,
// just linear interpolate between A and B.
// Can't do spins, since we don't know what direction to spin.
if (1.0 - cos_t < SLERP_EPSILON) {
beta = 1.0 - alpha;
} else { /* normal case */
theta = acos(cos_t);
phi = theta + spin * M_PI;
sin_t = sin(theta);
beta = sin(theta - alpha*phi) / sin_t;
alpha = sin(alpha*phi) / sin_t;
}
if (bflip)
alpha = -alpha;
// interpolate
return Quat( beta*a(0) + alpha*b(0),
beta*a(1) + alpha*b(1),
beta*a(2) + alpha*b(2),
beta*a(3) + alpha*b(3) );
}
Quat SLERPPoseInterpolation::operator()(double t) const {
// Make sure that t lies within the range [t0, t0+dt*length(points)]
if ((t < m_t0) || (t > m_t0+m_dt*m_pose_samples.size())) {
vw_out() << "Time: " << t << " min: " << m_t0
<< " max: " << (m_t0+m_dt*m_pose_samples.size()) <<"\n";
vw_throw( ArgumentErr() << "Cannot extrapolate point for time "
<< t << ". Out of valid range." );
}
size_t low_ind = (size_t)floor( (t-m_t0) / m_dt );
size_t high_ind = (size_t)ceil( (t-m_t0) / m_dt );
// If there are not enough points to interpolate at the end, we
// will limit the high_ind here.
if ( high_ind > m_pose_samples.size() ) {
vw_throw( ArgumentErr() << "Attempted to interpolate a quaternion past the last available control point." );
} else if (high_ind == m_pose_samples.size()) {
high_ind = m_pose_samples.size() - 1;
}
double low_t = m_t0 + m_dt * low_ind;
double norm_t = (t - low_t)/m_dt;
return this->slerp(norm_t, m_pose_samples[low_ind],
m_pose_samples[high_ind], 0);
}
| 32.95122 | 112 | 0.5623 | digimatronics |
1c75dcd317cdbd39b51445c4fe9ee4827b2851e3 | 4,830 | cpp | C++ | src/uscxml/plugins/datamodel/ecmascript/JavaScriptCore/dom/JSCDocumentType.cpp | sradomski/uscxml | b8ba0e7c31f397a66f9d509ff20a85b33619475a | [
"W3C",
"BSD-2-Clause"
] | null | null | null | src/uscxml/plugins/datamodel/ecmascript/JavaScriptCore/dom/JSCDocumentType.cpp | sradomski/uscxml | b8ba0e7c31f397a66f9d509ff20a85b33619475a | [
"W3C",
"BSD-2-Clause"
] | null | null | null | src/uscxml/plugins/datamodel/ecmascript/JavaScriptCore/dom/JSCDocumentType.cpp | sradomski/uscxml | b8ba0e7c31f397a66f9d509ff20a85b33619475a | [
"W3C",
"BSD-2-Clause"
] | null | null | null | /**
* @file
* @author This file has been generated by generate-bindings.pl. DO NOT MODIFY!
* @copyright Simplified BSD
*
* @cond
* This program is free software: you can redistribute it and/or modify
* it under the terms of the FreeBSD license as published by the FreeBSD
* project.
*
* 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.
*
* You should have received a copy of the FreeBSD license along with this
* program. If not, see <http://www.opensource.org/licenses/bsd-license>.
* @endcond
*/
#include "JSCDocumentType.h"
#include "JSCNamedNodeMap.h"
#include "JSCNode.h"
namespace Arabica {
namespace DOM {
JSClassRef JSCDocumentType::Tmpl;
JSStaticValue JSCDocumentType::staticValues[] = {
{ "name", nameAttrGetter, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "entities", entitiesAttrGetter, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "notations", notationsAttrGetter, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "publicId", publicIdAttrGetter, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "systemId", systemIdAttrGetter, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "internalSubset", internalSubsetAttrGetter, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ 0, 0, 0, 0 }
};
JSStaticFunction JSCDocumentType::staticFunctions[] = {
{ 0, 0, 0 }
};
JSValueRef JSCDocumentType::nameAttrGetter(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
struct JSCDocumentTypePrivate* privData = (struct JSCDocumentTypePrivate*)JSObjectGetPrivate(object);
JSStringRef stringRef = JSStringCreateWithUTF8CString(privData->nativeObj->getName().c_str());
JSValueRef retVal = JSValueMakeString(ctx, stringRef);
JSStringRelease(stringRef);
return retVal;
}
JSValueRef JSCDocumentType::entitiesAttrGetter(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
struct JSCDocumentTypePrivate* privData = (struct JSCDocumentTypePrivate*)JSObjectGetPrivate(object);
Arabica::DOM::NamedNodeMap<std::string>* arabicaRet = new Arabica::DOM::NamedNodeMap<std::string>(privData->nativeObj->getEntities());
JSClassRef arbaicaRetClass = JSCNamedNodeMap::getTmpl();
struct JSCNamedNodeMap::JSCNamedNodeMapPrivate* retPrivData = new JSCNamedNodeMap::JSCNamedNodeMapPrivate();
retPrivData->dom = privData->dom;
retPrivData->nativeObj = arabicaRet;
JSObjectRef arbaicaRetObj = JSObjectMake(ctx, arbaicaRetClass, retPrivData);
return arbaicaRetObj;
}
JSValueRef JSCDocumentType::notationsAttrGetter(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
struct JSCDocumentTypePrivate* privData = (struct JSCDocumentTypePrivate*)JSObjectGetPrivate(object);
Arabica::DOM::NamedNodeMap<std::string>* arabicaRet = new Arabica::DOM::NamedNodeMap<std::string>(privData->nativeObj->getNotations());
JSClassRef arbaicaRetClass = JSCNamedNodeMap::getTmpl();
struct JSCNamedNodeMap::JSCNamedNodeMapPrivate* retPrivData = new JSCNamedNodeMap::JSCNamedNodeMapPrivate();
retPrivData->dom = privData->dom;
retPrivData->nativeObj = arabicaRet;
JSObjectRef arbaicaRetObj = JSObjectMake(ctx, arbaicaRetClass, retPrivData);
return arbaicaRetObj;
}
JSValueRef JSCDocumentType::publicIdAttrGetter(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
struct JSCDocumentTypePrivate* privData = (struct JSCDocumentTypePrivate*)JSObjectGetPrivate(object);
JSStringRef stringRef = JSStringCreateWithUTF8CString(privData->nativeObj->getPublicId().c_str());
JSValueRef retVal = JSValueMakeString(ctx, stringRef);
JSStringRelease(stringRef);
return retVal;
}
JSValueRef JSCDocumentType::systemIdAttrGetter(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
struct JSCDocumentTypePrivate* privData = (struct JSCDocumentTypePrivate*)JSObjectGetPrivate(object);
JSStringRef stringRef = JSStringCreateWithUTF8CString(privData->nativeObj->getSystemId().c_str());
JSValueRef retVal = JSValueMakeString(ctx, stringRef);
JSStringRelease(stringRef);
return retVal;
}
JSValueRef JSCDocumentType::internalSubsetAttrGetter(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
struct JSCDocumentTypePrivate* privData = (struct JSCDocumentTypePrivate*)JSObjectGetPrivate(object);
JSStringRef stringRef = JSStringCreateWithUTF8CString(privData->nativeObj->getInternalSubset().c_str());
JSValueRef retVal = JSValueMakeString(ctx, stringRef);
JSStringRelease(stringRef);
return retVal;
}
}
}
| 40.588235 | 141 | 0.798758 | sradomski |
1c78a06ce6df0438fcb3464340f1c05f56aff8d2 | 7,774 | cpp | C++ | vm/src/vm/Core.cpp | lordadamson/tethys | 8bad2155462fb436a3da6ce1c69242486f62fe9f | [
"BSD-3-Clause"
] | null | null | null | vm/src/vm/Core.cpp | lordadamson/tethys | 8bad2155462fb436a3da6ce1c69242486f62fe9f | [
"BSD-3-Clause"
] | null | null | null | vm/src/vm/Core.cpp | lordadamson/tethys | 8bad2155462fb436a3da6ce1c69242486f62fe9f | [
"BSD-3-Clause"
] | null | null | null | #include "vm/Core.h"
#include "vm/Op.h"
#include "vm/Util.h"
namespace vm
{
inline static Op
pop_op(Core& self, const mn::Buf<uint8_t>& code)
{
return Op(pop8(code, self.r[Reg_IP].u64));
}
inline static Reg
pop_reg(Core& self, const mn::Buf<uint8_t>& code)
{
return Reg(pop8(code, self.r[Reg_IP].u64));
}
inline static Reg_Val&
load_reg(Core& self, const mn::Buf<uint8_t>& code)
{
Reg i = pop_reg(self, code);
assert(i < Reg_COUNT);
return self.r[i];
}
// API
void
core_ins_execute(Core& self, const mn::Buf<uint8_t>& code)
{
auto op = pop_op(self, code);
switch(op)
{
case Op_LOAD8:
{
auto& dst = load_reg(self, code);
dst.u8 = pop8(code, self.r[Reg_IP].u64);
break;
}
case Op_LOAD16:
{
auto& dst = load_reg(self, code);
dst.u16 = pop16(code, self.r[Reg_IP].u64);
break;
}
case Op_LOAD32:
{
auto& dst = load_reg(self, code);
dst.u32 = pop32(code, self.r[Reg_IP].u64);
break;
}
case Op_LOAD64:
{
auto& dst = load_reg(self, code);
dst.u64 = pop64(code, self.r[Reg_IP].u64);
break;
}
case Op_ADD8:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u8 += src.u8;
break;
}
case Op_ADD16:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u16 += src.u16;
break;
}
case Op_ADD32:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u32 += src.u32;
break;
}
case Op_ADD64:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u64 += src.u64;
break;
}
case Op_SUB8:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u8 -= src.u8;
break;
}
case Op_SUB16:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u16 -= src.u16;
break;
}
case Op_SUB32:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u32 -= src.u32;
break;
}
case Op_SUB64:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u64 -= src.u64;
break;
}
case Op_MUL8:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u8 *= src.u8;
break;
}
case Op_MUL16:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u16 *= src.u16;
break;
}
case Op_MUL32:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u32 *= src.u32;
break;
}
case Op_MUL64:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u64 *= src.u64;
break;
}
case Op_IMUL8:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i8 *= src.i8;
break;
}
case Op_IMUL16:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i16 *= src.i16;
break;
}
case Op_IMUL32:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i32 *= src.i32;
break;
}
case Op_IMUL64:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i64 *= src.i64;
break;
}
case Op_DIV8:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u8 /= src.u8;
break;
}
case Op_DIV16:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u16 /= src.u16;
break;
}
case Op_DIV32:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u32 /= src.u32;
break;
}
case Op_DIV64:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.u64 /= src.u64;
break;
}
case Op_IDIV8:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i8 /= src.i8;
break;
}
case Op_IDIV16:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i16 /= src.i16;
break;
}
case Op_IDIV32:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i32 /= src.i32;
break;
}
case Op_IDIV64:
{
auto& dst = load_reg(self, code);
auto& src = load_reg(self, code);
dst.i64 /= src.i64;
break;
}
case Op_CMP8:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.u8 > op2.u8)
self.cmp = Core::CMP_GREATER;
else if (op1.u8 < op2.u8)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_CMP16:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.u16 > op2.u16)
self.cmp = Core::CMP_GREATER;
else if (op1.u16 < op2.u16)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_CMP32:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.u32 > op2.u32)
self.cmp = Core::CMP_GREATER;
else if (op1.u32 < op2.u32)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_CMP64:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.u64 > op2.u64)
self.cmp = Core::CMP_GREATER;
else if (op1.u64 < op2.u64)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_ICMP8:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.i8 > op2.i8)
self.cmp = Core::CMP_GREATER;
else if (op1.i8 < op2.i8)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_ICMP16:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.i16 > op2.i16)
self.cmp = Core::CMP_GREATER;
else if (op1.i16 < op2.i16)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_ICMP32:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.i32 > op2.i32)
self.cmp = Core::CMP_GREATER;
else if (op1.i32 < op2.i32)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_ICMP64:
{
auto& op1 = load_reg(self, code);
auto& op2 = load_reg(self, code);
if (op1.i64 > op2.i64)
self.cmp = Core::CMP_GREATER;
else if (op1.i64 < op2.i64)
self.cmp = Core::CMP_LESS;
else
self.cmp = Core::CMP_EQUAL;
break;
}
case Op_JMP:
{
int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64));
self.r[Reg_IP].u64 += offset;
break;
}
case Op_JE:
{
int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64));
if (self.cmp == Core::CMP_EQUAL)
{
self.r[Reg_IP].u64 += offset;
}
break;
}
case Op_JNE:
{
int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64));
if (self.cmp != Core::CMP_EQUAL)
{
self.r[Reg_IP].u64 += offset;
}
break;
}
case Op_JL:
{
int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64));
if (self.cmp == Core::CMP_LESS)
{
self.r[Reg_IP].u64 += offset;
}
break;
}
case Op_JLE:
{
int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64));
if (self.cmp == Core::CMP_LESS || self.cmp == Core::CMP_EQUAL)
{
self.r[Reg_IP].u64 += offset;
}
break;
}
case Op_JG:
{
int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64));
if (self.cmp == Core::CMP_GREATER)
{
self.r[Reg_IP].u64 += offset;
}
break;
}
case Op_JGE:
{
int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64));
if (self.cmp == Core::CMP_GREATER || self.cmp == Core::CMP_EQUAL)
{
self.r[Reg_IP].u64 += offset;
}
break;
}
case Op_HALT:
self.state = Core::STATE_HALT;
break;
case Op_IGL:
default:
self.state = Core::STATE_ERR;
break;
}
}
} | 19.882353 | 68 | 0.583483 | lordadamson |
cc5f0159c6737950cf8497fcaf3281e8eca65677 | 93 | cpp | C++ | CsCoreDEPRECATED/Source/CsCoreDEPRECATED/AI/CsTypes_AI.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsCoreDEPRECATED/Source/CsCoreDEPRECATED/AI/CsTypes_AI.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsCoreDEPRECATED/Source/CsCoreDEPRECATED/AI/CsTypes_AI.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2019 Closed Sum Games, LLC. All Rights Reserved.
#include "AI/CsTypes_AI.h" | 46.5 | 66 | 0.763441 | closedsum |
cc627050e0e714ef8651548e2e4d95e7cd33a3ff | 1,064 | cc | C++ | tests/unit/mathematics/linalg/LinalgBackendBase_unittest.cc | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 2,753 | 2015-01-02T11:34:13.000Z | 2022-03-25T07:04:27.000Z | tests/unit/mathematics/linalg/LinalgBackendBase_unittest.cc | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 2,404 | 2015-01-02T19:31:41.000Z | 2022-03-09T10:58:22.000Z | tests/unit/mathematics/linalg/LinalgBackendBase_unittest.cc | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 1,156 | 2015-01-03T01:57:21.000Z | 2022-03-26T01:06:28.000Z | #include <gtest/gtest.h>
#include <shogun/base/ShogunEnv.h>
#include <shogun/lib/config.h>
#include <shogun/lib/SGVector.h>
#include <shogun/mathematics/linalg/LinalgNamespace.h>
using namespace shogun;
using namespace linalg;
TEST(LinalgBackendBase, SGVector_to_gpu_without_gpu_backend)
{
env()->linalg()->set_gpu_backend(nullptr);
const index_t size = 10;
SGVector<int32_t> a(size), b(size), c;
a.range_fill(0);
to_gpu(a, b);
from_gpu(b, c);
EXPECT_FALSE(a.on_gpu());
EXPECT_FALSE(b.on_gpu());
EXPECT_FALSE(c.on_gpu());
for (index_t i = 0; i < size; ++i)
EXPECT_NEAR(a[i], c[i], 1E-15);
}
TEST(LinalgBackendBase, SGMatrix_to_gpu_without_gpu_backend)
{
env()->linalg()->set_gpu_backend(nullptr);
const index_t nrows = 2, ncols = 3;
SGMatrix<int32_t> a(nrows, ncols), b(nrows, ncols), c;
for (index_t i = 0; i < nrows * ncols; ++i)
a[i] = i;
to_gpu(a, b);;
from_gpu(b, c);
EXPECT_FALSE(a.on_gpu());
EXPECT_FALSE(b.on_gpu());
EXPECT_FALSE(c.on_gpu());
for (index_t i = 0; i < nrows * ncols; ++i)
EXPECT_NEAR(a[i], c[i], 1E-15);
}
| 23.130435 | 60 | 0.684211 | ShankarNara |
cc644814ced864e55f84434873e4d5590205f56e | 7,856 | cc | C++ | chapter-casa/exp-6/main.cc | Mark1626/road-to-plus-plus | 500db757051e32e6ccd144b70171c826527610d4 | [
"CC0-1.0"
] | 1 | 2021-07-04T12:41:16.000Z | 2021-07-04T12:41:16.000Z | chapter-casa/exp-6/main.cc | Mark1626/road-to-plus-plus | 500db757051e32e6ccd144b70171c826527610d4 | [
"CC0-1.0"
] | null | null | null | chapter-casa/exp-6/main.cc | Mark1626/road-to-plus-plus | 500db757051e32e6ccd144b70171c826527610d4 | [
"CC0-1.0"
] | null | null | null | #include <casacore/casa/Arrays/IPosition.h>
#include <casacore/casa/Arrays/Matrix.h>
#include <casacore/casa/Containers/Record.h>
#include <casacore/casa/Quanta/MVTime.h>
#include <casacore/coordinates/Coordinates/Coordinate.h>
#include <casacore/coordinates/Coordinates/CoordinateSystem.h>
#include <casacore/coordinates/Coordinates/DirectionCoordinate.h>
#include <casacore/fits/FITS/FITSDateUtil.h>
#include <casacore/fits/FITS/FITSKeywordUtil.h>
#include <casacore/fits/FITS/FITSReader.h>
#include <casacore/fits/FITS/fits.h>
#include <casacore/measures/Measures/MDirection.h>
#include <fitsio.h>
#include <fstream>
#include <longnam.h>
#include <stdexcept>
#include <string>
namespace casa = casacore;
class FITSImageW {
static const int BITPIX = -32;
float minPix;
float maxPix;
casa::FitsKeywordList keywordList;
std::string name;
casa::IPosition shape;
public:
FITSImageW(std::string name, casa::IPosition shape)
: name(name), shape(shape) {}
bool create(casa::CoordinateSystem csys) {
std::ofstream outfile(name);
if (!outfile.is_open()) {
throw std::runtime_error("Unable to create file");
}
auto ndim = shape.nelements();
casa::Record header;
casa::Double b_scale, b_zero;
// if (BITPIX == -32) {
b_scale = 1.0;
b_zero = 0.0;
header.define("bitpix", BITPIX);
header.setComment("bitpix", "Floating point (32 bit)");
// }
casa::Vector<casa::Int> naxis(ndim);
for (int i = 0; i < ndim; i++)
naxis(i) = shape(i);
header.define("naxis", naxis);
header.define("bscale", b_scale);
header.setComment("bscale", "PHYSICAL = PIXEL * BSCALE + BZERO");
header.define("bzero", b_zero);
header.define("COMMENT1", "");
header.define("BUNIT", "Jy");
header.setComment("BUNIT", "Brightness (pixel) unit");
casa::IPosition shapeCpy = shape;
casa::CoordinateSystem wcs_copy = csys;
casa::Record saveHeader(header);
bool res = wcs_copy.toFITSHeader(header, shapeCpy, casa::True);
// if (!res) {
// }
if (naxis.nelements() != shapeCpy.nelements()) {
naxis.resize(shapeCpy.nelements());
for (int idx = 0; idx < shapeCpy.nelements(); idx++)
naxis(idx) = shapeCpy(idx);
header.define("NAXIS", naxis);
}
casa::String date, timesys;
casa::Time nowtime;
casa::MVTime now(nowtime);
casa::FITSDateUtil::toFITS(date, timesys, now);
header.define("date", date);
header.setComment("date", "Date FITS file was created");
if (!header.isDefined("timesys") && !header.isDefined("TIMESYS")) {
header.define("timesys", timesys);
header.setComment("timesys", "Time system for HDU");
}
header.define("ORIGIN", "Simulation");
keywordList = casa::FITSKeywordUtil::makeKeywordList();
casa::FITSKeywordUtil::addKeywords(keywordList, header);
keywordList.end();
keywordList.first();
keywordList.next();
casa::FitsKeyCardTranslator keycard;
const size_t card_size = 2880 * 4;
char cards[card_size];
memset(cards, 0, sizeof(cards));
while (keycard.build(cards, keywordList)) {
outfile << cards;
memset(cards, 0, sizeof(cards));
}
if (cards[0] != 0) {
outfile << cards;
}
return true;
}
static void wrapError(int code, int &status) {
if (code) {
char status_str[FLEN_STATUS];
fits_get_errstatus(status, status_str);
throw std::runtime_error("Error " + std::string(status_str) + " " +
std::to_string(status));
}
}
void setUnits(const std::string &units) {
fitsfile *fptr;
int status = 0;
wrapError(fits_open_file(&fptr, name.c_str(), READWRITE, &status), status);
wrapError(fits_update_key(fptr, TSTRING, "BUNIT", (void *)(units.c_str()),
"Brightness unit", &status),
status);
wrapError(fits_close_file(fptr, &status), status);
}
void setRestoringBeam(double bmaj, double bmin, double bpa) {
fitsfile *fptr;
int status = 0;
double radtodeg = 180.0 / M_PI;
wrapError(fits_open_file(&fptr, name.c_str(), READWRITE, &status), status);
double value = radtodeg * bmaj;
wrapError(fits_update_key(fptr, TDOUBLE, "BMAJ", &value,
"Restoring beam major axis", &status),
status);
value = radtodeg * bmin;
wrapError(fits_update_key(fptr, TDOUBLE, "BMIN", &value,
"Restoring beam minor axis", &status),
status);
value = radtodeg * bpa;
wrapError(fits_update_key(fptr, TDOUBLE, "BPA", &value,
"Restoring beam position angle", &status),
status);
wrapError(fits_update_key(fptr, TSTRING, "BTYPE", (void *)"Intensity", " ",
&status),
status);
wrapError(fits_close_file(fptr, &status), status);
}
bool write(casa::Array<float> &arr, casa::IPosition &where) {
fitsfile *fptr;
int status = 0;
double radtodeg = 180.0 / M_PI;
wrapError(fits_open_file(&fptr, name.c_str(), READWRITE, &status), status);
int hdutype;
wrapError(fits_movabs_hdu(fptr, 1, &hdutype, &status), status);
int naxis;
wrapError(fits_movabs_hdu(fptr, 1, &hdutype, &status), status);
wrapError(fits_get_img_dim(fptr, &naxis, &status), status);
long *axes = new long[naxis];
wrapError(fits_get_img_size(fptr, naxis, axes, &status), status);
long fpixel[4], lpixel[4];
int array_dim = arr.shape().nelements();
int location_dim = where.nelements();
fpixel[0] = where[0] + 1;
lpixel[0] = where[0] + arr.shape()[0];
fpixel[1] = where[1] + 1;
lpixel[1] = where[1] + arr.shape()[1];
if (array_dim == 2 && location_dim >= 3) {
fpixel[2] = where[2] + 1;
lpixel[2] = where[2] + 1;
if (location_dim == 4) {
fpixel[3] = where[3] + 1;
lpixel[3] = where[3] + 1;
}
} else if (array_dim == 3 && location_dim >= 3) {
fpixel[2] = where[2] + 1;
lpixel[2] = where[2] + arr.shape()[2];
if (location_dim == 4) {
fpixel[3] = where[3] + 1;
lpixel[3] = where[3] + 1;
}
} else if (array_dim == 4 && location_dim == 4) {
fpixel[2] = where[2] + 1;
lpixel[2] = where[2] + arr.shape()[2];
fpixel[3] = where[3] + 1;
lpixel[3] = where[3] + arr.shape()[3];
}
int64_t nelements = arr.nelements();
bool toDelete = false;
const float *data = arr.getStorage(toDelete);
float *dataptr = (float *)data;
long group = 0;
wrapError(fits_write_subset_flt(fptr, group, naxis, axes, fpixel, lpixel,
dataptr, &status),
status);
wrapError(fits_close_file(fptr, &status), status);
delete[] axes;
return true;
}
};
int main() {
std::string name = "dummy.fits";
int xsize = 128;
int ysize = 128;
casa::IPosition shape(2, xsize, ysize);
casa::CoordinateSystem wcs;
/*
1 0
0 1
*/
casacore::Matrix<double> xform(2, 2);
xform = 0.0;
xform.diagonal() = 1.0;
casa::DirectionCoordinate direction(
casa::MDirection::J2000, casa::Projection(casa::Projection::SIN),
294 * casa::C::pi / 180.0, -60 * casa::C::pi / 180,
-0.001 * casa::C::pi / 180.0, 0.001 * casa::C::pi / 180.0, xform,
xsize / 2.0, ysize / 2.0);
casa::Vector<casa::String> units(2);
units = "deg";
direction.setWorldAxisUnits(units);
wcs.addCoordinate(direction);
casa::Matrix<casa::Float> pixels(xsize, ysize);
pixels = 0.0;
pixels.diagonal() = 0.001;
pixels.diagonal(2) = 0.002;
casa::IPosition where(2, 0, 0);
FITSImageW fits(name, shape);
fits.create(wcs);
fits.setUnits("Jy/pixel");
fits.setRestoringBeam(2.0e-4, 1.0e-4, 1.0e-1);
fits.write(pixels, where);
}
| 28.671533 | 79 | 0.60998 | Mark1626 |
cc64622fa8d7d1e7841169261090f4849e8d0586 | 13,023 | cpp | C++ | src/renderer/base/characters.cpp | nomadsinteractive/ark | 52f84c6dbd5ca6bdd07d450b3911be1ffd995922 | [
"Apache-2.0"
] | 5 | 2018-03-28T09:14:55.000Z | 2018-04-02T11:54:33.000Z | src/renderer/base/characters.cpp | nomadsinteractive/ark | 52f84c6dbd5ca6bdd07d450b3911be1ffd995922 | [
"Apache-2.0"
] | null | null | null | src/renderer/base/characters.cpp | nomadsinteractive/ark | 52f84c6dbd5ca6bdd07d450b3911be1ffd995922 | [
"Apache-2.0"
] | null | null | null | #include "renderer/base/characters.h"
#include <cwctype>
#include "core/ark.h"
#include "core/inf/array.h"
#include "core/inf/variable.h"
#include "core/impl/boolean/boolean_by_weak_ref.h"
#include "core/util/bean_utils.h"
#include "core/util/math.h"
#include "graphics/base/layer.h"
#include "graphics/base/layer_context.h"
#include "graphics/base/glyph.h"
#include "graphics/base/render_layer.h"
#include "graphics/base/render_object.h"
#include "graphics/base/size.h"
#include "graphics/base/v3.h"
#include "graphics/impl/glyph_maker/glyph_maker_span.h"
#include "graphics/impl/renderable/renderable_passive.h"
#include "graphics/inf/glyph_maker.h"
#include "renderer/base/atlas.h"
#include "renderer/base/model.h"
#include "renderer/base/render_engine.h"
#include "renderer/base/resource_loader_context.h"
#include "renderer/inf/model_loader.h"
#include "app/base/application_context.h"
#include "app/base/resource_loader.h"
#include "app/view/layout_param.h"
#include <tinyxml2.h>
namespace ark {
Characters::Characters(const sp<LayerContext>& layer, float textScale, float letterSpacing, float lineHeight, float lineIndent)
: Characters(Ark::instance().applicationContext()->resourceLoader()->beanFactory(), layer, nullptr, textScale, letterSpacing, lineHeight, lineIndent)
{
}
Characters::Characters(const sp<Layer>& layer, float textScale, float letterSpacing, float lineHeight, float lineIndent)
: Characters(layer->context(), textScale, letterSpacing, lineHeight, lineIndent)
{
}
Characters::Characters(const sp<RenderLayer>& layer, float textScale, float letterSpacing, float lineHeight, float lineIndent)
: Characters(layer->makeContext(Layer::TYPE_DYNAMIC), textScale, letterSpacing, lineHeight, lineIndent)
{
}
Characters::Characters(const BeanFactory& factory, const sp<LayerContext>& layerContext, const sp<GlyphMaker>& characterMaker, float textScale, float letterSpacing, float lineHeight, float lineIndent)
: _bean_factory(factory), _layer_context(layerContext), _text_scale(textScale), _glyph_maker(characterMaker ? characterMaker : sp<GlyphMaker>::make<GlyphMakerSpan>()),
_letter_spacing(letterSpacing), _layout_direction(Ark::instance().applicationContext()->renderEngine()->toLayoutDirection(1.0f)), _line_height(_layout_direction * lineHeight),
_line_indent(lineIndent), _model_loader(layerContext->modelLoader()), _size(sp<Size>::make(0.0f, 0.0f))
{
}
const sp<LayoutParam>& Characters::layoutParam() const
{
return _layout_param;
}
void Characters::setLayoutParam(const sp<LayoutParam>& layoutParam)
{
_layout_param = layoutParam;
if(_layout_param)
_layout_size = _layout_param->size()->val();
}
const std::vector<sp<RenderObject>>& Characters::contents() const
{
return _contents;
}
const SafePtr<Size>& Characters::size() const
{
return _size;
}
const std::wstring& Characters::text() const
{
return _text;
}
void Characters::setText(const std::wstring& text)
{
_text = text;
createContent();
}
void Characters::setRichText(const std::wstring& richText, const Scope& args)
{
_text = richText;
createRichContent(args);
}
void Characters::renderRequest(const V3& position)
{
if(_layout_param && _layout_size != _layout_param->size()->val())
{
_layout_size = _layout_param->size()->val();
layoutContent();
}
_layer_context->renderRequest(V3());
for(const sp<RenderablePassive>& i : _renderables)
i->requestUpdate(position);
}
void Characters::createContent()
{
float boundary = _layout_param ? _layout_param->contentWidth() : 0;
float flowx = boundary > 0 ? 0 : -_letter_spacing, flowy = getFlowY();
_glyphs = makeGlyphs(_glyph_maker, _text);
flowy = doLayoutContent(_glyphs, flowx, flowy, boundary);
createLayerContent(flowx, flowy);
}
float Characters::doLayoutContent(GlyphContents& cm, float& flowx, float& flowy, float boundary)
{
return boundary > 0 ? doLayoutWithBoundary(cm, flowx, flowy, boundary) : doLayoutWithoutBoundary(cm, flowx, getFlowY());
}
void Characters::createRichContent(const Scope& args)
{
float boundary = _layout_param ? _layout_param->contentWidth() : 0;
float flowx = boundary > 0 ? 0 : -_letter_spacing, flowy = getFlowY();
BeanFactory factory = _bean_factory.ensure();
const document richtext = Documents::parseFull(Strings::toUTF8(_text));
const sp<GlyphMaker> characterMaker = factory.ensure<GlyphMaker>(richtext, args);
_glyphs.clear();
float height = doCreateRichContent(_glyphs, _glyph_maker, richtext, factory, args, flowx, flowy, boundary);
createLayerContent(flowx, height);
}
float Characters::doCreateRichContent(GlyphContents& cm, GlyphMaker& gm, const document& richtext, BeanFactory& factory, const Scope& args, float& flowx, float& flowy, float boundary)
{
float height = 0;
for(const document& i : richtext->children())
{
if(i->type() == DOMElement::ELEMENT_TYPE_TEXT)
{
for(sp<Glyph> i : makeGlyphs(gm, Strings::fromUTF8(i->value())))
cm.push_back(std::move(i));
}
else if(i->type() == DOMElement::ELEMENT_TYPE_ELEMENT)
{
const sp<GlyphMaker> characterMaker = factory.ensure<GlyphMaker>(i, args);
height = doCreateRichContent(cm, characterMaker, i, factory, args, flowx, flowy, boundary);
}
}
return height;
}
void Characters::layoutContent()
{
DCHECK(_contents.size() == _text.length(), "Contents have changed, cannot do relayout");
float boundary = _layout_param ? _layout_param->contentWidth() : 0;
float flowx = boundary > 0 ? 0 : -_letter_spacing, flowy = getFlowY();
flowy = doLayoutContent(_glyphs, flowx, flowy, boundary);
for(size_t i = 0; i < _contents.size(); ++i)
_contents.at(i)->setPosition(_glyphs.at(i)->toRenderObjectPosition());
_size->setWidth(flowx);
_size->setHeight(flowy);
}
void Characters::createLayerContent(float width, float height)
{
_contents.clear();
for(const sp<Glyph>& i : _glyphs)
_contents.push_back(i->toRenderObject());
_size->setWidth(width);
_size->setHeight(height);
_renderables.clear();
for(const sp<RenderObject>& i : _contents)
{
sp<RenderablePassive> renderable = sp<RenderablePassive>::make(i);
_layer_context->add(renderable, sp<BooleanByWeakRef<RenderablePassive>>::make(renderable, 1));
_renderables.push_back(std::move(renderable));
}
}
float Characters::doLayoutWithBoundary(GlyphContents& cm, float& flowx, float& flowy, float boundary)
{
const std::vector<LayoutChar> layoutChars = Characters::getCharacterMetrics(cm);
float fontHeight = layoutChars.size() > 0 ? layoutChars.at(0)._metrics.bounds.y() * _text_scale : 0;
size_t begin = 0;
for(size_t i = 0; i < layoutChars.size(); ++i)
{
size_t end = i + 1;
const LayoutChar& currentChar = layoutChars.at(i);
if(end == layoutChars.size() || currentChar._is_cjk || currentChar._is_word_break)
{
if(end - begin == 1)
{
placeOne(cm[i], currentChar._metrics, flowx, flowy);
if(flowx > boundary || currentChar._is_line_break)
nextLine(fontHeight, flowx, flowy);
}
else
{
float beginWidth = begin > 0 ? layoutChars.at(begin - 1)._width_integral : 0;
float width = currentChar._width_integral - beginWidth;
if(flowx + width > boundary || currentChar._is_line_break)
nextLine(fontHeight, flowx, flowy);
place(cm, layoutChars, begin, end, flowx, flowy);
}
begin = i + 1;
}
}
return std::abs(flowy) + fontHeight;
}
float Characters::doLayoutWithoutBoundary(GlyphContents& cm, float& flowx, float flowy)
{
float fontHeight = 0;
for(Glyph& i : cm)
{
const Metrics& metrics = _model_loader->loadModel(i.type()->val()).metrics();
flowx += _letter_spacing;
placeOne(i, metrics, flowx, flowy, &fontHeight);
}
return std::abs(flowy) + fontHeight;
}
void Characters::place(GlyphContents& cm, const std::vector<Characters::LayoutChar>& layouts, size_t begin, size_t end, float& flowx, float flowy)
{
for(size_t i = begin; i < end; ++i)
{
if(begin > 0)
flowx += _letter_spacing;
const Characters::LayoutChar& layoutChar = layouts.at(i);
placeOne(cm[i], layoutChar._metrics, flowx, flowy);
}
}
void Characters::placeOne(Glyph& glyph, const Metrics& metrics, float& flowx, float flowy, float* fontHeight)
{
const V2 scale = V2(_text_scale, _text_scale);
float bitmapWidth = scale.x() * metrics.size.x();
float bitmapHeight = scale.y() * metrics.size.y();
float width = scale.x() * metrics.bounds.x();
float height = scale.y() * metrics.bounds.y();
float bitmapX = scale.x() * metrics.xyz.x();
float bitmapY = scale.y() * metrics.xyz.y();
if(fontHeight)
*fontHeight = std::max(height, *fontHeight);
glyph.setLayoutPosition(V3(flowx + bitmapX, flowy + height - bitmapY - bitmapHeight, 0));
glyph.setLayoutSize(V2(bitmapWidth, bitmapHeight));
flowx += width;
}
void Characters::nextLine(float fontHeight, float& flowx, float& flowy) const
{
flowy += (_line_height != 0 ? _line_height : (fontHeight * _layout_direction));
flowx = _line_indent;
}
float Characters::getFlowY() const
{
if(!_layout_param || _layout_direction > 0)
return 0;
return _layout_param->size()->height() + _line_height;
}
std::vector<Characters::LayoutChar> Characters::getCharacterMetrics(const GlyphContents& glyphs) const
{
std::vector<LayoutChar> metrics;
std::unordered_map<wchar_t, std::tuple<Metrics, bool, bool>> mmap;
const float xScale = _text_scale;
float integral = 0;
metrics.reserve(glyphs.size());
for(const sp<Glyph>& i : glyphs)
{
const wchar_t c = i->character();
const bool isLineBreak = c == '\n';
const auto iter = mmap.find(c);
if(iter != mmap.end())
{
const std::tuple<Metrics, bool, bool>& val = iter->second;
integral += xScale * std::get<0>(val).bounds.x();
metrics.emplace_back(std::get<0>(val), integral, std::get<1>(val), std::get<2>(val), isLineBreak);
}
else
{
int32_t type = static_cast<int32_t>(c);
const Metrics& m = _model_loader->loadModel(type).metrics();
bool iscjk = isCJK(c);
bool iswordbreak = isWordBreaker(c);
integral += xScale * m.bounds.x();
mmap.insert(std::make_pair(c, std::make_tuple(m, iscjk, iswordbreak)));
metrics.emplace_back(m, integral, iscjk, iswordbreak, isLineBreak);
}
}
return metrics;
}
bool Characters::isCJK(int32_t c) const
{
return c == 0x3005 || Math::between<int32_t>(0x3400, 0x4DBF, c) || Math::between<int32_t>(0x4E00, 0x9FFF, c) ||
Math::between<int32_t>(0xF900, 0xFAFF, c) || Math::between<int32_t>(0x20000, 0x2A6DF, c) || Math::between<int32_t>(0x2A700, 0x2B73F, c) ||
Math::between<int32_t>(0x2B740, 0x2B81F, c) || Math::between<int32_t>(0x2F800, 0x2FA1F, c);
}
bool Characters::isWordBreaker(wchar_t c) const
{
return c != '_' && !std::iswalpha(c);
}
Characters::GlyphContents Characters::makeGlyphs(GlyphMaker& gm, const std::wstring& text)
{
Characters::GlyphContents glyphs = gm.makeGlyphs(text);
DCHECK(glyphs.size() == text.size(), "Bad GlyphMaker result returned, size mismatch(%d, %d), text: %s", glyphs.size(), text.size(), Strings::toUTF8(text).c_str());
for(size_t i = 0; i < text.size(); ++i)
glyphs[i]->setCharacter(text.at(i));
return glyphs;
}
Characters::BUILDER::BUILDER(BeanFactory& factory, const document& manifest)
: _bean_factory(factory), _layer_context(sp<LayerContext::BUILDER>::make(factory, manifest, Layer::TYPE_DYNAMIC)), _glyph_maker(factory.getBuilder<GlyphMaker>(manifest, "glyph-maker")),
_text_scale(factory.getBuilder<String>(manifest, "text-scale")), _letter_spacing(factory.getBuilder<Numeric>(manifest, "letter-spacing")),
_line_height(Documents::getAttribute<float>(manifest, "line-height", 0.0f)), _line_indent(Documents::getAttribute<float>(manifest, "line-indent", 0.0f))
{
}
sp<Characters> Characters::BUILDER::build(const Scope& args)
{
float textScale = _text_scale ? Strings::parse<float>(_text_scale->build(args)) : 1.0f;
return sp<Characters>::make(_bean_factory, _layer_context->build(args), _glyph_maker->build(args), textScale, BeanUtils::toFloat(_letter_spacing, args, 0.0f), _line_height, _line_indent);
}
Characters::LayoutChar::LayoutChar(const Metrics& metrics, float widthIntegral, bool isCJK, bool isWordBreak, bool isLineBreak)
: _metrics(metrics), _width_integral(widthIntegral), _is_cjk(isCJK), _is_word_break(isWordBreak), _is_line_break(isLineBreak)
{
}
}
| 37.857558 | 200 | 0.681794 | nomadsinteractive |
cc6824e011dd554b562ed3a9c271513e5d2cf604 | 2,469 | cc | C++ | services/service_manager/public/cpp/test/test_service_decorator.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | services/service_manager/public/cpp/test/test_service_decorator.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | services/service_manager/public/cpp/test/test_service_decorator.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/service_manager/public/cpp/test/test_service_decorator.h"
#include "base/memory/ptr_util.h"
namespace service_manager {
// static
std::unique_ptr<TestServiceDecorator>
TestServiceDecorator::CreateServiceWithUniqueOverride(
std::unique_ptr<Service> service,
const std::string& interface_name,
const BinderRegistryWithArgs<const BindSourceInfo&>::Binder& binder,
const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
return base::WrapUnique(new TestServiceDecorator(
std::move(service),
{std::make_tuple(interface_name, binder, task_runner)}));
}
// static
std::unique_ptr<TestServiceDecorator>
TestServiceDecorator::CreateServiceWithInterfaceOverrides(
std::unique_ptr<Service> decorated_service,
std::vector<InterfaceOverride> overrides) {
return base::WrapUnique(new TestServiceDecorator(std::move(decorated_service),
std::move(overrides)));
}
TestServiceDecorator::TestServiceDecorator(
std::unique_ptr<Service> decorated_service,
std::vector<InterfaceOverride> overrides)
: decorated_service_(std::move(decorated_service)) {
// It would be nice to accept the registry as a constructor argument, but it's
// not moveable at this time.
for (const auto& override : overrides) {
overriding_registry_.AddInterface(
std::get<0>(override), std::get<1>(override), std::get<2>(override));
}
}
TestServiceDecorator::~TestServiceDecorator() {}
void TestServiceDecorator::OnStart() {
decorated_service_->OnStart();
}
bool TestServiceDecorator::OnServiceManagerConnectionLost() {
return decorated_service_->OnServiceManagerConnectionLost();
}
void TestServiceDecorator::OnBindInterface(
const BindSourceInfo& source_info,
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
if (overriding_registry_.TryBindInterface(interface_name, &interface_pipe,
source_info)) {
return;
}
decorated_service_->OnBindInterface(source_info, interface_name,
std::move(interface_pipe));
}
void TestServiceDecorator::SetContext(ServiceContext* context) {
decorated_service_->SetContext(context);
}
} // namespace service_manager
| 34.774648 | 80 | 0.731065 | zipated |
cc68b4d592dcc1af1ee09b0268027738819e754c | 728 | cpp | C++ | src/opt/ssa/ssa.cpp | robtaylor/iroha | e7713910ee64ca98f999b98b0c77c02fcfe2da09 | [
"BSD-3-Clause"
] | 34 | 2016-02-07T17:43:55.000Z | 2021-12-18T12:01:08.000Z | src/opt/ssa/ssa.cpp | robtaylor/iroha | e7713910ee64ca98f999b98b0c77c02fcfe2da09 | [
"BSD-3-Clause"
] | 5 | 2016-04-12T09:27:31.000Z | 2021-06-29T10:59:18.000Z | src/opt/ssa/ssa.cpp | robtaylor/iroha | e7713910ee64ca98f999b98b0c77c02fcfe2da09 | [
"BSD-3-Clause"
] | 5 | 2015-12-26T10:58:46.000Z | 2021-06-25T18:58:40.000Z | #include "opt/ssa/ssa.h"
#include "opt/ssa/phi_cleaner.h"
#include "opt/ssa/ssa_converter.h"
namespace iroha {
namespace opt {
namespace ssa {
SSAConverterPass::~SSAConverterPass() {}
Pass *SSAConverterPass::Create() { return new SSAConverterPass(); }
bool SSAConverterPass::ApplyForTable(const string &key, ITable *table) {
SSAConverter converter(table, opt_log_);
converter.Perform();
return true;
}
PhiCleanerPass::~PhiCleanerPass() {}
Pass *PhiCleanerPass::Create() { return new PhiCleanerPass(); }
bool PhiCleanerPass::ApplyForTable(const string &key, ITable *table) {
PhiCleaner cleaner(table, opt_log_);
cleaner.Perform();
return true;
}
} // namespace ssa
} // namespace opt
} // namespace iroha
| 22.060606 | 72 | 0.729396 | robtaylor |
cc6afdc7e2218b1cca270b0afddac755fd9e52fb | 1,639 | cpp | C++ | Engine/Plugins/Runtime/Synthesis/Source/Synthesis/Private/SourceEffectChorus.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Runtime/Synthesis/Source/Synthesis/Private/SourceEffectChorus.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Runtime/Synthesis/Source/Synthesis/Private/SourceEffectChorus.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "SourceEffects/SourceEffectChorus.h"
void FSourceEffectChorus::Init(const FSoundEffectSourceInitData& InitData)
{
bIsActive = true;
Chorus.Init(InitData.SampleRate, 2.0f, 64);
}
void FSourceEffectChorus::OnPresetChanged()
{
GET_EFFECT_SETTINGS(SourceEffectChorus);
Chorus.SetDepth(Audio::EChorusDelays::Left, Settings.Depth);
Chorus.SetDepth(Audio::EChorusDelays::Center, Settings.Depth);
Chorus.SetDepth(Audio::EChorusDelays::Right, Settings.Depth);
Chorus.SetFeedback(Audio::EChorusDelays::Left, Settings.Feedback);
Chorus.SetFeedback(Audio::EChorusDelays::Center, Settings.Feedback);
Chorus.SetFeedback(Audio::EChorusDelays::Right, Settings.Feedback);
Chorus.SetFrequency(Audio::EChorusDelays::Left, Settings.Frequency);
Chorus.SetFrequency(Audio::EChorusDelays::Center, Settings.Frequency);
Chorus.SetFrequency(Audio::EChorusDelays::Right, Settings.Frequency);
Chorus.SetWetLevel(Settings.WetLevel);
Chorus.SetSpread(Settings.Spread);
}
void FSourceEffectChorus::ProcessAudio(const FSoundEffectSourceInputData& InData, FSoundEffectSourceOutputData& OutData)
{
if (InData.AudioFrame.Num() == 2)
{
Chorus.ProcessAudio(InData.AudioFrame[0], InData.AudioFrame[1], OutData.AudioFrame[0], OutData.AudioFrame[1]);
}
else
{
float OutLeft = 0.0f;
float OutRight = 0.0f;
Chorus.ProcessAudio(InData.AudioFrame[0], InData.AudioFrame[0], OutLeft, OutRight);
OutData.AudioFrame[0] = 0.5f * (OutLeft + OutRight);
}
}
void USourceEffectChorusPreset::SetSettings(const FSourceEffectChorusSettings& InSettings)
{
UpdateSettings(InSettings);
} | 32.78 | 120 | 0.785845 | windystrife |
cc7017dda9b6c5b938f6d22364ea0d0ab6dbd4a6 | 44,110 | cpp | C++ | unittest/obproxy/test_event_processor.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 74 | 2021-05-31T15:23:49.000Z | 2022-03-12T04:46:39.000Z | unittest/obproxy/test_event_processor.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 16 | 2021-05-31T15:26:38.000Z | 2022-03-30T06:02:43.000Z | unittest/obproxy/test_event_processor.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 64 | 2021-05-31T15:25:36.000Z | 2022-02-23T08:43:58.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX PROXY_EVENT
#define private public
#define protected public
#include <gtest/gtest.h>
#include <pthread.h>
#include "test_eventsystem_api.h"
namespace oceanbase
{
namespace obproxy
{
using namespace proxy;
using namespace common;
using namespace event;
#define TEST_SPAWN_THREADS_NUM 1
#define TEST_DEFAULT_NEXT_THREAD 0
#define TEST_DEFAULT_DTHREAD_NUM 0
#define TEST_ET_SPAWN (ET_CALL + 1)
#define OB_ALIGN(size, boundary) (((size) + ((boundary) - 1)) & ~((boundary) - 1))
#define INVALID_SPAWN_EVENT_THREADS(...) \
{ \
ASSERT_TRUE(OB_INVALID_ARGUMENT == g_event_processor.spawn_event_threads(__VA_ARGS__));\
}
#define NULL_SCHEDULE_IMM(...) \
{ \
ASSERT_TRUE(NULL == g_event_processor.schedule_imm(__VA_ARGS__)); \
}
#define NULL_SCHEDULE_AT(...) \
{ \
ASSERT_TRUE(NULL == g_event_processor.schedule_at(__VA_ARGS__)); \
}
#define NULL_SCHEDULE_IN(...) \
{ \
ASSERT_TRUE(NULL == g_event_processor.schedule_in(__VA_ARGS__)); \
}
#define NULL_SCHEDULE_EVERY(...) \
{ \
ASSERT_TRUE(NULL == g_event_processor.schedule_every(__VA_ARGS__)); \
}
#define NULL_SCHEDULE_IMM_SIGNAL(...) \
{ \
ASSERT_TRUE(NULL == g_event_processor.schedule_imm_signal(__VA_ARGS__)); \
}
#define NULL_SCHEDULE(...) \
{ \
ASSERT_TRUE(NULL == g_event_processor.schedule(__VA_ARGS__)->ethread_); \
}
#define NULL_PREPARE_SCHEDULE_IMM(...) \
{ \
ASSERT_TRUE(NULL == g_event_processor.prepare_schedule_imm(__VA_ARGS__)); \
}
enum TestProcessorFuncType
{
TEST_NULL = 0,
TEST_SCHEDULE_IMM = 1,
TEST_SCHEDULE_IMM_SIGNAL,
TEST_SCHEDULE_AT,
TEST_SCHEDULE_IN ,
TEST_SCHEDULE_EVERY,
TEST_PREPARE_SCHEDULE_IMM,
TEST_DO_SCHEDULE,
TEST_SCHEDULE,
TEST_SPAWN_THREAD
};
unsigned int next_thread[2] = {TEST_DEFAULT_NEXT_THREAD, TEST_DEFAULT_NEXT_THREAD};
unsigned int event_thread_count[2] = {TEST_ET_CALL_THREADS_NUM, TEST_SPAWN_THREADS_NUM};
unsigned int event_type_count = 0;
int64_t dthread_num = TEST_DEFAULT_DTHREAD_NUM;
int handle_schedule_test(ObContInternal *contp, ObEventType event, void *edata);
void *thread_main_start_test(void *func_param);
void set_fast_signal_true(TestFuncParam *param);
class TestEventProcessor : public ::testing::Test
{
public:
virtual void SetUp();
virtual void TearDown();
static void check_start(TestFuncParam *param);
static void check_spawn_event_threads(TestFuncParam *param);
static void check_schedule_common(TestFuncParam *param);
static void check_schedule_imm(TestFuncParam *param);
static void check_schedule_imm_signal(TestFuncParam *param);
static void check_schedule_at(TestFuncParam *param);
static void check_schedule_in(TestFuncParam *param);
static void check_schedule_every(TestFuncParam *param);
static void check_schedule(TestFuncParam *param);
static void check_prepare_schedule_imm(TestFuncParam *param);
static void check_do_schedule(TestFuncParam *param);
static void check_allocate(TestFuncParam *param);
static void check_assign_thread(TestFuncParam *param);
static void check_spawn_thread(TestFuncParam *param);
public:
TestFuncParam *test_param[MAX_PARAM_ARRAY_SIZE];
};
void TestEventProcessor::SetUp()
{
for (int i = 0; i < MAX_PARAM_ARRAY_SIZE; ++i) {
test_param[i] = NULL;
}
}
void TestEventProcessor::TearDown()
{
for (int i = 0; i < MAX_PARAM_ARRAY_SIZE; ++i) {
if (NULL != test_param[i]) {
destroy_funcparam_test(test_param[i]);
} else {}
}
}
void TestEventProcessor::check_start(TestFuncParam *param)
{
init_event_system(EVENT_SYSTEM_MODULE_VERSION);
ASSERT_EQ(0, g_event_processor.event_thread_count_);
ASSERT_EQ(0, g_event_processor.thread_group_count_);
ASSERT_EQ(0, g_event_processor.dedicate_thread_count_);
ASSERT_EQ(0, g_event_processor.thread_data_used_);
ASSERT_FALSE(g_event_processor.started_);
for (int i = 0; i < MAX_EVENT_TYPES; ++i) {
ASSERT_EQ(0, g_event_processor.thread_count_for_type_[i]);
ASSERT_EQ(0U, g_event_processor.next_thread_for_type_[i]);
for (int64_t j = 0; j < MAX_THREADS_IN_EACH_TYPE; ++j) {
ASSERT_TRUE(NULL == g_event_processor.event_thread_[i][j]);
}
}
for (int64_t i = 0; i < MAX_EVENT_THREADS; ++i) {
ASSERT_TRUE(NULL == g_event_processor.all_event_threads_[i]);
ASSERT_TRUE(NULL == g_event_processor.all_dedicate_threads_[i]);
}
ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(-100));
ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(-1));
ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(0));
ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(MAX_EVENT_THREADS + 1));
ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(MAX_EVENT_THREADS + 100));
ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(1, -100));
ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(1, -1));
ASSERT_EQ(OB_SUCCESS, g_event_processor.start(TEST_ET_CALL_THREADS_NUM, DEFAULT_STACKSIZE, false, false));
ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(MAX_EVENT_THREADS));
ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(0));
ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(-1));
ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(-1, 0));
ASSERT_EQ(TEST_ET_CALL_THREADS_NUM, g_event_processor.event_thread_count_);
ASSERT_EQ(TEST_ET_CALL_THREADS_NUM, g_event_processor.thread_count_for_type_[ET_CALL]);
ASSERT_EQ(1, g_event_processor.thread_group_count_);
ASSERT_EQ(0, g_event_processor.dedicate_thread_count_);
ASSERT_TRUE(g_event_processor.started_);
for (int64_t i = 0; i < TEST_ET_CALL_THREADS_NUM; ++i) {
ASSERT_TRUE(g_event_processor.all_event_threads_[i] != NULL);
ASSERT_TRUE(g_event_processor.event_thread_[ET_CALL][i]
== g_event_processor.all_event_threads_[i]);
ASSERT_TRUE(REGULAR == g_event_processor.all_event_threads_[i]->tt_);
ASSERT_TRUE(g_event_processor.all_event_threads_[i]->is_event_thread_type(ET_CALL));
}
next_thread[ET_CALL] = TEST_DEFAULT_NEXT_THREAD;
++event_type_count;
param->test_ok_ = true;
}
void TestEventProcessor::check_spawn_event_threads(TestFuncParam *param)
{
int64_t stacksize = DEFAULT_STACKSIZE;
ObEventThreadType etype = 0;
char thr_name[MAX_THREAD_NAME_LENGTH];
snprintf(thr_name, MAX_THREAD_NAME_LENGTH, "[T_ET_SPAWN]");
char *thr_null = NULL;
INVALID_SPAWN_EVENT_THREADS(-100, thr_name, stacksize, etype);
INVALID_SPAWN_EVENT_THREADS(-1, thr_name, stacksize, etype);
INVALID_SPAWN_EVENT_THREADS(0, thr_name, stacksize, etype);
INVALID_SPAWN_EVENT_THREADS(MAX_EVENT_THREADS - TEST_ET_CALL_THREADS_NUM + 1,
thr_name, stacksize, etype);
int64_t thread_group_count = g_event_processor.thread_group_count_;//save
g_event_processor.thread_group_count_ = MAX_EVENT_TYPES;//update error key
INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, stacksize, etype);
g_event_processor.thread_group_count_ = MAX_EVENT_TYPES + 1;//update error key
INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, stacksize, etype);
g_event_processor.thread_group_count_ = thread_group_count;//reset
INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_null, stacksize, etype);
INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, -100, etype);
INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, -1, etype);
ASSERT_TRUE(OB_SUCCESS == g_event_processor.spawn_event_threads(TEST_SPAWN_THREADS_NUM,
thr_name,
stacksize,
etype));
ASSERT_EQ(TEST_ET_SPAWN, etype);
ASSERT_EQ(2, g_event_processor.thread_group_count_);
ASSERT_EQ(TEST_SPAWN_THREADS_NUM, g_event_processor.thread_count_for_type_[TEST_ET_SPAWN]);
int64_t tmp_n = g_event_processor.event_thread_count_ - TEST_SPAWN_THREADS_NUM;
for (int64_t i = tmp_n; i < g_event_processor.event_thread_count_; ++i) {
ASSERT_TRUE(NULL != g_event_processor.all_event_threads_[i]);
ASSERT_TRUE(g_event_processor.event_thread_[TEST_ET_SPAWN][i - tmp_n]
== g_event_processor.all_event_threads_[i]);
ASSERT_TRUE(REGULAR == g_event_processor.all_event_threads_[i]->tt_);
ASSERT_TRUE(g_event_processor.all_event_threads_[i]->is_event_thread_type(TEST_ET_SPAWN));
}
next_thread[TEST_ET_SPAWN] = TEST_DEFAULT_NEXT_THREAD;
++event_type_count;
param->test_ok_ = true;
}
void TestEventProcessor::check_schedule_common(TestFuncParam *param)
{
ASSERT_EQ(param->callback_event_, param->event_->callback_event_);
ASSERT_TRUE(param->cookie_ == param->event_->cookie_);
ASSERT_TRUE(param->cont_ == param->event_->continuation_);
ASSERT_FALSE(param->event_->cancelled_);
ASSERT_TRUE(param->event_->continuation_->mutex_ == param->event_->mutex_);
if (event_thread_count[param->event_type_] > 1)
ASSERT_EQ(++next_thread[param->event_type_],
g_event_processor.next_thread_for_type_[param->event_type_]);
else {
ASSERT_EQ(0U, g_event_processor.next_thread_for_type_[param->event_type_]);
}
}
void TestEventProcessor::check_schedule_imm(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_SCHEDULE_IMM;
param->cookie_ = param;
param->callback_event_ = EVENT_IMMEDIATE;
ObContinuation *cont_null = NULL;
NULL_SCHEDULE_IMM(cont_null, param->event_type_, param->callback_event_, param->cookie_);
NULL_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES, param->callback_event_, param->cookie_);
NULL_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES + 1, param->callback_event_, param->cookie_);
NULL_SCHEDULE_IMM(param->cont_, -10, param->callback_event_, param->cookie_);
NULL_SCHEDULE_IMM(param->cont_, -1, param->callback_event_, param->cookie_);
NULL_SCHEDULE_IMM(param->cont_, event_type_count + 1, param->callback_event_, param->cookie_);
((ObContInternal *)param->cont_)->event_count_++;
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.schedule_imm(param->cont_,
param->event_type_,
param->callback_event_,
param->cookie_);
ASSERT_TRUE(NULL != param->event_);
} else {
check_schedule_common(param);
ASSERT_EQ(0, param->event_->timeout_at_);
ASSERT_EQ(0, param->event_->period_);
param->test_ok_ = check_imm_test_ok(hrtime_diff(param->cur_time_, param->last_time_));
}
}
void TestEventProcessor::check_schedule_at(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_SCHEDULE_AT;
param->cookie_ = param;
param->callback_event_ = EVENT_INTERVAL;
param->atimeout_ = TEST_TIME_SECOND_AT(param);
ObContinuation *cont_null = NULL;
NULL_SCHEDULE_AT(cont_null, param->atimeout_, param->event_type_,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_AT(param->cont_, param->atimeout_, MAX_EVENT_TYPES,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_AT(param->cont_, param->atimeout_, MAX_EVENT_TYPES + 1,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_AT(param->cont_, param->atimeout_, -10, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_AT(param->cont_, param->atimeout_, -1, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_AT(param->cont_, param->atimeout_, event_type_count + 1,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_AT(param->cont_, HRTIME_SECONDS(0), param->event_type_,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_AT(param->cont_, HRTIME_SECONDS(-1), param->event_type_,
param->callback_event_, param->cookie_);
((ObContInternal *)param->cont_)->event_count_++;
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.schedule_at(param->cont_,
param->atimeout_,
param->event_type_,
param->callback_event_,
param->cookie_);
ASSERT_TRUE(NULL != param->event_);
ASSERT_TRUE(param->at_delta_ > 0 ? 1 == param->event_->in_the_prot_queue_ : true);
} else {
check_schedule_common(param);
ASSERT_GE(TEST_TIME_SECOND_AT(param), param->event_->timeout_at_);
ASSERT_EQ(0, param->event_->period_);
check_test_ok(param, param->at_delta_);
// param->at_delta_ <= 0,//at the past point, equal to imm
// param->at_delta_ > 0,//at the future point, equal to in
}
}
void TestEventProcessor::check_schedule_in(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_SCHEDULE_IN;
param->cookie_ = param;
param->callback_event_ = EVENT_INTERVAL;
ObContinuation *cont_null = NULL;
NULL_SCHEDULE_IN(cont_null, param->atimeout_, param->event_type_,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_IN(param->cont_, param->atimeout_, MAX_EVENT_TYPES,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_IN(param->cont_, param->atimeout_, MAX_EVENT_TYPES + 1,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_IN(param->cont_, param->atimeout_, -10, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_IN(param->cont_, param->atimeout_, -1, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_IN(param->cont_, param->atimeout_, event_type_count + 1,
param->callback_event_, param->cookie_);
((ObContInternal *)param->cont_)->event_count_++;
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.schedule_in(param->cont_,
param->atimeout_,
param->event_type_,
param->callback_event_,
param->cookie_);
ASSERT_TRUE(NULL != param->event_);
ASSERT_TRUE(param->atimeout_ > 0 ? 1 == param->event_->in_the_prot_queue_ : true);
if (param->event_->timeout_at_ < 0) {//drop into poll queue, can not update deletable_
((ObContInternal *)(param->cont_))->deletable_ = true;
} else {}
} else {
check_schedule_common(param);
ASSERT_LT(param->atimeout_, param->event_->timeout_at_);
ASSERT_GE(get_hrtime_internal() + param->atimeout_, param->event_->timeout_at_);
ASSERT_EQ(0, param->event_->period_);
check_test_ok(param, param->atimeout_);
//param->atimeout_ <= 0 //in the past point,equal to imm
}
}
void TestEventProcessor::check_schedule_every(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_SCHEDULE_EVERY;
param->cookie_ = param;
param->callback_event_ = EVENT_INTERVAL;
ObContinuation *cont_null = NULL;
NULL_SCHEDULE_EVERY(cont_null, param->aperiod_, param->event_type_,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, MAX_EVENT_TYPES,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, MAX_EVENT_TYPES + 1,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, -10, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, -1, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, event_type_count + 1,
param->callback_event_, param->cookie_);
NULL_SCHEDULE_EVERY(param->cont_, HRTIME_SECONDS(0), param->event_type_,
param->callback_event_, param->cookie_);
((ObContInternal *)param->cont_)->event_count_ += TEST_DEFAULT_PERIOD_COUNT;
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.schedule_every(param->cont_,
param->aperiod_,
param->event_type_,
param->callback_event_,
param->cookie_);
ASSERT_TRUE(NULL != param->event_);
ASSERT_TRUE(param->aperiod_ > 0 ? 1 == param->event_->in_the_prot_queue_ : true);
if (param->aperiod_ < 0) {//drop into poll queue, can not update deletable_
((ObContInternal *)(param->cont_))->deletable_ = true;
} else {}
} else {
SCHEDULE_EVERY_FIRST_CHECK;
param->test_ok_ = param->test_ok_ && check_test_ok(param, param->aperiod_);
//param->aperiod_ < 0 ;//equal to schedule at, will fall into negative_queue
}
}
void TestEventProcessor::check_schedule(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_SCHEDULE;
param->callback_event_ = param->event_->callback_event_;
param->cookie_ = param;
param->event_->cookie_ = param;
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.schedule(param->event_,
param->event_type_,
param->fast_signal_);
ASSERT_TRUE(NULL != param->event_);
ASSERT_TRUE(NULL != param->event_->ethread_);
} else {
check_schedule_result(param, check_schedule_imm, check_schedule_at,
check_schedule_in, check_schedule_every);
if (param->fast_signal_) {
param->test_ok_ = param->test_ok_ && g_signal_hook_success;
}
}
}
void TestEventProcessor::check_schedule_imm_signal(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_SCHEDULE_IMM_SIGNAL;
param->cookie_ = param;
param->callback_event_ = EVENT_IMMEDIATE;
set_fast_signal_true(param);
ObContinuation *cont_null = NULL;
NULL_SCHEDULE_IMM_SIGNAL(cont_null, param->event_type_, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_IMM_SIGNAL(param->cont_, MAX_EVENT_TYPES, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_IMM_SIGNAL(param->cont_, MAX_EVENT_TYPES + 1, param->callback_event_,
param->cookie_);
NULL_SCHEDULE_IMM_SIGNAL(param->cont_, -10, param->callback_event_, param->cookie_);
NULL_SCHEDULE_IMM_SIGNAL(param->cont_, -1, param->callback_event_, param->cookie_);
NULL_SCHEDULE_IMM_SIGNAL(param->cont_, event_type_count + 1, param->callback_event_,
param->cookie_);
((ObContInternal *)param->cont_)->event_count_++;
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.schedule_imm_signal(param->cont_,
param->event_type_,
param->callback_event_,
param->cookie_);
ASSERT_TRUE(NULL != param->event_);
} else {
check_schedule_imm(param);
param->test_ok_ = param->test_ok_ && g_signal_hook_success;
}
}
void TestEventProcessor::check_prepare_schedule_imm(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_PREPARE_SCHEDULE_IMM;
param->callback_event_ = EVENT_IMMEDIATE;
param->cookie_ = param;
ObContinuation *cont_null = NULL;
NULL_PREPARE_SCHEDULE_IMM(cont_null, param->event_type_, param->callback_event_,
param->cookie_);
NULL_PREPARE_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES, param->callback_event_,
param->cookie_);
NULL_PREPARE_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES + 1, param->callback_event_,
param->cookie_);
NULL_PREPARE_SCHEDULE_IMM(param->cont_, -10, param->callback_event_, param->cookie_);
NULL_PREPARE_SCHEDULE_IMM(param->cont_, -1, param->callback_event_, param->cookie_);
NULL_PREPARE_SCHEDULE_IMM(param->cont_, event_type_count + 1, param->callback_event_,
param->cookie_);
((ObContInternal *)param->cont_)->event_count_++;
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.prepare_schedule_imm(param->cont_,
param->event_type_,
param->callback_event_,
param->cookie_);
ASSERT_TRUE(NULL != param->event_);
param->event_->ethread_->event_queue_external_.enqueue(param->event_);
} else {
check_schedule_imm(param);
}
}
void TestEventProcessor::check_do_schedule(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_DO_SCHEDULE;
param->callback_event_ = param->event_->callback_event_;
param->cookie_ = param;
param->event_->cookie_ = param;
ObEvent *event_null = NULL;
g_event_processor.do_schedule(event_null, param->fast_signal_);
param->last_time_ = get_hrtime_internal();
g_event_processor.do_schedule(param->event_, param->fast_signal_);
} else {
check_schedule(param);
}
}
void TestEventProcessor::check_allocate(TestFuncParam *param)
{
int64_t start = OB_ALIGN(offsetof(ObEThread, thread_private_), 16);
int64_t old = g_event_processor.thread_data_used_;
int64_t loss = start - offsetof(ObEThread, thread_private_);
ASSERT_TRUE(-1 == g_event_processor.allocate(-10));
ASSERT_TRUE((old + start) == g_event_processor.allocate(0));
ASSERT_TRUE(-1 == g_event_processor.allocate(ObEThread::MAX_THREAD_DATA_SIZE - old - loss + 1));
ASSERT_TRUE((start + old) == g_event_processor.allocate(1));
ASSERT_TRUE(g_event_processor.thread_data_used_ == old + 16);
old = old + 16;
ASSERT_TRUE((start + old) == g_event_processor.allocate(17));
ASSERT_TRUE(g_event_processor.thread_data_used_ == old + 32);
old = old + 32;
ASSERT_TRUE((start + old) == g_event_processor.allocate(16));
ASSERT_TRUE(g_event_processor.thread_data_used_ == old + 16);
param->test_ok_ = true;
}
void TestEventProcessor::check_assign_thread(TestFuncParam *param)
{
ObEventThreadType event_type = ET_CALL;
for (int i = 0; i < 10; ++i) {
ASSERT_TRUE(NULL != g_event_processor.assign_thread(event_type));
if (g_event_processor.next_thread_for_type_[event_type] > 1) {
ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type],
++next_thread[event_type]);
} else {
ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type], 0U);
}
}
event_type = TEST_ET_SPAWN;
for (int i = 0; i < 10; ++i) {
ASSERT_TRUE(NULL != g_event_processor.assign_thread(event_type));
if (g_event_processor.next_thread_for_type_[event_type] > 1) {
ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type],
++next_thread[event_type]);
} else {
ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type], 0U);
}
}
param->test_ok_ = true;
}
void TestEventProcessor::check_spawn_thread(TestFuncParam *param)
{
if (!param->started_) {
param->started_ = true;
param->func_type_ = TEST_SPAWN_THREAD;
snprintf(param->thr_name_, MAX_THREAD_NAME_LENGTH, "[T_ET_SPAWN_D]");
((ObContInternal *)param->cont_)->event_count_++;
char *thr_null = NULL;
ObContinuation *cont_null = NULL;
int64_t dedicate_thread_count = g_event_processor.dedicate_thread_count_;
ASSERT_TRUE(NULL == g_event_processor.spawn_thread(cont_null,
param->thr_name_,
param->stacksize_));
g_event_processor.dedicate_thread_count_ = MAX_EVENT_THREADS;
ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_,
param->thr_name_,
param->stacksize_));
g_event_processor.dedicate_thread_count_ = MAX_EVENT_THREADS + 10;
ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_,
param->thr_name_,
param->stacksize_));
g_event_processor.dedicate_thread_count_ = dedicate_thread_count;
ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_,
thr_null,
param->stacksize_));
ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_,
param->thr_name_,
-100));
param->last_time_ = get_hrtime_internal();
param->event_ = g_event_processor.spawn_thread(param->cont_,
param->thr_name_,
param->stacksize_);
param->event_->cookie_ = param;
ASSERT_TRUE(NULL != param->event_);
} else {
ASSERT_TRUE(param->cont_ == param->event_->continuation_);
ASSERT_EQ(0, param->event_->timeout_at_);
ASSERT_EQ(0, param->event_->period_);
ASSERT_FALSE(param->event_->cancelled_);
ASSERT_TRUE(param->event_->continuation_->mutex_ == param->event_->mutex_);
ASSERT_TRUE(DEDICATED == g_event_processor.all_dedicate_threads_[dthread_num]->tt_);
ASSERT_TRUE(++dthread_num == g_event_processor.dedicate_thread_count_);
param->test_ok_ = check_imm_test_ok(hrtime_diff(param->cur_time_, param->last_time_));
}
}
int handle_schedule_test(ObContInternal *contp, ObEventType event, void *edata)
{
UNUSED(event);
UNUSED(contp);
TestFuncParam *param;
param = static_cast<TestFuncParam *>((static_cast<ObEvent *>(edata))->cookie_);
++param->seq_no_;
param->cur_time_ = get_hrtime_internal();
switch (param->func_type_) {
case TEST_SCHEDULE_IMM:
case TEST_PREPARE_SCHEDULE_IMM: {
TestEventProcessor::check_schedule_imm(param);
break;
}
case TEST_SCHEDULE_IN: {
TestEventProcessor::check_schedule_in(param);
break;
}
case TEST_SCHEDULE_AT: {
TestEventProcessor::check_schedule_at(param);
break;
}
case TEST_SCHEDULE_EVERY: {
TestEventProcessor::check_schedule_every(param);
break;
}
case TEST_SCHEDULE_IMM_SIGNAL: {
TestEventProcessor::check_schedule_imm_signal(param);
break;
}
case TEST_SCHEDULE: {
TestEventProcessor::check_schedule(param);
break;
}
case TEST_DO_SCHEDULE: {
TestEventProcessor::check_do_schedule(param);
break;
}
case TEST_SPAWN_THREAD: {
TestEventProcessor::check_spawn_thread(param);
break;
}
default: {
LOG_ERROR("handle_schedule_test, invalid event type");
break;
}
}
#ifdef DEBUG_TEST // print the process
print_process(param->seq_no_, param->cur_time_, param->last_time_);
#endif
int ret = OB_ERROR;
if (TEST_SCHEDULE_EVERY == param->func_type_
|| (EVENT_INTERVAL == param->event_->callback_event_ && 0 != param->event_->period_)) {
param->last_time_ = param->cur_time_;
if (param->period_count_ > 1) {
--param->period_count_;
} else {
ret = OB_SUCCESS;
param->event_->cancelled_ = true;
}
} else {
ret = OB_SUCCESS;
}
if (OB_SUCC(ret)) {
signal_condition(param->wait_cond_);
}
return ret;
}
void *thread_main_start_test(void *func_param)
{
TestEventProcessor::check_start((TestFuncParam *)func_param);
signal_condition(((TestFuncParam *)func_param)->wait_cond_);
this_ethread()->execute();
return NULL;
}
void set_fast_signal_true(TestFuncParam *param)
{
int next = 0;
param->fast_signal_ = true;
g_signal_hook_success = false;
if (event_thread_count[param->event_type_] > 1) {
next = next_thread[param->event_type_] % event_thread_count[param->event_type_];
} else {
next = 0;
}
ObEThread *tmp_ethread = g_event_processor.event_thread_[param->event_type_][next];
tmp_ethread->signal_hook_ = handle_hook_test;
}
TEST_F(TestEventProcessor, eventprocessor_start)
{
LOG_DEBUG("eventprocessor start");
pthread_t thread;
test_param[0] = create_funcparam_test();
pthread_attr_t *attr_null = NULL;
if (0 != pthread_create(&thread, attr_null, thread_main_start_test, (void *)test_param[0])) {
LOG_ERROR("failed to create processor_start");
} else {
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
}
}
TEST_F(TestEventProcessor, eventprocessor_spawn_event_threads)
{
LOG_DEBUG("eventprocessor spawn_event_threads");
test_param[0] = create_funcparam_test();
TestEventProcessor::check_spawn_event_threads(test_param[0]);
ASSERT_TRUE(test_param[0]->test_ok_);
}
TEST_F(TestEventProcessor, eventprocessor_schedule_imm1)
{
LOG_DEBUG("eventprocessor schedule_imm");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->event_type_ = ET_CALL;
TestEventProcessor::check_schedule_imm(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
}
TEST_F(TestEventProcessor, eventprocessor_schedule_imm2_spawn)
{
LOG_DEBUG("eventprocessor schedule_imm (spawn)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
test_param[0]->event_type_ = TEST_ET_SPAWN;
TestEventProcessor::check_schedule_imm(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
}
TEST_F(TestEventProcessor, eventprocessor_schedule_at1)
{
LOG_DEBUG("eventprocessor schedule_at");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->at_delta_ = HRTIME_SECONDS(2);
test_param[0]->event_type_ = ET_CALL;
TestEventProcessor::check_schedule_at(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule_at2_minus_spawn)
{
LOG_DEBUG("eventprocessor schedule_at (-spawn)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
test_param[0]->at_delta_ = HRTIME_SECONDS(-2);
test_param[0]->event_type_ = TEST_ET_SPAWN;
TestEventProcessor::check_schedule_at(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule_in1)
{
LOG_DEBUG("eventprocessor schedule_in");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->event_type_ = ET_CALL;
test_param[0]->atimeout_ = TEST_TIME_SECOND_IN;
TestEventProcessor::check_schedule_in(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule_in2_minus_spawn)
{
LOG_DEBUG("eventprocessor schedule_in (-spawn)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
test_param[0]->event_type_ = TEST_ET_SPAWN;
test_param[0]->atimeout_ = 0 - TEST_TIME_SECOND_IN;
TestEventProcessor::check_schedule_in(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule_in3_minus_negative_queue)
{
LOG_DEBUG("eventprocessor schedule_in (-negative_queue)");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->event_type_ = ET_CALL;
test_param[0]->atimeout_ = 0 - TEST_TIME_SECOND_IN - get_hrtime_internal();
TestEventProcessor::check_schedule_in(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule_every1)
{
LOG_DEBUG("eventprocessor schedule_every");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->event_type_ = ET_CALL;
test_param[0]->aperiod_ = TEST_TIME_SECOND_EVERY;
TestEventProcessor::check_schedule_every(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule_every2_minus_spawn_negative_queue)
{
LOG_DEBUG("eventprocessor schedule_every (-spawn negative_queue)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
test_param[0]->event_type_ = TEST_ET_SPAWN;
test_param[0]->aperiod_ = 0 - TEST_TIME_SECOND_EVERY;
TestEventProcessor::check_schedule_every(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule1_in)
{
LOG_DEBUG("eventprocessor schedule (ET_CALL in)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
ASSERT_TRUE(NULL != test_param[0]->cont_->mutex_);
if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) {
LOG_ERROR("fail to alloc mem for processor_schedule test");
} else {
test_param[0]->event_type_ = ET_CALL;
test_param[0]->event_->callback_event_ = EVENT_INTERVAL;
test_param[0]->atimeout_ = TEST_TIME_SECOND_IN;
ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_,
get_hrtime_internal() + test_param[0]->atimeout_, 0));
ASSERT_TRUE(test_param[0]->event_->is_inited_);
test_param[0]->fast_signal_ = false;
((ObContInternal *)test_param[0]->cont_)->event_count_++;
TestEventProcessor::check_schedule(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
}
};
TEST_F(TestEventProcessor, eventprocessor_schedule2_at)
{
LOG_DEBUG("eventprocessor schedule (spawn at)");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) {
LOG_ERROR("fail to alloc mem for processor_schedule test");
} else {
test_param[0]->event_type_ = TEST_ET_SPAWN;
test_param[0]->event_->callback_event_ = EVENT_INTERVAL;
test_param[0]->at_delta_ = HRTIME_SECONDS(2);
test_param[0]->atimeout_ = TEST_TIME_SECOND_AT(test_param[0]);
ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_, test_param[0]->atimeout_, 0));
ASSERT_TRUE(test_param[0]->event_->is_inited_);
((ObContInternal *)test_param[0]->cont_)->event_count_++;
set_fast_signal_true(test_param[0]);
TestEventProcessor::check_schedule(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
}
};
TEST_F(TestEventProcessor, eventprocessor_schedule_imm_signal1)
{
LOG_DEBUG("eventprocessor schedule_imm_signal");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->event_type_ = ET_CALL;
TestEventProcessor::check_schedule_imm_signal(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_schedule_imm_signal2_spawn)
{
LOG_DEBUG("eventprocessor schedule_imm_signal (spawn)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
test_param[0]->event_type_ = TEST_ET_SPAWN;
TestEventProcessor::check_schedule_imm_signal(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_prepare_schedule_imm1)
{
LOG_DEBUG("eventprocessor prepare_schedule_imm");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->event_type_ = ET_CALL;
TestEventProcessor::check_prepare_schedule_imm(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_prepare_schedule_imm2_spawn)
{
LOG_DEBUG("eventprocessor prepare_schedule_imm (spawn)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
test_param[0]->event_type_ = TEST_ET_SPAWN;
TestEventProcessor::check_prepare_schedule_imm(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_do_schedule1_every)
{
LOG_DEBUG("eventprocessor do_schedule (ET_CALL every)");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
// test_param[0]->func_type_ = TEST_DO_SCHEDULE;
if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) {
LOG_ERROR("fail to alloc mem for do_schedule");
} else {
test_param[0]->event_->callback_event_ = EVENT_INTERVAL;
test_param[0]->aperiod_ = TEST_TIME_SECOND_EVERY;
((ObContInternal *)test_param[0]->cont_)->event_count_ += TEST_DEFAULT_PERIOD_COUNT;
ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_,
get_hrtime_internal() + test_param[0]->aperiod_, test_param[0]->aperiod_));
ASSERT_TRUE(test_param[0]->event_->is_inited_);
test_param[0]->event_type_ = ET_CALL;
test_param[0]->event_->ethread_ = g_event_processor.assign_thread(
test_param[0]->event_type_);
if (NULL != test_param[0]->event_->continuation_->mutex_) {
test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_;
} else {
test_param[0]->event_->continuation_->mutex_ = test_param[0]->event_->ethread_->mutex_;
test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_;
}
TestEventProcessor::check_do_schedule(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
}
};
TEST_F(TestEventProcessor, eventprocessor_do_schedule2_minus_every)
{
LOG_DEBUG("eventprocessor do_schedule (spawn every-)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
ASSERT_TRUE(NULL != test_param[0]->cont_->mutex_);
if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) {
LOG_ERROR("fail to alloc mem for do_schedule");
} else {
test_param[0]->event_->callback_event_ = EVENT_INTERVAL;
test_param[0]->aperiod_ = 0 - TEST_TIME_SECOND_EVERY;
((ObContInternal *)test_param[0]->cont_)->event_count_ += TEST_DEFAULT_PERIOD_COUNT;
ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_,
test_param[0]->aperiod_, test_param[0]->aperiod_));
ASSERT_TRUE(test_param[0]->event_->is_inited_);
test_param[0]->event_type_ = TEST_ET_SPAWN;
test_param[0]->event_->ethread_ = g_event_processor.assign_thread(
test_param[0]->event_type_);
if (NULL != test_param[0]->event_->continuation_->mutex_) {
test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_;
} else {
test_param[0]->event_->continuation_->mutex_ = test_param[0]->event_->ethread_->mutex_;
test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_;
}
set_fast_signal_true(test_param[0]);
((ObContInternal *)(test_param[0]->cont_))->deletable_ = true;
TestEventProcessor::check_do_schedule(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
}
};
TEST_F(TestEventProcessor, eventprocessor_assign_thread)
{
LOG_DEBUG("eventprocessor _assign_thread");
test_param[0] = create_funcparam_test();
TestEventProcessor::check_assign_thread(test_param[0]);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_allocate)
{
LOG_DEBUG("eventprocessor allocate");
test_param[0] = create_funcparam_test();
TestEventProcessor::check_allocate(test_param[0]);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_spawn_thread1_0)
{
LOG_DEBUG("eventprocessor spawn_thread (0)");
test_param[0] = create_funcparam_test(true, handle_schedule_test);
test_param[0]->stacksize_ = 0;
TestEventProcessor::check_spawn_thread(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, eventprocessor_spawn_thread2_default)
{
LOG_DEBUG("eventprocessor spawn_thread (default)");
test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex());
test_param[0]->stacksize_ = DEFAULT_STACKSIZE;
TestEventProcessor::check_spawn_thread(test_param[0]);
wait_condition(test_param[0]->wait_cond_);
ASSERT_TRUE(test_param[0]->test_ok_);
};
TEST_F(TestEventProcessor, processor)
{
LOG_DEBUG("processor");
ObTasksProcessor *task_processor = NULL;
test_param[0] = create_funcparam_test();
if (NULL == (test_param[0]->processor_ = new(std::nothrow) ObProcessor())) {
LOG_ERROR("failed to create ObProcessor");
} else {
ASSERT_TRUE(0 == test_param[0]->processor_->get_thread_count());
ASSERT_TRUE(0 == test_param[0]->processor_->start(0));
test_param[0]->processor_->shutdown();
delete test_param[0]->processor_;
test_param[0]->processor_ = NULL;
}
if (NULL == (task_processor = new(std::nothrow) ObTasksProcessor())) {
LOG_ERROR("failed to create ObTasksProcessor");
} else {
test_param[0]->processor_ = static_cast<ObProcessor *>(task_processor);
ASSERT_TRUE(OB_INVALID_ARGUMENT == task_processor->start(-10));
ASSERT_TRUE(OB_INVALID_ARGUMENT == task_processor->start(0));
ASSERT_TRUE(OB_SUCCESS == task_processor->start(1));
delete task_processor;
test_param[0]->processor_ = NULL;
}
g_event_processor.shutdown();//do nothing
}
} // end of namespace obproxy
} // end of namespace oceanbase
int main(int argc, char **argv)
{
oceanbase::common::ObLogger::get_logger().set_log_level("WARN");
OB_LOGGER.set_log_level("WARN");
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 40.880445 | 115 | 0.683428 | stutiredboy |
cc70e6c4befbc4621a267274e49806a5a78331b1 | 2,690 | cpp | C++ | AlphaEngine/Source/Math/Vector4.cpp | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | AlphaEngine/Source/Math/Vector4.cpp | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | AlphaEngine/Source/Math/Vector4.cpp | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | /**
Copyright 2014-2015 Jason R. Wendlandt
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 "Math/Vector4.h"
namespace alpha
{
Vector4::Vector4()
: x(0.f), y(0.f), z(0.f), w(0.f)
{ }
Vector4::Vector4(float _x, float _y, float _z, float _w)
: x(_x), y(_y), z(_z), w(_w)
{ }
Vector4::Vector4(const Vector3 & vec3, float _w)
: x(vec3.x), y(vec3.y), z(vec3.z), w(_w)
{ }
Vector4::Vector4(const Vector4 &vec)
{
this->x = vec.x;
this->y = vec.y;
this->z = vec.z;
this->w = vec.w;
}
Vector4 & Vector4::operator=(const Vector4 & right)
{
this->x = right.x;
this->y = right.y;
this->z = right.z;
this->w = right.w;
return *this;
}
Vector4 operator+(const Vector4 & left, const Vector4 & right)
{
return Vector4(left.x + right.x,
left.y + right.y,
left.z + right.z,
left.w + right.w);
}
Vector4 operator-(const Vector4 & left, const Vector4 & right)
{
return Vector4(left.x - right.x,
left.y - right.y,
left.z - right.z,
left.w - right.w);
}
Vector4 operator*(const Vector4 & left, const Vector4 & right)
{
return Vector4(left.x * right.x,
left.y * right.y,
left.z * right.z,
left.w * right.w);
}
Vector4 operator*(const Vector4 & left, float right)
{
return Vector4(left.x * right,
left.y * right,
left.z * right,
left.w * right);
}
Vector4 operator/(const Vector4 & left, const Vector4 & right)
{
return Vector4(left.x / right.x,
left.y / right.y,
left.z / right.z,
left.w / right.w);
}
Vector4 operator*(float left, const Vector4 & right)
{
return Vector4(left * right.x,
left * right.y,
left * right.z,
left * right.w);
}
}
| 28.020833 | 72 | 0.51487 | Sh1ft0 |
cc71ca850c8d94a413d3537d9a6677411b073e79 | 471 | hpp | C++ | src/internal/compiler_specifics.hpp | bmknecht/palnatoki | 0522d690f034d9f52730f9666731c3376dd33405 | [
"MIT"
] | null | null | null | src/internal/compiler_specifics.hpp | bmknecht/palnatoki | 0522d690f034d9f52730f9666731c3376dd33405 | [
"MIT"
] | null | null | null | src/internal/compiler_specifics.hpp | bmknecht/palnatoki | 0522d690f034d9f52730f9666731c3376dd33405 | [
"MIT"
] | null | null | null | #ifndef PALNATOKI_COMPILER_SPECIFICS_HPP
#define PALNATOKI_COMPILER_SPECIFICS_HPP
/** This file is part of the Palnatoki optimization library. For licensing
* information refer to the LICENSE file that is included in the project.
*
* This file in particular contains compiler specific defines.
*/
// On my system MINGW fails to define _hypot but needs it in a std-header.
#ifdef __MINGW32__
#define _hypot hypot
#endif
#endif // PALNATOKI_COMPILER_SPECIFICS_HPP
| 29.4375 | 74 | 0.796178 | bmknecht |
cc734a5f8a6328bfefc86ac8a7d925ceee9f70f6 | 4,589 | hpp | C++ | cpp_algs/data_structures/tree/trie.hpp | pskrunner14/cpp-practice | c59928bb9b91204588a0bafdc9f42deaacc64d29 | [
"MIT"
] | 2 | 2018-09-14T14:17:27.000Z | 2020-01-02T00:20:52.000Z | cpp_algs/data_structures/tree/trie.hpp | pskrunner14/cpp-practice | c59928bb9b91204588a0bafdc9f42deaacc64d29 | [
"MIT"
] | 1 | 2018-10-28T19:45:20.000Z | 2018-10-28T19:50:02.000Z | cpp_algs/data_structures/tree/trie.hpp | pskrunner14/cpp-practice | c59928bb9b91204588a0bafdc9f42deaacc64d29 | [
"MIT"
] | 1 | 2019-12-29T19:58:08.000Z | 2019-12-29T19:58:08.000Z | /**
* MIT License
*
* Copyright (c) 2018 Prabhsimran Singh
*
* 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.
*/
#pragma once
/**
* Data Structures - trie
* trie.hpp
* Purpose: Trie interface
*
* @author Prabhsimran Singh
* @version 1.0 27/11/18
*/
#include <iostream>
#include <memory>
#include <queue>
#include <string>
namespace ds {
// ---------------------------------------------- Interface ---------------------------------------------------//
class Trie {
private:
// pointer to root
std::shared_ptr<TrieNode> root;
// recursive remove func.
void remove(std::shared_ptr<TrieNode> const &, const std::string &);
// recursive print func.
void print(std::shared_ptr<TrieNode>, string) const;
public:
// trie default constructor
Trie();
// trie copy constructor
Trie(const Trie &);
// inserts word into trie
void insertWord(const std::string &);
// removes the word from trie if present
void removeWord(const std::string &);
// checks if trie contains the given word
bool containsWord(const std::string &) const;
// prints all the words in the trie
void printWords() const;
};
// -------------------------------------------- Implementation --------------------------------------------------//
Trie::Trie() : root(std::shared_ptr<TrieNode>(new TrieNode('\0'))) {}
Trie::Trie(const Trie &t) {
throw NotImplementedError();
}
void Trie::insertWord(const std::string &str) {
std::shared_ptr<TrieNode> temp = root;
size_t i = 0;
while (i < str.size() && temp->contains(str[i])) {
temp = temp->children[str[i]];
i++;
}
if (i == str.size() && temp->data == str[i - 1]) {
temp->isTerminal = true;
return;
}
for (; i < str.size() - 1; i++) {
std::shared_ptr<TrieNode> child(new TrieNode(str[i]));
temp->children[str[i]] = child;
temp = child;
}
if (i < str.size()) {
std::shared_ptr<TrieNode> child(new TrieNode(str[i], true));
temp->children[str[i]] = child;
}
}
bool Trie::containsWord(const std::string &str) const {
std::shared_ptr<TrieNode> temp = root;
size_t i = 0;
while (i < str.size() && temp->contains(str[i])) {
temp = temp->children[str[i]];
i++;
}
if (i == str.size()) {
if (temp->isTerminal) {
return true;
}
}
return false;
}
void Trie::remove(std::shared_ptr<TrieNode> const &node, const string &str) {
if (str.empty()) {
node->isTerminal = false;
return;
}
if (node->contains(str[0])) {
std::shared_ptr<TrieNode> child = node->children[str[0]];
remove(child, str.substr(1));
if (child->children.empty() && !child->isTerminal) {
node->remove(str[0]);
}
}
}
void Trie::removeWord(const string &str) {
if (root->contains(str[0])) {
std::shared_ptr<TrieNode> child = root->children[str[0]];
// keep root safe
remove(child, str.substr(1));
if (child->children.empty() && !child->isTerminal) {
root->remove(str[0]);
}
}
}
void Trie::print(std::shared_ptr<TrieNode> node, string str) const {
str += node->data;
if (node->isTerminal) {
cout << str << endl;
}
for (const auto &child : node->children) {
print(child.second, str);
}
}
void Trie::printWords() const {
string str = "";
for (const auto &child : root->children) {
print(child.second, str);
}
}
} // namespace ds | 28.68125 | 115 | 0.594247 | pskrunner14 |
cc77f3e8f23ca5abef0546d9387061bf4cd532c0 | 2,160 | cpp | C++ | Engine/src/Components/UI/LayoutComponent.cpp | SpectralCascade/ossium | f9d00de8313c0f91942eb311c20de8d74aa41735 | [
"MIT"
] | 1 | 2019-01-02T15:35:05.000Z | 2019-01-02T15:35:05.000Z | Engine/src/Components/UI/LayoutComponent.cpp | SpectralCascade/ossium | f9d00de8313c0f91942eb311c20de8d74aa41735 | [
"MIT"
] | 2 | 2018-11-11T21:29:05.000Z | 2019-01-02T15:34:10.000Z | Engine/src/Components/UI/LayoutComponent.cpp | SpectralCascade/ossium | f9d00de8313c0f91942eb311c20de8d74aa41735 | [
"MIT"
] | null | null | null | #include "LayoutComponent.h"
#include "LayoutSurface.h"
using namespace std;
namespace Ossium
{
BaseComponent* LayoutComponent::ComponentFactory(void* target_entity)
{
return nullptr;
}
LayoutComponent::LayoutComponent() {}
LayoutComponent::~LayoutComponent() {}
void LayoutComponent::OnCreate() { ParentType::OnCreate(); }
void LayoutComponent::OnDestroy() { ParentType::OnDestroy(); }
void LayoutComponent::OnSetEnabled(bool enable) { ParentType::OnSetEnabled(enable); }
void LayoutComponent::OnLoadStart() { ParentType::OnLoadStart(); }
void LayoutComponent::OnClone(BaseComponent* src) {}
void LayoutComponent::Update(){}
std::string LayoutComponent::GetBaseTypeNames()
{
return std::is_same<BaseComponent, ParentType>::value ?
std::string("") : std::string(parentTypeName) + "," + ParentType::GetBaseTypeNames();
}
Ossium::TypeSystem::TypeFactory<BaseComponent, ComponentType> LayoutComponent::__ecs_factory_ =
std::is_same<ParentType, BaseComponent>::value ? Ossium::TypeSystem::TypeFactory<BaseComponent, ComponentType>(
SID( "LayoutComponent" )::str, ComponentFactory
) :
Ossium::TypeSystem::TypeFactory<BaseComponent, ComponentType>(
SID( "LayoutComponent" )::str, ComponentFactory, std::string(parentTypeName), true
);
void LayoutComponent::OnLoadFinish()
{
layoutSurface = entity->GetComponent<LayoutSurface>();
if (!layoutSurface)
{
layoutSurface = entity->GetAncestor<LayoutSurface>();
if (!layoutSurface)
{
// Automagically add one.
layoutSurface = entity->AddComponent<LayoutSurface>();
}
}
// After loading, make sure the LayoutSurface is marked dirty!
layoutSurface->SetDirty();
}
void LayoutComponent::OnEditorPropertyChanged()
{
// Mark the layout dirty.
layoutSurface->SetDirty();
}
void LayoutComponent::OnSetActive(bool active)
{
if (active && layoutSurface)
{
layoutSurface->SetDirty();
}
}
}
| 33.230769 | 115 | 0.649074 | SpectralCascade |
cc79a10f195b24ee64dee6b05423e5d472e61e41 | 1,790 | hpp | C++ | libember/Headers/ember/glow/GlowSignal.hpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 78 | 2015-07-31T14:46:38.000Z | 2022-03-28T09:28:28.000Z | libember/Headers/ember/glow/GlowSignal.hpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 81 | 2015-08-03T07:58:19.000Z | 2022-02-28T16:21:19.000Z | libember/Headers/ember/glow/GlowSignal.hpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 49 | 2015-08-03T12:53:10.000Z | 2022-03-17T17:25:49.000Z | /*
libember -- C++ 03 implementation of the Ember+ Protocol
Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com).
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __LIBEMBER_GLOW_GLOWSIGNAL_HPP
#define __LIBEMBER_GLOW_GLOWSIGNAL_HPP
#include "GlowContainer.hpp"
namespace libember { namespace glow
{
/**
* GlowSignal is the base class for GlowTarget and GlowSource
*/
class LIBEMBER_API GlowSignal : public GlowContainer
{
public:
/**
* Returns the signal number.
* @return The signal number.
*/
int number() const;
protected:
/**
* Initializes a new instance of GlowSignal
* @param type The type of the instance. Either target or source.
* @param tag The application tag to set
*/
GlowSignal(GlowType const& type, ber::Tag const& tag);
/**
* Initializes a new instance of GlowSignal
* @param type The type of the instance. Either target or source.
* @param number The signal number.
*/
GlowSignal(GlowType const& type, int number);
/**
* Initializes a new instance of GlowSignal
* @param type The type of the instance. Either target or source.
* @param tag The application tag to set
* @param number The signal number.
*/
GlowSignal(GlowType const& type, ber::Tag const& tag, int number);
};
}
}
#ifdef LIBEMBER_HEADER_ONLY
# include "impl/GlowSignal.ipp"
#endif
#endif // __LIBEMBER_GLOW_GLOWSIGNAL_HPP
| 30.338983 | 91 | 0.6 | purefunsolutions |
cc7b8e491205d45097cb667f8eabebbe167534ac | 4,818 | hpp | C++ | source/GcLib/directx/VertexBuffer.hpp | Mugenri/Touhou-Danmakufu-ph3sx-2 | 4ab7e40682341ff41d7467b83bb64c9a669a6064 | [
"MIT"
] | null | null | null | source/GcLib/directx/VertexBuffer.hpp | Mugenri/Touhou-Danmakufu-ph3sx-2 | 4ab7e40682341ff41d7467b83bb64c9a669a6064 | [
"MIT"
] | null | null | null | source/GcLib/directx/VertexBuffer.hpp | Mugenri/Touhou-Danmakufu-ph3sx-2 | 4ab7e40682341ff41d7467b83bb64c9a669a6064 | [
"MIT"
] | null | null | null | #pragma once
#include "../pch.h"
#include "DxConstant.hpp"
namespace directx {
struct BufferLockParameter {
UINT lockOffset = 0U;
DWORD lockFlag = 0U;
void* data = nullptr;
size_t dataCount = 0U;
size_t dataStride = 1U;
BufferLockParameter() {
lockOffset = 0U;
lockFlag = 0U;
data = nullptr;
dataCount = 0U;
dataStride = 1U;
};
BufferLockParameter(DWORD _lockFlag) {
lockOffset = 0U;
lockFlag = _lockFlag;
data = nullptr;
dataCount = 0U;
dataStride = 1U;
};
BufferLockParameter(void* _data, size_t _count, size_t _stride, DWORD _lockFlag) {
lockOffset = 0U;
lockFlag = _lockFlag;
data = 0U;
dataCount = _count;
dataStride = _stride;
};
template<typename T>
void SetSource(T& vecSrc, size_t countMax, size_t _stride) {
data = vecSrc.data();
dataCount = std::min(countMax, vecSrc.size());
dataStride = _stride;
}
};
class VertexBufferManager;
template<typename T>
class BufferBase {
static_assert(std::is_base_of<IDirect3DResource9, T>::value, "T must be a Direct3D resource");
public:
BufferBase();
BufferBase(IDirect3DDevice9* device);
virtual ~BufferBase();
inline void Release() { ptr_release(buffer_); }
HRESULT UpdateBuffer(BufferLockParameter* pLock);
virtual HRESULT Create(DWORD usage, D3DPOOL pool) = 0;
T* GetBuffer() { return buffer_; }
size_t GetSize() { return size_; }
size_t GetSizeInBytes() { return sizeInBytes_; }
protected:
IDirect3DDevice9* pDevice_;
T* buffer_;
size_t size_;
size_t stride_;
size_t sizeInBytes_;
};
class FixedVertexBuffer : public BufferBase<IDirect3DVertexBuffer9> {
public:
FixedVertexBuffer(IDirect3DDevice9* device);
virtual ~FixedVertexBuffer();
virtual void Setup(size_t iniSize, size_t stride, DWORD fvf);
virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT);
private:
DWORD fvf_;
};
class FixedIndexBuffer : public BufferBase<IDirect3DIndexBuffer9> {
public:
FixedIndexBuffer(IDirect3DDevice9* device);
virtual ~FixedIndexBuffer();
virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format);
virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT);
private:
D3DFORMAT format_;
};
template<typename T>
class GrowableBuffer : public BufferBase<T> {
public:
GrowableBuffer(IDirect3DDevice9* device);
virtual ~GrowableBuffer();
virtual HRESULT Create(DWORD usage, D3DPOOL pool) = 0;
virtual void Expand(size_t newSize) = 0;
};
class GrowableVertexBuffer : public GrowableBuffer<IDirect3DVertexBuffer9> {
public:
GrowableVertexBuffer(IDirect3DDevice9* device);
virtual ~GrowableVertexBuffer();
virtual void Setup(size_t iniSize, size_t stride, DWORD fvf);
virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT);
virtual void Expand(size_t newSize);
private:
DWORD fvf_;
};
class GrowableIndexBuffer : public GrowableBuffer<IDirect3DIndexBuffer9> {
public:
GrowableIndexBuffer(IDirect3DDevice9* device);
virtual ~GrowableIndexBuffer();
virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format);
virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT);
virtual void Expand(size_t newSize);
private:
D3DFORMAT format_;
};
class DirectGraphics;
class VertexBufferManager : public DirectGraphicsListener {
static VertexBufferManager* thisBase_;
public:
enum : size_t {
MAX_STRIDE_STATIC = 65536U,
};
VertexBufferManager();
~VertexBufferManager();
static VertexBufferManager* GetBase() { return thisBase_; }
virtual void ReleaseDxResource();
virtual void RestoreDxResource();
virtual bool Initialize(DirectGraphics* graphics);
virtual void Release();
FixedVertexBuffer* GetVertexBufferTLX() { return vertexBuffers_[0]; }
FixedVertexBuffer* GetVertexBufferLX() { return vertexBuffers_[1]; }
FixedVertexBuffer* GetVertexBufferNX() { return vertexBuffers_[2]; }
FixedIndexBuffer* GetIndexBuffer() { return indexBuffer_; }
GrowableVertexBuffer* GetGrowableVertexBuffer() { return vertexBufferGrowable_; }
GrowableIndexBuffer* GetGrowableIndexBuffer() { return indexBufferGrowable_; }
GrowableVertexBuffer* GetInstancingVertexBuffer() { return vertexBuffer_HWInstancing_; }
static void AssertBuffer(HRESULT hr, const std::wstring& bufferID);
private:
/*
* 0 -> TLX
* 1 -> LX
* 2 -> NX
*/
std::vector<FixedVertexBuffer*> vertexBuffers_;
FixedIndexBuffer* indexBuffer_;
GrowableVertexBuffer* vertexBufferGrowable_;
GrowableIndexBuffer* indexBufferGrowable_;
GrowableVertexBuffer* vertexBuffer_HWInstancing_;
virtual void CreateBuffers(IDirect3DDevice9* device);
};
} | 28.011628 | 110 | 0.74616 | Mugenri |
cc7fa0fdb0833c69c92b3315963a928e6b6b5e23 | 4,967 | cpp | C++ | Css343Lab4/Classic.cpp | Whompithian/css343-project4 | b527c4a35126c0be41bf0a2c0d70d1a2d986b164 | [
"MIT"
] | null | null | null | Css343Lab4/Classic.cpp | Whompithian/css343-project4 | b527c4a35126c0be41bf0a2c0d70d1a2d986b164 | [
"MIT"
] | null | null | null | Css343Lab4/Classic.cpp | Whompithian/css343-project4 | b527c4a35126c0be41bf0a2c0d70d1a2d986b164 | [
"MIT"
] | null | null | null | /*
* @file Classic.cpp
* @brief This class represents a classic movie. It is a type of DVD media
* that is categorized, or sorted, by date then famous actor. It also
* allows comparison operations, as well as assignment.
* @author Brendan Sweeney, SID 1161836
* @date March 9, 2012
*/
#include <fstream>
#include <iomanip>
#include <iostream>
#include "Classic.h"
Classic::Classic()
{
KeyedItem tempKey("Item Code");
tempKey.setValue("Classic");
setField(tempKey);
} // end Default Constructor
Classic::Classic(const string& searchKey) : DVDMedia(searchKey)
{
KeyedItem tempKey("Item Code");
tempKey.setValue("Classic");
setField(tempKey);
} // end Constructor
Classic::~Classic()
{
} // end Destructor
bool Classic::updateSearchKey(void)
{
KeyedItem tempKey;
string year, month, majorActor, searchKey = "";
try
{
tempKey.setKey("Year");
getField(tempKey);
year = tempKey.getValue();
tempKey.setKey("Month");
getField(tempKey);
month = tempKey.getValue();
tempKey.setKey("Major Actor");
getField(tempKey);
majorActor = tempKey.getValue();
searchKey += year;
searchKey += " ";
if (month.length() < 2) // single digit month
{
searchKey += "0"; // leading zero for sorting
} // end if (month.length() < 2)
searchKey += month;
searchKey += ", ";
searchKey += majorActor;
setSearchKey(searchKey);
}
catch (TreeException e)
{
cout << "ERROR: Could not update classic movie search string." << endl;
return false;
} // end try
return true;
} // end updateSearchKey()
Merch* Classic::copy(void) const
{
Merch *tempMerch = new Classic();
KeyedItem tempKey("Director");
tempMerch->setStockQty(getStockQty());
tempMerch->setOnHandQty(getOnHandQty());
getField(tempKey);
tempMerch->setField(tempKey);
tempKey.setKey("Title");
getField(tempKey);
tempMerch->setField(tempKey);
tempKey.setKey("Year");
getField(tempKey);
tempMerch->setField(tempKey);
tempKey.setKey("Month");
getField(tempKey);
tempMerch->setField(tempKey);
tempKey.setKey("Major Actor");
getField(tempKey);
tempMerch->setField(tempKey);
tempKey.setKey("Item Code");
tempKey.setValue("Classic");
tempMerch->setField(tempKey);
tempMerch->updateSearchKey();
return tempMerch;
} // end copy()
void Classic::display(void) const
{
KeyedItem tempKey("Title");
getField(tempKey);
cout << left << tempKey.getValue().substr(0, 20);
tempKey.setKey("Director");
getField(tempKey);
cout << left << tempKey.getValue().substr(0, 15);
tempKey.setKey("Year");
getField(tempKey);
cout << right << setw(6) << tempKey.getValue();
tempKey.setKey("Month");
getField(tempKey);
cout << right << setw(3) << tempKey.getValue();
tempKey.setKey("Major Actor");
getField(tempKey);
cout << left << tempKey.getValue().substr(0, 15);
} // end display()
void Classic::displayLine(void) const
{
cout << right << setw(2) << getStockQty() - getOnHandQty();
cout << right << setw(5) << getOnHandQty();
cout << " ";
display();
cout << endl;
} // end displayLine()
DVDMedia* Classic::create(ifstream& infile) const
{
string month, year, actorFirst, actorLast;
KeyedItem tempKey;
Classic *newClassic = new Classic;
infile >> actorFirst >> actorLast; // input star's name
infile >> month >> year; // input month and year;
if (tempKey.setKey("Major Actor"))
{
tempKey.setValue(actorFirst + " " + actorLast);
} // end if (key.setKey("Major Actor"))
newClassic->setField(tempKey);
if (tempKey.setKey("Month"))
{
tempKey.setValue(month);
} // end if (tempKey.setKey("Month"))
newClassic->setField(tempKey);
tempKey.setKey("Year");
tempKey.setValue(year);
newClassic->setField(tempKey);
tempKey.setKey("Item Code");
tempKey.setValue("Classic");
newClassic->setField(tempKey);
return newClassic;
} // end create()
DVDMedia* Classic::create(ifstream& infile, char mediaCode) const
{
string searchKey, textMonth;
int month;
infile >> month;
infile.get();
getline(infile, searchKey);
if (mediaCode == 'D')
{
if (month < 10)
{
textMonth.push_back('0');
textMonth.push_back('0' + month);
}
else
{
textMonth.push_back('1');
textMonth.push_back('0' + month % 10);
} // end if (month < 10)
textMonth.push_back(' ');
searchKey.insert(5, textMonth);
return new Classic(searchKey);
} // end if (mediaCode == 'D')
cerr << mediaCode << " not a recognized media type.";
return NULL;
} // end create()
| 23.21028 | 79 | 0.601369 | Whompithian |
cc808f61475662d3cc8815b2816b27415f5377ea | 2,234 | cpp | C++ | datastructures/binarytrees/largest_nonadj_sum.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 5 | 2021-05-17T12:32:42.000Z | 2021-12-12T21:09:55.000Z | datastructures/binarytrees/largest_nonadj_sum.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | null | null | null | datastructures/binarytrees/largest_nonadj_sum.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 1 | 2021-05-13T20:29:57.000Z | 2021-05-13T20:29:57.000Z | #include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node() = default;
Node(int d) : data(d), left(NULL), right(NULL) {}
~Node() { delete left, delete right, left = right = NULL; }
};
Node* buildTree();
pair<int, int> getLargestDisjointSum(Node *);
int main() {
/**
* In order to find the largest disjoint node sum, we will
* return two things as a pair, the first being the sum if the
* current node is seleceted, other being if not selected
*/
cout << "\nThis program finds out the largest disjoint node in the given tree.\n" << endl;
Node *root;
cout << "Enter space seperated elements of the tree :" << endl;
root = buildTree();
pair<int, int> disjointSum = getLargestDisjointSum(root);
int maxSum = max(disjointSum.first, disjointSum.second);
cout << "\nThe largest disjoint node sum possible here is: " << maxSum << "." << endl;
cout << endl;
delete root;
return 0;
}
Node* buildTree() {
int data;
cin >> data;
// -1 means an end Node aka leaf
if (data == -1) return NULL;
// Recursively build tree
Node *curr = new Node(data);
curr->left = buildTree();
curr->right = buildTree();
return curr;
}
pair<int, int> getLargestDisjointSum(Node *root) {
// Base condition when we reach NULL after leaf
// First pair is value when considering current
// Second pair is when we are not including it
if (!root) return make_pair(0, 0);
// Postorder traversal to acquire values of left & right
pair<int, int> left = getLargestDisjointSum(root->left);
pair<int, int> right = getLargestDisjointSum(root->right);
// When we include current, we cannot select left
// or right child, we must select nodes after them,
// so we access second element of the pair
int includingCurrent = root->data + left.second + right.second;
// If we are not including current, we simply select
// whatever is max including / excluding the left & right nodes
int excludingCurrent = max(left.first, left.second) + max(right.first, right.second);
return make_pair(includingCurrent, excludingCurrent);
} | 30.189189 | 95 | 0.647269 | oishikm12 |
cc85072f23c7cc6c31573bf529aadbee3c0ed4c6 | 1,153 | hpp | C++ | ex00/Cat.hpp | Gundul42/CPP_04 | 61cf8baeb9a9ed931ba423517937e697984c009b | [
"MIT"
] | null | null | null | ex00/Cat.hpp | Gundul42/CPP_04 | 61cf8baeb9a9ed931ba423517937e697984c009b | [
"MIT"
] | null | null | null | ex00/Cat.hpp | Gundul42/CPP_04 | 61cf8baeb9a9ed931ba423517937e697984c009b | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Cat.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: graja <graja@student.42wolfsburg.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/17 16:57:04 by graja #+# #+# */
/* Updated: 2022/02/18 13:36:44 by graja ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CAT_H
# define CAT_H
# include "Animal.hpp"
# include <iostream>
class Cat: public Animal
{
public:
Cat(void);
Cat(const Cat &cpy);
virtual ~Cat(void);
Cat& operator=(const Cat &ovr);
virtual std::string makeSound(void) const;
};
#endif
| 36.03125 | 80 | 0.235039 | Gundul42 |
cc86109edbffb3c2f6b28cbe7f5da7b06f6b2759 | 6,967 | cc | C++ | okl4_kernel/okl4_2.1.1-patch.9/tools/magpie/test/fullsystem/pistachio/kernel/kdb/api/v4/input.cc | CyberQueenMara/baseband-research | e1605537e10c37e161fff1a3416b908c9894f204 | [
"MIT"
] | 77 | 2018-12-31T22:12:09.000Z | 2021-12-31T22:56:13.000Z | okl4_kernel/okl4_2.1.1-patch.9/tools/magpie/test/fullsystem/pistachio/kernel/kdb/api/v4/input.cc | CyberQueenMara/baseband-research | e1605537e10c37e161fff1a3416b908c9894f204 | [
"MIT"
] | null | null | null | okl4_kernel/okl4_2.1.1-patch.9/tools/magpie/test/fullsystem/pistachio/kernel/kdb/api/v4/input.cc | CyberQueenMara/baseband-research | e1605537e10c37e161fff1a3416b908c9894f204 | [
"MIT"
] | 24 | 2019-01-20T15:51:52.000Z | 2021-12-25T18:29:13.000Z | /*********************************************************************
*
* Copyright (C) 2002-2004, 2006, Karlsruhe University
*
* File path: kdb/api/v4/input.cc
* Description: Version 4 specific input functions
*
* 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 AUTHOR 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 AUTHOR 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.
*
* $Id: input.cc,v 1.5.4.6 2006/12/05 16:10:15 skoglund Exp $
*
********************************************************************/
#include <debug.h>
#include <kdb/input.h>
#include <kdb/kdb.h>
#include <kdb/console.h>
#include INC_API(space.h)
#include INC_API(tcb.h)
/**
* Prompt for an address space using PROMPT and return the space
* pointer. Input value can be a TCB address or a physical or virtual
* space pointer.
* @param prompt prompt
*
* @return pointer to space
*/
space_t SECTION(SEC_KDEBUG) * get_space (const char * prompt)
{
space_t * dummy = kdb.kdb_current->get_space ();
space_t * space;
addr_t val;
if (!dummy)
dummy = get_kernel_space ();
val = (addr_t) get_hex (prompt, (word_t) dummy,
"current");
tcb_t * tidtcb = dummy->get_tcb (threadid ((word_t) val));
if (dummy->is_tcb_area (val))
{
// Pointer into the TCB area
tcb_t * tcb = addr_to_tcb (val);
space = tcb->get_space ();
}
else if (tidtcb->myself_global == threadid ((word_t) val))
{
// A valid thread ID
space = tidtcb->get_space ();
}
else if (dummy->is_user_area (val))
{
// Pointer in lower memory area. Probably a physical address.
val = phys_to_virt (val);
space = (space_t *) val;
}
else
{
// Hopefuly a valid space pointer
space = (space_t *) val;
}
return space;
}
static char * thread_names[] = {
"nil_thrd", "irq_", "idlethrd", "sigma0", "sigma1", "roottask", 0
};
static inline char lowercase (char c)
{
return c >= 'A' && c <= 'Z' ? c + 'a' - 'A' : c;
}
static inline int thread_match (const char * str)
{
for (word_t i = 0; thread_names[i] != 0; i++)
{
for (word_t j = 0; thread_names[i][j] == str[j]; j++)
if (str[j] == 0)
return i+1;
}
return 0;
}
/**
* Prompt for a thread using PROMPT and return the tcb pointer. Input
* value can be a TCB address or a thread id.
*
* @param prompt prompt
*
* @return pointer to tcb
*/
tcb_t SECTION (SEC_KDEBUG) * get_thread (const char * prompt)
{
space_t * dummy = kdb.kdb_current->get_space ();
const word_t nsize = sizeof (word_t) * 2;
printf ("%s [current]: ", prompt ? prompt : "Thread");
word_t val = 0;
word_t num = 0;
word_t len = 0;
word_t version_char = 0;
bool break_loop = false;
char c, r;
while (! break_loop &&
(len < nsize || version_char != 0))
{
switch (r = c = getc ())
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
num *= 16;
num += c - '0';
putc (r);
len++;
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
c += 'a' - 'A';
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
num *= 16;
num += c - 'a' + 10;
putc (r);
len++;
break;
case 'x': case 'X':
// Allow "0x" prefix
if (len == 1 && num == 0)
{
putc (r);
len--;
}
break;
case 'v': case 'V':
if (len == 0)
break;
putc (r);
val = num << L4_GLOBAL_VERSION_BITS;
num = 0;
version_char = len++;
break;
case 'S': case 'N': case 'R': case 'I':
case 's': case 'n': case 'r': case 'i':
if (len == 0)
{
// Trying to type in name of thread.
char buf[9];
int i = 0;
putc (r);
buf[i++] = lowercase (r);
buf[i] = 0;
while (! thread_match (buf) && r != KEY_RETURN)
{
switch (r = getc ())
{
case '\b':
printf ("\b \b");
buf[i--] = 0;
break;
case '\e':
printf ("\n");
return (tcb_t *) NULL;
case KEY_RETURN:
break;
default:
if (i == 8)
break;
putc (r);
buf[i++] = lowercase (r);
buf[i] = 0;
break;
}
}
// Check which thread name the user gave
word_t ubase = get_kip ()->thread_info.get_user_base ();
break_loop = true;
switch (thread_match (buf))
{
case 1: // Nilthrad
val = threadid_t::nilthread ().get_raw ();
break;
case 2: // IRQ thread
val = threadid_t::irqthread (get_dec ()).get_raw ();
break;
case 3: // Idle thread
val = (word_t) get_idle_tcb ();
break;
case 4: // Sigma0
val = threadid_t::threadid (ubase, 1).get_raw ();
break;
case 5: // Sigma1
val = threadid_t::threadid (ubase + 1, 1).get_raw ();
break;
case 6: // Roottask
val = threadid_t::threadid (ubase + 2, 1).get_raw ();
break;
default: // (invalid)
while (i-- > 0)
printf ("\b \b");
break_loop = false;
break;
}
break;
}
// Not typing string. Fallthrough.
case '\b':
// Backspace
if (len > 0)
{
printf ("\b \b");
num /= 16;
len--;
if (len == version_char)
{
version_char = 0;
num = val >> L4_GLOBAL_VERSION_BITS;
}
}
break;
case KEY_RETURN:
if (len == 0)
{
// Use default value
printf ("current");
val = (word_t) kdb.kdb_current;
}
else
{
len = 0;
if (version_char != 0)
val |= num & ((1UL << L4_GLOBAL_VERSION_BITS) - 1);
else
val = num;
}
break_loop = true;
break;
}
}
if (len == nsize)
val = num;
printf ("\n");
if (dummy->is_tcb_area ((addr_t) val) ||
(addr_t) val == (addr_t) get_idle_tcb())
return addr_to_tcb ((addr_t) val);
else
return dummy->get_tcb (threadid (val));
}
| 23.379195 | 77 | 0.56782 | CyberQueenMara |
cc870d8419fa4828708cf513941a4e2d2b0f6a29 | 4,627 | cpp | C++ | tests/bm_heterogeneous_count_ptr.cpp | mpusz/unordered_v2 | a3ab5a08b335b15fc60454ecc0c1d2199d01a5a1 | [
"MIT"
] | 5 | 2018-04-08T17:03:16.000Z | 2019-06-01T19:12:47.000Z | tests/bm_heterogeneous_count_ptr.cpp | mpusz/unordered_v2 | a3ab5a08b335b15fc60454ecc0c1d2199d01a5a1 | [
"MIT"
] | null | null | null | tests/bm_heterogeneous_count_ptr.cpp | mpusz/unordered_v2 | a3ab5a08b335b15fc60454ecc0c1d2199d01a5a1 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2017 Mateusz Pusz
//
// 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 "unordered_map"
#include "unordered_set"
#include <benchmark/benchmark.h>
#include <array>
#include <memory>
#include <random>
#include <vector>
namespace {
struct my_data {
size_t i;
std::array<char, 256> data;
explicit my_data(size_t i_) : i{i_} { std::iota(begin(data), end(data), 0); }
};
struct my_data_equal {
using is_transparent = void;
bool operator()(const std::unique_ptr<my_data>& l, const std::unique_ptr<my_data>& r) const { return l == r; }
bool operator()(const std::unique_ptr<my_data>& l, my_data* ptr) const { return l.get() == ptr; }
bool operator()(my_data* ptr, const std::unique_ptr<my_data>& r) const { return ptr == r.get(); }
};
struct my_data_hash {
using transparent_key_equal = my_data_equal; // KeyEqual to use
size_t operator()(const std::unique_ptr<my_data>& v) const { return std::hash<const my_data*>{}(v.get()); }
size_t operator()(const my_data* ptr) const { return std::hash<const my_data*>{}(ptr); }
};
// based on https://stackoverflow.com/a/17853770
class opt_out_deleter {
bool delete_;
public:
explicit opt_out_deleter(bool do_delete = true) : delete_{do_delete} {}
template<typename T>
void operator()(T* p) const
{
if(delete_) delete p;
}
};
template<typename T>
using set_unique_ptr = std::unique_ptr<T, opt_out_deleter>;
template<typename T>
set_unique_ptr<T> make_find_ptr(T* raw)
{
return set_unique_ptr<T>{raw, opt_out_deleter{false}};
}
constexpr size_t item_count = 4096;
struct test_data {
std::vector<std::unique_ptr<my_data>> storage;
std::vector<my_data*> test_sequence;
};
test_data make_test_data()
{
test_data data;
data.storage.reserve(item_count);
data.test_sequence.reserve(item_count);
for(size_t i = 0; i < item_count; ++i) {
data.storage.push_back(std::make_unique<my_data>(i));
data.test_sequence.push_back(data.storage.back().get());
}
std::mt19937 g;
std::shuffle(begin(data.test_sequence), end(data.test_sequence), g);
return data;
}
using regular_set = std::unordered_set<set_unique_ptr<my_data>>;
using regular_map = std::unordered_map<my_data*, std::unique_ptr<my_data>>;
using heterogeneous_set = std::unordered_set<std::unique_ptr<my_data>, my_data_hash>;
void bm_heterogeneous_set_count_ptr_regular(benchmark::State& state)
{
auto data = make_test_data();
regular_set set;
for(auto& ptr : data.storage) set.emplace(ptr.release());
for(auto _ : state)
for(auto ptr : data.test_sequence) benchmark::DoNotOptimize(set.count(make_find_ptr(ptr)));
}
void bm_heterogeneous_map_count_ptr_regular(benchmark::State& state)
{
auto data = make_test_data();
regular_map map;
for(auto& ptr : data.storage) {
auto p = ptr.release();
map.emplace(p, p);
}
for(auto _ : state)
for(auto ptr : data.test_sequence) benchmark::DoNotOptimize(map.count(ptr));
}
void bm_heterogeneous_set_count_ptr_heterogeneous(benchmark::State& state)
{
auto data = make_test_data();
heterogeneous_set set;
for(auto& ptr : data.storage) set.emplace(std::move(ptr));
for(auto _ : state)
for(auto ptr : data.test_sequence) benchmark::DoNotOptimize(set.count(ptr));
}
BENCHMARK(bm_heterogeneous_set_count_ptr_regular);
BENCHMARK(bm_heterogeneous_map_count_ptr_regular);
BENCHMARK(bm_heterogeneous_set_count_ptr_heterogeneous);
} // namespace
| 33.773723 | 114 | 0.707154 | mpusz |
cc8a5816aeb17ade6844422e5df3784f6a38df3b | 1,887 | cpp | C++ | tests/board_test.cpp | JAOP1/GO | 48c0275fd37bb552c0db4b968391a5a95ed6c860 | [
"MIT"
] | null | null | null | tests/board_test.cpp | JAOP1/GO | 48c0275fd37bb552c0db4b968391a5a95ed6c860 | [
"MIT"
] | null | null | null | tests/board_test.cpp | JAOP1/GO | 48c0275fd37bb552c0db4b968391a5a95ed6c860 | [
"MIT"
] | 2 | 2019-12-12T18:55:35.000Z | 2019-12-12T19:03:35.000Z | #include "../Include/BoardGame.hpp"
#include <gtest/gtest.h>
#include <iostream>
TEST(Board_Test, Creation)
{
Graph G = graphs::Grid(4, 4);
BoardGame Go(G, 0.5);
std::vector<char> initial_state(25, 'N');
ASSERT_EQ(Go.show_current_state(), initial_state);
}
TEST(Board_Test, Valid_action)
{
Graph G = graphs::Grid(3, 3); // Grid size is 4 x 4.
BoardGame Go(G, 0.5);
std::vector<char> state(16, 'N');
state[1] = 'B';
state[4] = 'B';
state[5] = 'W';
Go.make_action(1); // Black has done an action in node 1.
Go.make_action(-1); // White pass.
Go.make_action(4); // Black has done an action in node 4.
Go.make_action(5); // White.
auto v = Go.get_current_node_state(0);
auto v1 = Go.get_current_node_state(1);
auto v2 = Go.get_current_node_state(4);
ASSERT_EQ(Go.show_current_state(), state);
ASSERT_EQ(Go.player_status(), 'B');
ASSERT_EQ(v.type, 'N');
ASSERT_EQ(v1.type, 'B');
ASSERT_EQ(v2.type, 'B');
ASSERT_EQ(v1.libertiesNodes.size(), 2);
ASSERT_EQ(v2.libertiesNodes.size(), 2);
ASSERT_EQ(v.libertiesNodes.size(), 0);
ASSERT_TRUE(Go.is_valid_move(0));
ASSERT_TRUE(Go.is_valid_move(2));
ASSERT_TRUE(!Go.is_valid_move(5));
}
TEST(Board_Test, Eliminate)
{
Graph G = graphs::Complete(3);
BoardGame Go(G);
Go.make_action(1);
Go.make_action(2);
std::vector<char> state(3, 'N');
state[1] = 'B';
state[2] = 'W';
ASSERT_EQ(Go.show_current_state(), state);
state[2] = 'N';
state[0] = 'B';
Go.make_action(0);
ASSERT_EQ(Go.show_current_state(), state);
}
TEST(Board_Test, reward)
{
Graph G = graphs::Grid(2, 2);
BoardGame Go(G);
Go.make_action(4);
Go.make_action(-1);
Go.make_action(3);
Go.make_action(-1);
Go.make_action(1);
ASSERT_EQ(Go.reward('B'), 1);
ASSERT_EQ(Go.reward('W'), -1);
} | 23.886076 | 61 | 0.615262 | JAOP1 |
cc8c6ce05dd60ee0584e8e40f3aa68c2e377f35d | 356 | cpp | C++ | spriterengine/objectinfo/tagobjectinfo.cpp | Squalr/SpriterPlusPlus | ad728307b1d31238c6164b7b42936e6212e77a9e | [
"Zlib"
] | 92 | 2015-11-03T08:46:58.000Z | 2021-03-12T22:36:45.000Z | spriterengine/objectinfo/tagobjectinfo.cpp | Squalr/SpriterPlusPlus | ad728307b1d31238c6164b7b42936e6212e77a9e | [
"Zlib"
] | 15 | 2015-11-04T12:16:36.000Z | 2019-09-03T17:13:16.000Z | spriterengine/objectinfo/tagobjectinfo.cpp | Squalr/SpriterPlusPlus | ad728307b1d31238c6164b7b42936e6212e77a9e | [
"Zlib"
] | 53 | 2015-11-04T12:25:50.000Z | 2021-04-30T06:14:37.000Z | #include "tagobjectinfo.h"
namespace SpriterEngine
{
TagObjectInfo::TagObjectInfo()
{
}
void TagObjectInfo::setObjectToLinear(UniversalObjectInterface *bObject, real t, UniversalObjectInterface *resultObject)
{
resultObject->setTagList(&tagList);
}
void TagObjectInfo::pushBackTag(const std::string * tag)
{
tagList.pushBackTag(tag);
}
}
| 16.952381 | 121 | 0.758427 | Squalr |
cc8e38dd536004284e8293e73b86b9c6766c613e | 2,090 | cpp | C++ | TurboX-Engine/TurboX-Engine/W_Hierarchy.cpp | moon-funding/TurboX-Engine | 0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2020-10-08T03:21:06.000Z | 2022-01-19T14:50:01.000Z | TurboX-Engine/TurboX-Engine/W_Hierarchy.cpp | moon-funding/TurboX-Engine | 0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 11 | 2021-01-09T09:40:54.000Z | 2021-12-01T22:28:35.000Z | TurboX-Engine/TurboX-Engine/W_Hierarchy.cpp | moon-funding/TurboX-Engine | 0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6 | [
"MIT",
"Zlib",
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2020-12-15T00:36:33.000Z | 2021-01-05T08:28:17.000Z | #include "W_Hierarchy.h"
#include "ModuleScene.h"
#include "Application.h"
W_Hierarchy::W_Hierarchy()
{
open_pop_up = false;
}
W_Hierarchy::~W_Hierarchy()
{
}
void W_Hierarchy::Draw()
{
ImGui::Begin("Hierarchy");
ImGuiTreeNodeFlags default_flags = ImGuiTreeNodeFlags_NoTreePushOnOpen;
DrawGameObject(App->scene->GetRoot(), default_flags, App->scene->GetRoot());
ImGui::End();
}
void W_Hierarchy::DrawGameObject(GameObject* gameObject, ImGuiTreeNodeFlags default_flags, GameObject* root)
{
bool drawAgain = true;
ImGuiTreeNodeFlags flags = default_flags;
if (gameObject->childs.empty()) {
flags |= ImGuiTreeNodeFlags_Leaf;
}
if (gameObject->is_selected)
{
flags |= ImGuiTreeNodeFlags_Selected;
}
if (gameObject != root)
drawAgain = ImGui::TreeNodeEx(gameObject, flags, gameObject->name.c_str());
else
drawAgain = true;
if (ImGui::IsItemClicked(0))
{
App->scene->selectGameObject(gameObject);
}
if (ImGui::BeginPopupContextItem((gameObject->name + "rightClick").c_str(), 1))
{
if (ImGui::Button("Delete"))
{
gameObject->to_delete = true;
}
ImGui::EndPopup();
}
if (App->scene->selected_GO != nullptr)
{
if (App->scene->selected_GO->to_delete == true)
{
App->scene->DestroyGameObject(gameObject);
}
}
if (ImGui::BeginDragDropSource())
{
uint gameObject_UUID = gameObject->GetUUID();
ImGui::SetDragDropPayload("Reparenting", &gameObject_UUID, sizeof(uint));
ImGui::Text(gameObject->name.c_str());
ImGui::EndDragDropSource();
}
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Reparenting", ImGuiDragDropFlags_SourceAllowNullID))
{
GameObject* draggedGameobject = App->scene->GetGameObjectByUUID(*(uint*)payload->Data);
if (draggedGameobject != nullptr)
draggedGameobject->SetParent(gameObject);
}
ImGui::EndDragDropTarget();
}
if (drawAgain)
{
for (uint i = 0; i < gameObject->childs.size(); i++)
{
DrawGameObject(gameObject->childs[i], flags, root);
}
}
}
void W_Hierarchy::SetShowWindow()
{
showWindow = !showWindow;
} | 21.111111 | 118 | 0.705263 | moon-funding |
cc8f1137e28203976c0898359fa68819376026d1 | 693 | hpp | C++ | src/include/data/lpc_encoded_data.hpp | sahaRatul/SELA | ca09cbd80bd6084bca08288d980c7f6928571bbb | [
"MIT"
] | 241 | 2015-07-23T16:24:01.000Z | 2022-01-25T11:16:30.000Z | src/include/data/lpc_encoded_data.hpp | sahaRatul/lpc | ca09cbd80bd6084bca08288d980c7f6928571bbb | [
"MIT"
] | 23 | 2015-07-24T05:50:06.000Z | 2021-09-20T07:41:50.000Z | src/include/data/lpc_encoded_data.hpp | sahaRatul/lpc | ca09cbd80bd6084bca08288d980c7f6928571bbb | [
"MIT"
] | 29 | 2015-07-23T15:39:36.000Z | 2022-01-29T09:50:23.000Z | #ifndef _LPC_ENCODED_DATA_H_
#define _LPC_ENCODED_DATA_H_
#include <cstdint>
#include <vector>
namespace data {
class LpcEncodedData {
public:
uint8_t optimalLpcOrder;
uint8_t bitsPerSample;
const std::vector<int32_t> quantizedReflectionCoefficients;
const std::vector<int32_t> residues;
LpcEncodedData(uint8_t optimalLpcOrder, uint8_t bitsPerSample, const std::vector<int32_t>&& quantizedReflectionCoefficients, const std::vector<int32_t>&& residues) noexcept
: optimalLpcOrder(optimalLpcOrder)
, bitsPerSample(bitsPerSample)
, quantizedReflectionCoefficients(quantizedReflectionCoefficients)
, residues(residues)
{
}
};
}
#endif | 28.875 | 176 | 0.756133 | sahaRatul |
cc99208330900c78abe94288f0dbb1b7e162dad0 | 2,623 | hpp | C++ | shared/sdk/regenny/re7/via/clr/VM.hpp | fengjixuchui/REFramework | 131b25ef58064b1c36cdd15072c30f5fbd9a7ad8 | [
"MIT"
] | 583 | 2021-06-05T06:56:54.000Z | 2022-03-31T19:16:09.000Z | src/sdk/regenny/re7/via/clr/VM.hpp | drowhunter/REFramework | 49ef476d13439110cc0ae565cc323cd615d9b327 | [
"MIT"
] | 198 | 2021-07-13T02:54:19.000Z | 2022-03-29T20:28:53.000Z | src/sdk/regenny/re7/via/clr/VM.hpp | drowhunter/REFramework | 49ef476d13439110cc0ae565cc323cd615d9b327 | [
"MIT"
] | 73 | 2021-07-12T18:52:12.000Z | 2022-03-31T17:12:56.000Z | #pragma once
namespace regenny::System {
struct Type;
}
namespace regenny::tdb49 {
struct TypeDefinition;
}
namespace regenny::via::typeinfo {
struct TypeInfo;
}
namespace regenny::tdb49 {
struct TDB;
}
namespace regenny::tdb49 {
struct FieldDefinition;
}
namespace regenny::tdb49 {
struct MethodDefinition;
}
namespace regenny {
struct BullShit;
}
namespace regenny::via::clr {
#pragma pack(push, 1)
struct VM {
struct Method;
struct Field;
struct Type {
regenny::tdb49::TypeDefinition* tdb_type; // 0x0
uint32_t type_flags; // 0x8
uint32_t fieldptr_offset; // 0xc
char pad_10[0x10];
regenny::via::clr::VM::Type* parent; // 0x20
regenny::via::clr::VM::Type* next; // 0x28
char pad_30[0x8];
regenny::System::Type* runtime_type; // 0x38
regenny::via::clr::VM::Method** methods; // 0x40
regenny::via::clr::VM::Field** fields; // 0x48
void* static_fields; // 0x50
char pad_58[0x8];
regenny::via::typeinfo::TypeInfo* reflection_type; // 0x60
void** vtable; // 0x68
}; // Size: 0x70
struct Module {
void** vtable; // 0x0
// Metadata: utf8*
char* name; // 0x8
char pad_10[0x20];
}; // Size: 0x30
struct FullModule {
char pad_0[0x8];
uint32_t unk1; // 0x8
uint32_t unk2; // 0xc
regenny::via::clr::VM::Module module; // 0x10
}; // Size: 0x40
struct ModuleContainer {
regenny::via::clr::VM::Module* module; // 0x0
regenny::via::clr::VM::FullModule* full_module; // 0x8
}; // Size: 0x10
struct ModuleArray {
regenny::via::clr::VM::ModuleContainer* modules; // 0x0
uint32_t num; // 0x8
uint32_t num_allocated; // 0xc
}; // Size: 0x10
struct Method {
regenny::tdb49::MethodDefinition* tdb_method; // 0x0
char pad_8[0x8];
void* function; // 0x10
char pad_18[0x8];
}; // Size: 0x20
struct Field {
regenny::tdb49::FieldDefinition* tdb_field; // 0x0
uint32_t unk; // 0x8
uint32_t offset; // 0xc
regenny::via::clr::VM::Type* type; // 0x10
}; // Size: 0x18
char pad_0[0x110];
ModuleArray modules; // 0x110
char pad_120[0x3920];
Type* types; // 0x3a40
uint32_t num_types; // 0x3a48
char pad_3a4c[0x4];
Method* methods; // 0x3a50
uint32_t num_methods; // 0x3a58
char pad_3a5c[0x6c];
regenny::tdb49::TDB* tdb; // 0x3ac8
char pad_3ad0[0x28];
regenny::BullShit** asdf; // 0x3af8
char pad_3b00[0xc500];
}; // Size: 0x10000
#pragma pack(pop)
}
| 25.970297 | 66 | 0.598551 | fengjixuchui |
cc9c4fbdb45d79d0fd9d176302543bd38330349a | 875 | cpp | C++ | Linked List/stackImplementionLinkedList.cpp | harshallgarg/Diversified-Programming | 7e6fb135c4639dbaa0651b85f98397f994a5b11d | [
"MIT"
] | 2 | 2020-08-09T02:09:50.000Z | 2020-08-09T07:07:47.000Z | Linked List/stackImplementionLinkedList.cpp | harshallgarg/Diversified-Programming | 7e6fb135c4639dbaa0651b85f98397f994a5b11d | [
"MIT"
] | null | null | null | Linked List/stackImplementionLinkedList.cpp | harshallgarg/Diversified-Programming | 7e6fb135c4639dbaa0651b85f98397f994a5b11d | [
"MIT"
] | 5 | 2020-09-21T12:49:07.000Z | 2020-09-29T16:13:09.000Z | //
// stackImplementionLinkedList.cpp
// C++
//
// Created by Anish Mookherjee on 31/03/20.
// Copyright © 2020 Anish Mookherjee. All rights reserved.
//
#include <iostream>
using namespace std;
struct StackNode
{
int data;
StackNode *next;
StackNode(int a)
{
data = a;
next = NULL;
}
};
class MyStack {
private:
StackNode *top;
public :
void push(int);
int pop();
MyStack()
{
top = NULL;
}
};
void MyStack ::push(int x) {
StackNode *newNode=(struct StackNode*)malloc(sizeof(struct StackNode));
newNode->data=x;
if(top==NULL)
{
top=newNode;
}
else
{
newNode->next=top;
top=newNode;
}
}
int MyStack ::pop() {
if(top==NULL)
return -1;
StackNode *temp;
temp=top;
top=top->next;
temp->next=NULL;
return temp->data;
}
| 14.830508 | 75 | 0.56 | harshallgarg |
cc9d4c05139e6626c27df4354e9a42179b77abaa | 884 | cpp | C++ | HDUOJ/6324/observation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | HDUOJ/6324/observation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | HDUOJ/6324/observation.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <iterator>
using namespace std;
#define SIZE 100010
int arr[SIZE];
int main()
{
int caseNum;
scanf("%d", &caseNum);
while (caseNum--)
{
int num;
scanf("%d", &num);
int xorSum = 0;
for (int i = 0; i < num; i++)
{
scanf("%d", arr + i);
xorSum ^= arr[i];
}
for (int i = 0; i < num - 1; i++)
{
int from, to;
scanf("%d%d", &from, &to);
}
if (xorSum == 0)
{
puts("D");
}
else
{
puts("Q");
}
}
return 0;
} | 16.37037 | 41 | 0.46267 | codgician |
cca299c64288ae42223e36c1a26c99d8b4c9b402 | 1,095 | cpp | C++ | src/lib/helium_us915_netjoin.cpp | olicooper/arduino-lorawan | caceeb49b1f5520d11668aeb7c587ef1a96ca9ad | [
"MIT"
] | 198 | 2016-11-04T13:49:53.000Z | 2022-03-30T13:25:51.000Z | src/lib/helium_us915_netjoin.cpp | olicooper/arduino-lorawan | caceeb49b1f5520d11668aeb7c587ef1a96ca9ad | [
"MIT"
] | 134 | 2017-03-02T05:25:20.000Z | 2022-03-31T19:26:33.000Z | src/lib/helium_us915_netjoin.cpp | olicooper/arduino-lorawan | caceeb49b1f5520d11668aeb7c587ef1a96ca9ad | [
"MIT"
] | 51 | 2017-11-16T15:14:38.000Z | 2022-03-09T09:41:43.000Z | /*
Module: helium_us915_netjoin.cpp
Function:
Arduino_LoRaWAN_Helium_us915::NetBeginRegionInit()
Copyright notice:
See LICENSE file accompanying this project.
Author:
Terry Moore, MCCI Corporation February 2020
*/
#include <Arduino_LoRaWAN_Helium.h>
#include <Arduino_LoRaWAN_lmic.h>
/****************************************************************************\
|
| Manifest constants & typedefs.
|
\****************************************************************************/
/****************************************************************************\
|
| Read-only data.
|
\****************************************************************************/
/****************************************************************************\
|
| Variables.
|
\****************************************************************************/
#if defined(CFG_us915)
void Arduino_LoRaWAN_Helium_us915::NetJoin()
{
// do the common work.
this->Super::NetJoin();
// Helium is bog standard, and our DNW2 value is already right.
}
#endif // defined(CFG_us915)
| 21.9 | 78 | 0.400913 | olicooper |
cca39a7cb53ac0ae1c18f46c4f89f85cb5920f12 | 4,123 | cpp | C++ | src/Mesh.cpp | arpg/torch | 601ec64854008d97e39d2ca86ef4a93f79930967 | [
"Apache-2.0"
] | 1 | 2018-05-29T03:08:54.000Z | 2018-05-29T03:08:54.000Z | src/Mesh.cpp | arpg/torch | 601ec64854008d97e39d2ca86ef4a93f79930967 | [
"Apache-2.0"
] | null | null | null | src/Mesh.cpp | arpg/torch | 601ec64854008d97e39d2ca86ef4a93f79930967 | [
"Apache-2.0"
] | 1 | 2017-07-24T11:58:52.000Z | 2017-07-24T11:58:52.000Z | #include <torch/Mesh.h>
#include <torch/Context.h>
#include <torch/Point.h>
#include <torch/Normal.h>
namespace torch
{
Mesh::Mesh(std::shared_ptr<Context> context) :
SingleGeometry(context, "Mesh")
{
Initialize();
}
Mesh::~Mesh()
{
}
size_t Mesh::GetVertexCount() const
{
return m_vertices.size();
}
void Mesh::GetVertices(std::vector<Point>& vertices) const
{
vertices = m_vertices;
}
void Mesh::SetVertices(const std::vector<Point>& vertices)
{
UpdateBounds(vertices);
m_vertices = vertices;
CopyTo(m_vertexBuffer, vertices);
}
void Mesh::GetNormals(std::vector<Normal>& normals) const
{
normals = m_normals;
}
void Mesh::SetNormals(const std::vector<Normal>& normals)
{
m_normals = normals;
CopyTo(m_normalBuffer, normals);
}
void Mesh::GetFaces(std::vector<uint3>& faces) const
{
faces = m_faces;
}
void Mesh::SetFaces(const std::vector<uint3>& faces)
{
m_faces = faces;
m_geometry->setPrimitiveCount(faces.size());
CopyTo(m_faceBuffer, faces);
}
optix::Buffer Mesh::GetVertexBuffer() const
{
return m_vertexBuffer;
}
optix::Buffer Mesh::GetNormalBuffer() const
{
return m_normalBuffer;
}
optix::Buffer Mesh::GetFaceBuffer() const
{
return m_faceBuffer;
}
void Mesh::GetVertexAdjacencyMap(std::vector<uint>& map,
std::vector<uint>& offsets, bool includeSelf) const
{
std::vector<std::vector<uint>> map2D;
GetVertexAdjacencyMap(map2D, includeSelf);
offsets.resize(map2D.size() + 1);
offsets[0] = 0;
for (size_t i = 0; i < map2D.size(); ++i)
{
const std::vector<uint>& row = map2D[i];
offsets[i + 1] = row.size() + offsets[i];
}
map.resize(offsets.back());
for (size_t i = 0; i < map2D.size(); ++i)
{
const std::vector<uint>& row = map2D[i];
std::copy(row.begin(), row.end(), &map[offsets[i]]);
}
}
void Mesh::GetVertexAdjacencyMap(std::vector<std::vector<uint>>& map,
bool includeSelf) const
{
map.resize(m_vertices.size());
for (const uint3& face : m_faces)
{
AddAdjacencies(map, face, 0, includeSelf);
AddAdjacencies(map, face, 1, includeSelf);
AddAdjacencies(map, face, 2, includeSelf);
}
}
BoundingBox Mesh::GetBounds(const Transform& transform)
{
return transform * m_transform * m_bounds;
}
void Mesh::AddAdjacencies(std::vector<std::vector<uint>>& map,
const uint3& face, uint index, bool includeSelf)
{
const uint child1 = (index + 1) % 3;
const uint child2 = (index + 2) % 3;
const uint* array = reinterpret_cast<const uint*>(&face);
AddAdjacencies(map[array[index]], array[index], array[child1]);
AddAdjacencies(map[array[index]], array[index], array[child2]);
if (includeSelf)
{
AddAdjacencies(map[array[index]], array[index], array[index]);
}
}
void Mesh::AddAdjacencies(std::vector<uint>& map, uint parent, uint child)
{
auto iter = std::find(map.begin(), map.end(), child);
if (iter == map.end()) map.push_back(child);
}
void Mesh::UpdateBounds(const std::vector<Point>& vertices)
{
m_bounds = BoundingBox();
for (const Point& vertex : vertices)
{
m_bounds.Union(vertex.x, vertex.y, vertex.z);
}
}
template<typename T>
void Mesh::CopyTo(optix::Buffer buffer, const std::vector<T>& data)
{
buffer->setSize(data.size());
T* device = reinterpret_cast<T*>(buffer->map());
std::copy(data.begin(), data.end(), device);
buffer->unmap();
}
void Mesh::Initialize()
{
CreateVertexBuffer();
CreateNormalBuffer();
CreateFaceBuffer();
}
void Mesh::CreateVertexBuffer()
{
m_vertexBuffer = m_context->CreateBuffer(RT_BUFFER_INPUT);
m_geometry["vertices"]->setBuffer(m_vertexBuffer);
m_vertexBuffer->setFormat(RT_FORMAT_FLOAT3);
m_vertexBuffer->setSize(0);
}
void Mesh::CreateNormalBuffer()
{
m_normalBuffer = m_context->CreateBuffer(RT_BUFFER_INPUT);
m_geometry["normals"]->setBuffer(m_normalBuffer);
m_normalBuffer->setFormat(RT_FORMAT_FLOAT3);
m_normalBuffer->setSize(0);
}
void Mesh::CreateFaceBuffer()
{
m_faceBuffer = m_context->CreateBuffer(RT_BUFFER_INPUT);
m_geometry["faces"]->setBuffer(m_faceBuffer);
m_faceBuffer->setFormat(RT_FORMAT_UNSIGNED_INT3);
m_faceBuffer->setSize(0);
}
} // namespace torch | 22.166667 | 74 | 0.695367 | arpg |
cca7779d4cd5e5cd70a4749115a3ec5bd72eebd3 | 23 | cpp | C++ | ch15/ex15.34.35.36.38/andquery.cpp | shawabhishek/Cpp-Primer | c93143965e62c7ab833f43586ab1c759a5707cfc | [
"CC0-1.0"
] | 7,897 | 2015-01-02T04:35:38.000Z | 2022-03-31T08:32:50.000Z | ch15/ex15.34.35.36.38/andquery.cpp | shawabhishek/Cpp-Primer | c93143965e62c7ab833f43586ab1c759a5707cfc | [
"CC0-1.0"
] | 456 | 2015-01-01T15:47:52.000Z | 2022-02-07T04:17:56.000Z | ch15/ex15.34.35.36.38/andquery.cpp | shawabhishek/Cpp-Primer | c93143965e62c7ab833f43586ab1c759a5707cfc | [
"CC0-1.0"
] | 3,887 | 2015-01-01T13:23:23.000Z | 2022-03-31T15:05:21.000Z | #include "andquery.h"
| 7.666667 | 21 | 0.695652 | shawabhishek |
cca836501907614c4cf55c6d3a70e53d93748bd8 | 3,113 | cpp | C++ | modules/core/src/single_instance.cpp | tizenorg/platform.framework.web.wrt-commons | 5835a89c8b013c00b828fecf04f423adc9e5d561 | [
"Apache-2.0"
] | null | null | null | modules/core/src/single_instance.cpp | tizenorg/platform.framework.web.wrt-commons | 5835a89c8b013c00b828fecf04f423adc9e5d561 | [
"Apache-2.0"
] | null | null | null | modules/core/src/single_instance.cpp | tizenorg/platform.framework.web.wrt-commons | 5835a89c8b013c00b828fecf04f423adc9e5d561 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @file single_instance.cpp
* @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
* @version 1.0
* @brief This file is the implementation file of single instance
*/
#include <dpl/single_instance.h>
#include <dpl/log/log.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <dpl/assert.h>
namespace DPL
{
namespace // anonumous
{
const char *LOCK_PREFIX_PATH = "/tmp/dpl_single_instance_";
}
SingleInstance::SingleInstance()
: m_locked(false),
m_fdLock(-1)
{
}
SingleInstance::~SingleInstance()
{
Assert(!m_locked && "Single instance must be released before exit!");
}
bool SingleInstance::TryLock(const std::string &lockName)
{
LogPedantic("Locking single instance: " << lockName);
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 1;
// Open lock file
m_fdLock = TEMP_FAILURE_RETRY(open((std::string(LOCK_PREFIX_PATH) + lockName).c_str(), O_WRONLY | O_CREAT, 0666));
if (m_fdLock == -1)
ThrowMsg(Exception::LockError, "Cannot open single instance lock file!");
// Lock file
int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock));
// Was the instance successfuly locked ?
if (result == 0)
{
LogPedantic("Instance locked: " << lockName);
// It is locked now
m_locked = true;
// Done
return true;
}
if (errno == EACCES || errno == EAGAIN)
{
LogPedantic("Instance is already running: " << lockName);
return false;
}
// This is lock error
ThrowMsg(Exception::LockError, "Cannot lock single instance lock file!");
}
void SingleInstance::Release()
{
if (!m_locked)
return;
LogPedantic("Unlocking single instance");
// Unlock file
struct flock lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 1;
int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock));
// Was the instance successfuly unlocked ?
if (result == -1)
ThrowMsg(Exception::LockError, "Cannot unlock single instance lock file!");
// Close lock file
if (TEMP_FAILURE_RETRY(close(m_fdLock)) == -1)
ThrowMsg(Exception::LockError, "Cannot close single instance lock file!");
m_fdLock = -1;
// Done
m_locked = false;
LogPedantic("Instance unlocked");
}
} // namespace DPL
| 25.941667 | 118 | 0.65628 | tizenorg |
cca8c4e26b768dddcf516e3d929d11c4b025470c | 1,656 | cpp | C++ | leetcode_cpp/reverse_linked_list_II.cpp | jialing3/corner_cases | 54a316518fcf4b43ae96ed9935b4cf91ade1eed9 | [
"Apache-2.0"
] | 1 | 2015-05-29T08:40:48.000Z | 2015-05-29T08:40:48.000Z | leetcode_cpp/reverse_linked_list_II.cpp | jialing3/corner_cases | 54a316518fcf4b43ae96ed9935b4cf91ade1eed9 | [
"Apache-2.0"
] | null | null | null | leetcode_cpp/reverse_linked_list_II.cpp | jialing3/corner_cases | 54a316518fcf4b43ae96ed9935b4cf91ade1eed9 | [
"Apache-2.0"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
// case in which no swap is needed
if (m == n) {
return head;
}
ListNode *current = head;
ListNode *next;
ListNode *previous;
int counter = 1;
ListNode *node_m_minus_1;
ListNode *node_m;
ListNode *node_n;
ListNode *node_n_plus_1;
// case in which swap starts from the beginning
while (true) {
if (current != NULL) {
next = current -> next;
}
if (counter == m - 1) {
node_m_minus_1 = current;
}
else if (counter == m) {
node_m = current;
}
else if (counter == n) {
node_n = current;
}
else if (counter == n + 1) {
node_n_plus_1 = current;
}
if (counter >= m + 1 && counter <= n) {
current -> next = previous;
}
if (current == NULL) {
break;
}
counter += 1;
previous = current;
current = next;
}
if (m != 1) {
node_m_minus_1 -> next = node_n;
}
else {
head = node_n;
}
node_m -> next = node_n_plus_1;
return head;
}
};
| 23.657143 | 61 | 0.407005 | jialing3 |
ccad57f059424cb47150cc48cf0d7c1a417233bc | 1,294 | cpp | C++ | Code/C++/sorted_zig_zag_array.cpp | Atul-Kashyap/Algo-Tree | 5ab65e86551be2843cae85a7c9860a91883abede | [
"MIT"
] | 356 | 2021-01-24T11:34:15.000Z | 2022-03-16T08:39:02.000Z | Code/C++/sorted_zig_zag_array.cpp | Atul-Kashyap/Algo-Tree | 5ab65e86551be2843cae85a7c9860a91883abede | [
"MIT"
] | 1,778 | 2021-01-24T10:52:44.000Z | 2022-01-30T12:34:05.000Z | Code/C++/sorted_zig_zag_array.cpp | Atul-Kashyap/Algo-Tree | 5ab65e86551be2843cae85a7c9860a91883abede | [
"MIT"
] | 782 | 2021-01-24T10:54:10.000Z | 2022-03-23T10:16:04.000Z | /*
Approach : First sort the array then, swap pairs of elements
except the first element. Example - keep a[0], swap a[1] with a[2], swap a[3] with a[4], and so on.
So, we will take array and its size as parameters, run a loop from i to size of the array
and swap every pair of element using swap function. At the end of loop, we will print the array.
*/
#include <bits/stdc++.h>
using namespace std;
//helper function that converts given array in zig-zag form
void zigzag(int a[] , int n)
{
for(int i = 1 ; i < n ; i += 2)
{
if(i+1 < n)
swap(a[i] , a[i+1]);
}
cout << "\nZig - Zag array : ";
for(int i = 0 ; i < n ; i++)
cout << a[i] << " ";
}
int main()
{
int a[] = {4,3,7,8,6,2,1};
int n = sizeof(a)/sizeof(a[0]);
sort(a , a+n);
cout << "Original array : ";
for(int i=0 ; i<n ; i++)
cout << a[i]<<" ";
zigzag(a , n);
return 0;
}
/*
Test Case -
Sample Input/Output (1):
Original array : 1 2 3 4 6 7 8
Zig - Zag array : 1 3 2 6 4 8 7
Sample Input/Output (2):
Original array : 11 12 13 14 16 17 18
Zig - Zag array : 11 13 12 16 14 18 17
Time Complexity : O(n log n), where n is the number of elements.
Space Complexity : O(1)
*/
| 23.527273 | 99 | 0.544822 | Atul-Kashyap |
ccae3b7834d20ce2f8ca76cac69cb28f2bfc65a9 | 1,895 | cpp | C++ | cpp-leetcode/leetcode284-peeking-iterator_with_main.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode284-peeking-iterator_with_main.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode284-peeking-iterator_with_main.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include <iostream>
#include <queue>
#include <vector>
#include <assert.h>
#include <algorithm>
using namespace std;
class Iterator {
const vector<int>* nums;
int index;
public:
Iterator(const vector<int>& nums) {
this->nums = &nums;
this->index = 0;
}
Iterator(const Iterator& iter);
// Returns the next element in the iteration.
int next() {
return (*nums)[index++];
}
// Returns true if the iteration has more elements.
bool hasNext() const {
return index < (*nums).size();
}
};
class PeekingIterator : public Iterator {
private:
int nextElement;
bool flag;
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
// Initialize any member here.
// **DO NOT** save a copy of nums and manipulate it directly.
// You should only use the Iterator interface methods.
flag = Iterator::hasNext();
if (flag) {
nextElement = Iterator::next();
}
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
return nextElement;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
int ret = nextElement;
flag = Iterator::hasNext();
if (flag) {
nextElement = Iterator::next();
}
return ret;
}
bool hasNext() const {
return flag;
}
};
// Test
int main()
{
/** 用gcc/g++编译, 需要用这种方式初始化vector:
*/
int a[3] = {1, 2, 3};
vector<int> nums(a, a + 3);
PeekingIterator peekingIterator(nums);
assert(1 == peekingIterator.next());
assert(2 == peekingIterator.peek());
assert(2 == peekingIterator.next());
assert(3 == peekingIterator.next());
assert(!peekingIterator.hasNext());
cout << "OK~" << endl;
return 0;
} | 22.831325 | 80 | 0.590501 | yanglr |
ccaf786c723eb9e2b5b472bcfd90366cc2650e7a | 1,767 | cc | C++ | src/bin/ngrammerge.cc | unixnme/opengrm_ngram | ce9b55b406c681902a20c4b547bdd254a8a399e7 | [
"Apache-2.0"
] | 1 | 2020-05-11T00:44:55.000Z | 2020-05-11T00:44:55.000Z | src/bin/ngrammerge.cc | unixnme/opengrm_ngram | ce9b55b406c681902a20c4b547bdd254a8a399e7 | [
"Apache-2.0"
] | null | null | null | src/bin/ngrammerge.cc | unixnme/opengrm_ngram | ce9b55b406c681902a20c4b547bdd254a8a399e7 | [
"Apache-2.0"
] | null | null | null |
// 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.
//
// Copyright 2005-2016 Brian Roark and Google, Inc.
#include <fst/flags.h>
#include <ngram/ngram-model.h>
DEFINE_double(alpha, 1.0, "Weight for first FST");
DEFINE_double(beta, 1.0, "Weight for second (and subsequent) FST(s)");
DEFINE_string(context_pattern, "", "Context pattern for second FST");
DEFINE_string(contexts, "", "Context patterns file (all FSTs)");
DEFINE_bool(normalize, false, "Normalize resulting model");
DEFINE_string(method, "count_merge",
"One of: \"context_merge\", \"count_merge\", \"model_merge\" "
"\"bayes_model_merge\", \"histogram_merge\", \"replace_merge\"");
DEFINE_int32(max_replace_order, -1,
"Maximum order to replace in replace_merge, ignored if < 1.");
DEFINE_string(ofile, "", "Output file");
DEFINE_int64(backoff_label, 0, "Backoff label");
DEFINE_double(norm_eps, ngram::kNormEps, "Normalization check epsilon");
DEFINE_bool(check_consistency, false, "Check model consistency");
DEFINE_bool(complete, false, "Complete partial models");
DEFINE_bool(round_to_int, false, "Round all merged counts to integers");
int ngrammerge_main(int argc, char** argv);
int main(int argc, char** argv) {
return ngrammerge_main(argc, argv);
}
| 45.307692 | 79 | 0.728919 | unixnme |
ccb088631b6ec9d949e90b8364b37129fe8757a2 | 7,307 | cpp | C++ | src/app/app.cpp | zgpio/tree.nvim | 5ff3644fb4eddc6754488263c21745e057a16f05 | [
"BSD-3-Clause"
] | 199 | 2019-10-20T12:53:41.000Z | 2022-03-28T09:04:41.000Z | src/app/app.cpp | zgpio/tree.nvim | 5ff3644fb4eddc6754488263c21745e057a16f05 | [
"BSD-3-Clause"
] | 12 | 2019-10-21T01:16:56.000Z | 2022-01-27T03:22:55.000Z | src/app/app.cpp | zgpio/tree.nvim | 5ff3644fb4eddc6754488263c21745e057a16f05 | [
"BSD-3-Clause"
] | 7 | 2019-11-01T02:13:58.000Z | 2021-11-30T17:34:24.000Z | #include <cinttypes>
#include <iostream>
#include "app.h"
using std::cout;
using std::endl;
using std::string;
namespace tree
{
App::App(nvim::Nvim *nvim, int chan_id) : m_nvim(nvim), chan_id(chan_id)
{
INFO("chan_id: %d\n", chan_id);
auto &a = *m_nvim;
// NOTE: 必须同步调用
a.execute_lua("require('tree').channel_id = ...", {chan_id});
Tree::api = m_nvim;
init_highlight();
}
void App::init_highlight()
{
auto &a = *m_nvim;
// init highlight
char name[40];
char cmd[80];
// sprintf(cmd, "silent hi %s guifg=%s", name, cell.color.toStdString().c_str());
sprintf(name, "tree_%d_0", FILENAME); // file
sprintf(cmd, "hi %s guifg=%s", name, gui_colors[YELLOW].data());
a.command(cmd);
sprintf(name, "tree_%d_1", FILENAME); // dir
sprintf(cmd, "hi %s guifg=%s", name, gui_colors[BLUE].data());
a.command(cmd);
sprintf(name, "tree_%d", SIZE);
sprintf(cmd, "hi %s guifg=%s", name, gui_colors[GREEN].data());
a.command(cmd);
sprintf(name, "tree_%d", INDENT);
sprintf(cmd, "hi %s guifg=%s", name, "#41535b");
a.command(cmd);
sprintf(name, "tree_%d", TIME);
sprintf(cmd, "hi %s guifg=%s", name, gui_colors[BLUE].data());
a.command(cmd);
for (int i = 0; i < 83; ++i) {
sprintf(name, "tree_%d_%d", ICON, i);
sprintf(cmd, "hi %s guifg=%s", name, icons[i].second.data());
a.command(cmd);
}
for (int i = 0; i < 16; ++i) {
sprintf(name, "tree_%d_%d", MARK, i);
sprintf(cmd, "hi %s guifg=%s", name, gui_colors[i].data());
a.command(cmd);
}
for (int i = 0; i < 8; ++i) {
sprintf(name, "tree_%d_%d", GIT, i);
sprintf(cmd, "hi %s guifg=%s", name, git_indicators[i].second.data());
a.command(cmd);
}
}
void App::createTree(int bufnr, string &path)
{
auto &b = m_nvim;
int ns_id = b->create_namespace("tree_icon");
if (path.back() == '/') // path("/foo/bar/").parent_path(); // "/foo/bar"
path.pop_back();
INFO("bufnr:%d ns_id:%d path:%s\n", bufnr, ns_id, path.c_str());
Tree &tree = *(new Tree(bufnr, ns_id));
trees.insert({bufnr, &tree});
treebufs.insert(treebufs.begin(), bufnr);
tree.cfg.update(m_cfgmap);
m_ctx.prev_bufnr = bufnr;
tree.changeRoot(path);
b->async_buf_set_option(bufnr, "buflisted", tree.cfg.listed);
nvim::Dictionary tree_cfg{
{"toggle", tree.cfg.toggle},
};
b->execute_lua("tree.resume(...)", {m_ctx.prev_bufnr, tree_cfg});
}
void App::handleNvimNotification(const string &method, const vector<nvim::Object> &args)
{
INFO("method: %s\n", method.c_str());
if (method == "_tree_async_action" && args.size() > 0) {
// _tree_async_action [action: string, args: vector, context: multimap]
string action = args.at(0).as_string();
vector<nvim::Object> act_args = args.at(1).as_vector();
auto context = args.at(2).as_multimap();
// INFO("\taction: %s\n", action.c_str());
m_ctx = context;
// INFO("\tprev_bufnr: %d\n", m_ctx.prev_bufnr);
auto search = trees.find(m_ctx.prev_bufnr);
if (search != trees.end()) {
// if (action == "quit" && args.size() > 0)
search->second->action(action, act_args, context);
}
} else if (method == "function") {
string fn = args.at(0).as_string();
// TODO The logic of tree.nvim calling lua code and then calling back cpp code should be placed in tree.cpp
if (fn == "paste") {
vector<nvim::Object> fargs = args.at(1).as_vector();
vector<nvim::Object> pos = fargs[0].as_vector();
string src = fargs[1].as_string();
string dest = fargs[2].as_string();
int buf = pos[0].as_uint64_t();
int line = pos[1].as_uint64_t();
trees[buf]->paste(line, src, dest);
} else if (fn == "new_file") {
vector<nvim::Object> fargs = args.at(1).as_vector();
string input = fargs[0].as_string();
int bufnr = fargs[1].as_uint64_t();
trees[bufnr]->handleNewFile(input);
} else if (fn == "rename") {
vector<nvim::Object> fargs = args.at(1).as_vector();
string input = fargs[0].as_string();
int bufnr = fargs[1].as_uint64_t();
trees[bufnr]->handleRename(input);
} else if (fn == "remove") {
vector<nvim::Object> fargs = args.at(1).as_vector();
int buf = fargs[0].as_uint64_t();
int choice = fargs[1].as_uint64_t();
trees[buf]->remove();
} else if (fn == "on_detach") {
const int buf = args.at(1).as_uint64_t();
auto got = trees.find(buf);
if (got != trees.end()) {
delete trees[buf];
trees.erase(buf);
// TODO: 修改tree_buf
printf("\tAfter remove %d, trees:", buf);
for (auto i : trees) {
cout << i.first << ",";
}
cout << endl;
}
}
}
}
void App::handleRequest(nvim::NvimRPC &rpc, uint64_t msgid, const string &method, const vector<nvim::Object> &args)
{
INFO("method: %s args.size: %lu\n", method.c_str(), args.size());
if (method == "_tree_start" && args.size() > 0) {
// _tree_start [paths: List, context: Dictionary]
auto paths = args[0].as_vector();
// TODO: 支持path列表(多个path源)
string path = paths[0].as_string();
m_cfgmap = args[1].as_multimap();
auto *b = m_nvim;
auto search = m_cfgmap.find("bufnr");
if (search != m_cfgmap.end()) {
// TODO: createTree时存在request和此处的response好像产生冲突
createTree(search->second.as_uint64_t(), path);
} else {
// NOTE: Resume tree buffer by default.
// TODO: consider to use treebufs[0]
Tree &tree = *trees[m_ctx.prev_bufnr];
auto it = std::find(treebufs.begin(), treebufs.end(), m_ctx.prev_bufnr);
if (it != treebufs.end()) {
treebufs.erase(it);
treebufs.insert(treebufs.begin(), m_ctx.prev_bufnr);
}
// NOTE: 暂时不支持通过_tree_start动态更新columns
auto got = m_cfgmap.find("columns");
if (got != m_cfgmap.end()) {
m_cfgmap.erase(got);
}
tree.cfg.update(m_cfgmap);
nvim::Array bufnrs;
for (const int item : treebufs)
bufnrs.push_back(item);
Map tree_cfg = {
{"toggle", tree.cfg.toggle},
};
b->async_execute_lua("tree.resume(...)", {bufnrs, tree_cfg});
// TODO: columns 状态更新需要清除不需要的columns
}
rpc.send_response(msgid, {}, {});
} else if (method == "_tree_get_candidate") {
Map context = args[0].as_multimap();
Tree &tree = *trees[m_ctx.prev_bufnr];
auto search = context.find("cursor");
auto rv = tree.get_candidate(search->second.as_uint64_t() - 1);
rpc.send_response(msgid, {}, rv);
} else {
// be sure to return early or this message will be sent
rpc.send_response(msgid, {"Unknown method"}, {});
}
}
} // namespace tree
| 34.630332 | 115 | 0.545641 | zgpio |
ccb2ac203882c1bd30851b880da094ac75bbbf43 | 1,470 | hpp | C++ | code/jsbind/v8/global.hpp | Chobolabs/jsbind | 874b41df6bbc9a3b756e828c64e43e1b6cbd4386 | [
"MIT"
] | 57 | 2019-03-30T21:26:08.000Z | 2022-03-11T02:22:09.000Z | code/jsbind/v8/global.hpp | Chobolabs/jsbind | 874b41df6bbc9a3b756e828c64e43e1b6cbd4386 | [
"MIT"
] | null | null | null | code/jsbind/v8/global.hpp | Chobolabs/jsbind | 874b41df6bbc9a3b756e828c64e43e1b6cbd4386 | [
"MIT"
] | 3 | 2020-04-11T09:19:44.000Z | 2021-09-30T07:30:45.000Z | // jsbind
// Copyright (c) 2019 Chobolabs Inc.
// http://www.chobolabs.com/
//
// Distributed under the MIT Software License
// See accompanying file LICENSE.txt or copy at
// http://opensource.org/licenses/MIT
//
#pragma once
#if defined(JSBIND_NODE)
# include <node.h>
#endif
#include <v8.h>
#include <new>
namespace jsbind
{
extern void v8_initialize_with_global(v8::Local<v8::Object> global);
namespace internal
{
extern v8::Isolate* isolate;
struct context
{
v8::Locker* m_locker = nullptr;
void enter()
{
if (!m_locker) // simple reentry
{
m_locker = new (buf)v8::Locker(isolate);
isolate->Enter();
auto ctx = to_local();
ctx->Enter();
}
}
void exit()
{
if (m_locker)
{
auto ctx = to_local();
ctx->Exit();
isolate->Exit();
m_locker->~Locker();
m_locker = nullptr;
}
}
const v8::Local<v8::Context>& to_local() const
{
return *reinterpret_cast<const v8::Handle<v8::Context>*>(&v8ctx);
}
v8::Persistent<v8::Context> v8ctx;
char buf[sizeof(v8::Locker)]; // placing the locker here to avoid needless allocations
};
extern context ctx;
extern void report_exception(const v8::TryCatch& try_catch);
}
}
| 19.6 | 94 | 0.533333 | Chobolabs |
ccb569defcd3a351a7d493e3bccf21d2d98e4c18 | 703 | cpp | C++ | backend/drone_ros_ws/src/drone_app/test/BBoxTest.cpp | Flytte/flytte | 36e2dc886c7437c3e3fff5a082296d5bc1f10bd7 | [
"BSD-3-Clause"
] | 3 | 2018-05-08T18:01:48.000Z | 2019-06-27T07:31:20.000Z | backend/drone_ros_ws/src/drone_app/test/BBoxTest.cpp | Flytte/flytte | 36e2dc886c7437c3e3fff5a082296d5bc1f10bd7 | [
"BSD-3-Clause"
] | null | null | null | backend/drone_ros_ws/src/drone_app/test/BBoxTest.cpp | Flytte/flytte | 36e2dc886c7437c3e3fff5a082296d5bc1f10bd7 | [
"BSD-3-Clause"
] | null | null | null | #include "common/BBox.hpp"
#include <gtest/gtest.h>
TEST(BBox, defaultConstructor)
{
BBox box;
EXPECT_EQ(0, box.posX);
EXPECT_EQ(0, box.posY);
EXPECT_EQ(0, box.w);
EXPECT_EQ(0, box.h);
EXPECT_EQ(0, box.rotX);
EXPECT_EQ(0, box.rotY);
EXPECT_EQ(0, box.rotZ);
}
TEST(BBox, copyConstructor)
{
BBox box0(10, 20, 30, 40, 50, 60, 70);
BBox box1(box0);
EXPECT_EQ(10, box1.posX);
EXPECT_EQ(20, box1.posY);
EXPECT_EQ(30, box1.w);
EXPECT_EQ(40, box1.h);
EXPECT_EQ(50, box1.rotX);
EXPECT_EQ(60, box1.rotY);
EXPECT_EQ(70, box1.rotZ);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 19 | 42 | 0.623044 | Flytte |
ccb5c6c9346c1270e6beacf912fe3b038cdd64fb | 4,923 | cpp | C++ | owGame/Sky/Sky.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 30 | 2017-09-02T20:25:47.000Z | 2021-12-31T10:12:07.000Z | owGame/Sky/Sky.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | null | null | null | owGame/Sky/Sky.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 23 | 2018-02-04T17:18:33.000Z | 2022-03-22T09:45:36.000Z | #include "stdafx.h"
// Include
#include "SkyManager.h"
// General
#include "Sky.h"
namespace
{
const float cSkyMultiplier = 36.0f;
template<typename T>
inline T GetByTimeTemplate(std::vector<Sky::SSkyInterpolatedParam<T>> param, uint32 _time)
{
if (param.empty())
return T();
T parBegin, parEnd;
uint32 timeBegin, timeEnd;
uint32_t last = static_cast<uint32>(param.size()) - 1;
if (_time < param[0].time)
{
// interpolate between last and first
parBegin = param[last].value;
timeBegin = param[last].time;
parEnd = param[0].value;
timeEnd = param[0].time + C_Game_SecondsInDay; // next day
_time += C_Game_SecondsInDay;
}
else
{
for (uint32 i = last; i >= 0; i--)
{
if (_time >= param[i].time)
{
parBegin = param[i].value;
timeBegin = param[i].time;
if (i == last) // if current is last, then interpolate with first
{
parEnd = param[0].value;
timeEnd = param[0].time + C_Game_SecondsInDay;
}
else
{
parEnd = param[i + 1].value;
timeEnd = param[i + 1].time;
}
break;
}
}
}
float tt = (float)(_time - timeBegin) / (float)(timeEnd - timeBegin);
return parBegin * (1.0f - tt) + (parEnd * tt);
}
}
Sky::Sky() :
m_LightRecord(nullptr)
{}
Sky::Sky(const CDBCStorage* DBCStorage, const DBC_LightRecord* LightData)
: m_LightRecord(LightData)
{
m_Position.x = m_LightRecord->Get_PositionX() / cSkyMultiplier;
m_Position.y = m_LightRecord->Get_PositionY() / cSkyMultiplier;
m_Position.z = m_LightRecord->Get_PositionZ() / cSkyMultiplier;
m_Range.min = m_LightRecord->Get_RadiusInner() / cSkyMultiplier;
m_Range.max = m_LightRecord->Get_RadiusOuter() / cSkyMultiplier;
m_IsGlobalSky = (m_Position.x == 0.0f && m_Position.y == 0.0f && m_Position.z == 0.0f);
if (m_IsGlobalSky)
Log::Info("Sky: [%d] is global sky.", m_LightRecord->Get_ID());
LoadParams(DBCStorage, ESkyParamsNames::SKY_ParamsClear);
}
Sky::~Sky()
{}
class SkyParam_Color
: public Sky::SSkyInterpolatedParam<ColorRGB>
{
public:
SkyParam_Color(uint32 _time, uint32 _color)
: SSkyInterpolatedParam<ColorRGB>(_time, fromRGB(_color))
{}
};
class SkyParam_Fog
: public Sky::SSkyInterpolatedParam<float>
{
public:
SkyParam_Fog(uint32 _time, float _param)
: SSkyInterpolatedParam<float>(_time, _param)
{}
};
void Sky::LoadParams(const CDBCStorage* DBCStorage, ESkyParamsNames _param)
{
for (uint32 i = 0; i < ESkyColors::SKY_COLOR_COUNT; i++)
m_IntBand_Colors[i].clear();
for (uint32 i = 0; i < ESkyFogs::SKY_FOG_COUNT; i++)
m_FloatBand_Fogs[i].clear();
const DBC_LightParamsRecord* paramRecord = DBCStorage->DBC_LightParams()[m_LightRecord->Get_LightParams(_param)];
_ASSERT(paramRecord != nullptr);
uint32 paramSet = paramRecord->Get_ID();
//-- LightParams
m_Params.HighlightSky = paramRecord->Get_HighlightSky();
m_Params.LightSkyBoxRecord = DBCStorage->DBC_LightSkybox()[paramRecord->Get_LightSkyboxID()];
m_Params.Glow = paramRecord->Get_Glow();
if (m_Params.LightSkyBoxRecord != nullptr)
{
// TODO
//Log::Info("Sky: Skybox name = '%s'.", m_Params.GetSkybox()->Get_Filename().c_str());
}
//-- Color params
for (uint32 i = 0; i < ESkyColors::SKY_COLOR_COUNT; i++)
{
const DBC_LightIntBandRecord* lightColorsRecord = DBCStorage->DBC_LightIntBand()[paramSet * ESkyColors::SKY_COLOR_COUNT - (ESkyColors::SKY_COLOR_COUNT - 1) + i];
_ASSERT(lightColorsRecord != nullptr);
for (uint32 l = 0; l < lightColorsRecord->Get_Count(); l++)
{
// Read time & color value
m_IntBand_Colors[i].push_back(SkyParam_Color(lightColorsRecord->Get_Times(l), lightColorsRecord->Get_Values(l)));
}
}
//-- Fog, Sun, Clouds param
for (uint32 i = 0; i < ESkyFogs::SKY_FOG_COUNT; i++)
{
const DBC_LightFloatBandRecord* lightFogRecord = DBCStorage->DBC_LightFloatBand()[paramSet * ESkyFogs::SKY_FOG_COUNT - (ESkyFogs::SKY_FOG_COUNT - 1) + i];
_ASSERT(lightFogRecord != nullptr);
for (uint32 l = 0; l < lightFogRecord->Get_Count(); l++)
{
// Read time & fog param
float param = lightFogRecord->Get_Values(l);
if (i == ESkyFogs::SKY_FOG_DISTANCE)
param /= cSkyMultiplier;
m_FloatBand_Fogs[i].push_back(SkyParam_Fog(lightFogRecord->Get_Times(l), param));
}
}
m_Params.WaterAplha[ESkyWaterAlpha::SKY_WATER_SHALLOW] = paramRecord->Get_WaterShallowAlpha();
m_Params.WaterAplha[ESkyWaterAlpha::SKY_WATER_DEEP] = paramRecord->Get_WaterDeepAlpha();
m_Params.WaterAplha[ESkyWaterAlpha::SKY_OCEAN_SHALLOW] = paramRecord->Get_OceanShallowAlpha();
m_Params.WaterAplha[ESkyWaterAlpha::SKY_OCEAN_DEEP] = paramRecord->Get_OceanDeepAlpha();
}
SSkyParams& Sky::Interpolate(uint32 _time)
{
for (uint8 i = 0; i < ESkyColors::SKY_COLOR_COUNT; i++)
m_Params.Colors[i] = GetByTimeTemplate(m_IntBand_Colors[i], _time);
for (uint8 i = 0; i < ESkyFogs::SKY_FOG_COUNT; i++)
m_Params.Fogs[i] = GetByTimeTemplate(m_FloatBand_Fogs[i], _time);
return m_Params;
}
| 28.789474 | 163 | 0.700995 | Chaos192 |
ccbcb51d561c51fc823b3a68ecb2125657108454 | 2,228 | cpp | C++ | game.cpp | Niakr1s/ctetris | 59335c61e58dfef2ab0385f724fedaf62e8721a4 | [
"MIT"
] | null | null | null | game.cpp | Niakr1s/ctetris | 59335c61e58dfef2ab0385f724fedaf62e8721a4 | [
"MIT"
] | null | null | null | game.cpp | Niakr1s/ctetris | 59335c61e58dfef2ab0385f724fedaf62e8721a4 | [
"MIT"
] | 1 | 2019-12-16T13:58:58.000Z | 2019-12-16T13:58:58.000Z | #include "game.h"
#include <time.h>
#include <chrono>
#include <functional>
#include <thread>
#include "consolekeyboardcontroller.h"
#include "gamestate.h"
using namespace std::chrono_literals;
Game::Game()
: Game(std::make_shared<ConsoleDisplay>(20, 14),
std::make_shared<ConsoleKeyboardController>()) {}
Game::Game(std::shared_ptr<IDisplay> display,
std::shared_ptr<IInputController> input)
: glass_(display->height(), display->width()),
score_(0),
display_(display),
input_(input),
speedup_timer_(30s),
movedown_timer_(1s) {
setGamestate<RunningGameState>();
input_->setGame(this);
movedown_timer_.start([this] { parseInput(IInputController::Key::DOWN); });
speedup_timer_.start([this] { speedUp(); });
}
void Game::start() {
reprintAll();
input_->startPolling();
}
void Game::quit() {
reprintAll();
display_->exit();
std::exit(1);
}
void Game::parseInput(IInputController::Key key) {
gamestate_->parseInput(key);
}
void Game::reprintIfNeeded() {
if (need_reprint_.glass) {
display_->printGlass(glass_);
}
if (need_reprint_.next_figure) {
display_->printNextFigure(glass_.next_figure());
}
if (need_reprint_.figure) {
display_->printFigure(glass_.figure());
}
need_reprint_ = NeedReprint();
}
void Game::reprintAll() {
display_->printGlass(glass_);
display_->printScore(score_);
display_->printFigure(glass_.figure());
display_->printNextFigure(glass_.next_figure());
}
bool Game::clearRows() {
bool res = need_clear_rows_;
if (need_clear_rows_) {
int cleared_rows = glass_.clearRows();
if (cleared_rows) {
score_ += cleared_rows * 100;
display_->printScore(score_);
need_reprint_.glass = true;
}
}
need_clear_rows_ = false;
return res;
}
void Game::moveDown() {
display_->eraseFigure(glass_.figure());
bool glued = glass_.figureMoveY(1);
need_clear_rows_ |= glued;
need_reprint_.next_figure |= glued;
need_reprint_.glass |= glued;
need_reprint_.figure = true;
if (glued) { // figure already spawned
if (glass_.figure()->top() == 0 && glass_.figureIntersects()) {
quit();
}
}
}
void Game::speedUp() { gamestate_->speedUp(); }
| 23.208333 | 77 | 0.671454 | Niakr1s |
ccbeadcd7cdc4214ba78636dafecb47cb6bcc123 | 441 | hpp | C++ | sort/shaker_sort.hpp | lis411/sorting | 57b113849c0a598c96aecc5fe6fd27582f141bfa | [
"MIT"
] | null | null | null | sort/shaker_sort.hpp | lis411/sorting | 57b113849c0a598c96aecc5fe6fd27582f141bfa | [
"MIT"
] | null | null | null | sort/shaker_sort.hpp | lis411/sorting | 57b113849c0a598c96aecc5fe6fd27582f141bfa | [
"MIT"
] | null | null | null | #ifndef SHAKER_SORT_HPP
#define SHAKER_SORT_HPP
template<typename Iterator>
void shaker_sort(Iterator b, Iterator e)
{
while(b != e)
{
for(auto bb = b; std::next(bb) != e; ++bb)
{
if(*bb > *std::next(bb))
std::swap(*bb, *std::next(bb));
}
--e;
if(b == e)
break;
for(auto ee = std::prev(e); ee != b; --ee)
{
if(*std::prev(ee) > *ee)
std::swap(*std::prev(ee), *ee);
}
++b;
}
return;
}
#endif
| 11.605263 | 44 | 0.530612 | lis411 |