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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
283a71c9583a82d67aa9059ac89118881af9ce63
| 47,507
|
cpp
|
C++
|
src/conformance/conformance_test/test_LayerComposition.cpp
|
JoeLudwig/OpenXR-CTS
|
144c94e8982fe76986019abc9bf2b016740536df
|
[
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | 1
|
2020-12-11T03:28:32.000Z
|
2020-12-11T03:28:32.000Z
|
src/conformance/conformance_test/test_LayerComposition.cpp
|
JoeLudwig/OpenXR-CTS
|
144c94e8982fe76986019abc9bf2b016740536df
|
[
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | null | null | null |
src/conformance/conformance_test/test_LayerComposition.cpp
|
JoeLudwig/OpenXR-CTS
|
144c94e8982fe76986019abc9bf2b016740536df
|
[
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | null | null | null |
// Copyright (c) 2019-2021, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 <array>
#include <thread>
#include <numeric>
#include "utils.h"
#include "report.h"
#include "conformance_utils.h"
#include "conformance_framework.h"
#include "composition_utils.h"
#include <catch2/catch.hpp>
#include <openxr/openxr.h>
#include <xr_linear.h>
using namespace Conformance;
namespace
{
const XrVector3f Up{0, 1, 0};
enum class LayerMode
{
Scene,
Help,
Complete
};
namespace Colors
{
constexpr XrColor4f Red = {1, 0, 0, 1};
constexpr XrColor4f Green = {0, 1, 0, 1};
constexpr XrColor4f Blue = {0, 0, 1, 1};
constexpr XrColor4f Purple = {1, 0, 1, 1};
constexpr XrColor4f Yellow = {1, 1, 0, 1};
constexpr XrColor4f Orange = {1, 0.65f, 0, 1};
constexpr XrColor4f White = {1, 1, 1, 1};
constexpr XrColor4f Transparent = {0, 0, 0, 0};
// Avoid including red which is a "failure color".
constexpr std::array<XrColor4f, 4> UniqueColors{Green, Blue, Yellow, Orange};
} // namespace Colors
namespace Math
{
// Do a linear conversion of a number from one range to another range.
// e.g. 5 in range [0-8] projected into range (-.6 to 0.6) is 0.15.
float LinearMap(int i, int sourceMin, int sourceMax, float targetMin, float targetMax)
{
float percent = (i - sourceMin) / (float)sourceMax;
return targetMin + ((targetMax - targetMin) * percent);
}
constexpr float DegToRad(float degree)
{
return degree / 180 * MATH_PI;
}
} // namespace Math
namespace Quat
{
constexpr XrQuaternionf Identity{0, 0, 0, 1};
XrQuaternionf FromAxisAngle(XrVector3f axis, float radians)
{
XrQuaternionf rowQuat;
XrQuaternionf_CreateFromAxisAngle(&rowQuat, &axis, radians);
return rowQuat;
}
} // namespace Quat
// Appends composition layers for interacting with interactive composition tests.
struct InteractiveLayerManager
{
InteractiveLayerManager(CompositionHelper& compositionHelper, const char* exampleImage, const char* descriptionText)
: m_compositionHelper(compositionHelper)
{
// Set up the input system for toggling between modes and passing/failing.
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy(actionSetInfo.actionSetName, "interaction_test");
strcpy(actionSetInfo.localizedActionSetName, "Interaction Test");
XRC_CHECK_THROW_XRCMD(xrCreateActionSet(compositionHelper.GetInstance(), &actionSetInfo, &m_actionSet));
compositionHelper.GetInteractionManager().AddActionSet(m_actionSet);
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_BOOLEAN_INPUT;
strcpy(actionInfo.actionName, "interaction_manager_select");
strcpy(actionInfo.localizedActionName, "Interaction Manager Select");
XRC_CHECK_THROW_XRCMD(xrCreateAction(m_actionSet, &actionInfo, &m_select));
strcpy(actionInfo.actionName, "interaction_manager_menu");
strcpy(actionInfo.localizedActionName, "Interaction Manager Menu");
XRC_CHECK_THROW_XRCMD(xrCreateAction(m_actionSet, &actionInfo, &m_menu));
XrPath simpleInteractionProfile =
StringToPath(compositionHelper.GetInstance(), "/interaction_profiles/khr/simple_controller");
compositionHelper.GetInteractionManager().AddActionBindings(
simpleInteractionProfile,
{{
{m_select, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/select/click")},
{m_select, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/select/click")},
{m_menu, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/menu/click")},
{m_menu, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/menu/click")},
}});
}
m_viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, XrPosef{{0, 0, 0, 1}, {0, 0, 0}});
// Load example screenshot if available and set up the quad layer for it.
{
XrSwapchain exampleSwapchain;
if (exampleImage) {
exampleSwapchain = compositionHelper.CreateStaticSwapchainImage(RGBAImage::Load(exampleImage), true /* sRGB */);
}
else {
RGBAImage image(256, 256);
image.PutText(XrRect2Di{{0, image.height / 2}, {image.width, image.height}}, "Example Not Available", 64, {1, 0, 0, 1});
exampleSwapchain = compositionHelper.CreateStaticSwapchainImage(image);
}
// Create a quad to the right of the help text.
m_exampleQuad = compositionHelper.CreateQuadLayer(exampleSwapchain, m_viewSpace, 1.25f, {Quat::Identity, {0.5f, 0, -1.5f}});
XrQuaternionf_CreateFromAxisAngle(&m_exampleQuad->pose.orientation, &Up, -15 * MATH_PI / 180);
}
// Set up the quad layer for showing the help text to the left of the example image.
m_descriptionQuad = compositionHelper.CreateQuadLayer(
m_compositionHelper.CreateStaticSwapchainImage(CreateTextImage(768, 768, descriptionText, 48)), m_viewSpace, 0.75f,
{Quat::Identity, {-0.5f, 0, -1.5f}});
m_descriptionQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
XrQuaternionf_CreateFromAxisAngle(&m_descriptionQuad->pose.orientation, &Up, 15 * MATH_PI / 180);
constexpr uint32_t actionsWidth = 768, actionsHeight = 128;
m_sceneActionsSwapchain = compositionHelper.CreateStaticSwapchainImage(
CreateTextImage(actionsWidth, actionsHeight, "Press Select to PASS. Press Menu for description", 48));
m_helpActionsSwapchain =
compositionHelper.CreateStaticSwapchainImage(CreateTextImage(actionsWidth, actionsHeight, "Press select to FAIL", 48));
// Set up the quad layer and swapchain for showing what actions the user can take in the Scene/Help mode.
m_actionsQuad =
compositionHelper.CreateQuadLayer(m_sceneActionsSwapchain, m_viewSpace, 0.75f, {Quat::Identity, {0, -0.4f, -1}});
m_actionsQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
}
template <typename T>
void AddLayer(T* layer)
{
m_sceneLayers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(layer));
}
bool EndFrame(const XrFrameState& frameState, std::vector<XrCompositionLayerBaseHeader*> layers = {})
{
bool keepRunning = AppendLayers(layers);
keepRunning &= m_compositionHelper.PollEvents();
m_compositionHelper.EndFrame(frameState.predictedDisplayTime, std::move(layers));
return keepRunning;
}
private:
bool AppendLayers(std::vector<XrCompositionLayerBaseHeader*>& layers)
{
// Add layer(s) based on the interaction mode.
switch (GetLayerMode()) {
case LayerMode::Scene:
m_actionsQuad->subImage = m_compositionHelper.MakeDefaultSubImage(m_sceneActionsSwapchain);
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_actionsQuad));
for (auto& sceneLayer : m_sceneLayers) {
layers.push_back(sceneLayer);
}
break;
case LayerMode::Help:
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_descriptionQuad));
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_exampleQuad));
m_actionsQuad->subImage = m_compositionHelper.MakeDefaultSubImage(m_helpActionsSwapchain);
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(m_actionsQuad));
break;
case LayerMode::Complete:
return false; // Interactive test is complete.
}
return true;
}
LayerMode GetLayerMode()
{
m_compositionHelper.GetInteractionManager().SyncActions(XR_NULL_PATH);
XrActionStateBoolean actionState{XR_TYPE_ACTION_STATE_BOOLEAN};
XrActionStateGetInfo getInfo{XR_TYPE_ACTION_STATE_GET_INFO};
LayerMode mode = LayerMode::Scene;
getInfo.action = m_menu;
XRC_CHECK_THROW_XRCMD(xrGetActionStateBoolean(m_compositionHelper.GetSession(), &getInfo, &actionState));
if (actionState.currentState) {
mode = LayerMode::Help;
}
getInfo.action = m_select;
XRC_CHECK_THROW_XRCMD(xrGetActionStateBoolean(m_compositionHelper.GetSession(), &getInfo, &actionState));
if (actionState.changedSinceLastSync && actionState.currentState) {
if (mode != LayerMode::Scene) {
// Select on the non-Scene modes (help description/preview image) means FAIL and move to the next.
FAIL("User failed the interactive test");
}
// Select on scene means PASS and move to next
mode = LayerMode::Complete;
}
return mode;
}
CompositionHelper& m_compositionHelper;
XrActionSet m_actionSet;
XrAction m_select;
XrAction m_menu;
XrSpace m_viewSpace;
XrSwapchain m_sceneActionsSwapchain;
XrSwapchain m_helpActionsSwapchain;
XrCompositionLayerQuad* m_actionsQuad;
XrCompositionLayerQuad* m_descriptionQuad;
XrCompositionLayerQuad* m_exampleQuad;
std::vector<XrCompositionLayerBaseHeader*> m_sceneLayers;
};
} // namespace
namespace Conformance
{
// Purpose: Verify behavior of quad visibility and occlusion with the expectation that:
// 1. Quads render with painters algo.
// 2. Quads which are facing away are not visible.
TEST_CASE("Quad Occlusion", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Occlusion");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "quad_occlusion.png",
"This test includes a blue and green quad at Z=-2 with opposite rotations on Y axis forming X. The green quad should be"
" fully visible due to painter's algorithm. A red quad is facing away and should not be visible.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
const XrSwapchain redSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Red);
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
// Each quad is rotated on Y axis by 45 degrees to form an X.
// Green is added second so it should draw over the blue quad.
const XrQuaternionf blueRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(-45));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(blueSwapchain, viewSpace, 1.0f, XrPosef{blueRot, {0, 0, -2}}));
const XrQuaternionf greenRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(45));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{greenRot, {0, 0, -2}}));
// Red quad is rotated away from the viewer and should not be visible.
const XrQuaternionf redRot = Quat::FromAxisAngle({0, 1, 0}, Math::DegToRad(180));
interactiveLayerManager.AddLayer(compositionHelper.CreateQuadLayer(redSwapchain, viewSpace, 1.0f, XrPosef{redRot, {0, 0, -1}}));
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Verify order of transforms by exercising the two ways poses can be specified:
// 1. A pose offset when creating the space
// 2. A pose offset when adding the layer
// If the poses are applied in an incorrect order, the quads will not rendener in the correct place or orientation.
TEST_CASE("Quad Poses", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Poses");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "quad_poses.png",
"Render pairs of quads using similar poses to validate order of operations. The blue/green quads apply a"
" rotation around the Z axis on an XrSpace and then translate the quad out on the Z axis through the quad"
" layer's pose. The purple/yellow quads apply the same translation on the XrSpace and the rotation on the"
" quad layer's pose.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
const XrSwapchain orangeSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Orange);
const XrSwapchain yellowSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Yellow);
constexpr int RotationCount = 2;
constexpr float MaxRotationDegrees = 30;
// For each rotation there are a pair of quads.
static_assert(RotationCount * 2 <= XR_MIN_COMPOSITION_LAYERS_SUPPORTED, "Too many layers");
for (int i = 0; i < RotationCount; i++) {
const float radians =
Math::LinearMap(i, 0, RotationCount - 1, Math::DegToRad(-MaxRotationDegrees), Math::DegToRad(MaxRotationDegrees));
const XrPosef pose1 = XrPosef{Quat::FromAxisAngle({0, 1, 0}, radians), {0, 0, 0}};
const XrPosef pose2 = XrPosef{Quat::Identity, {0, 0, -1}};
const XrSpace viewSpacePose1 = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, pose1);
const XrSpace viewSpacePose2 = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, pose2);
auto quad1 = compositionHelper.CreateQuadLayer((i % 2) == 0 ? blueSwapchain : greenSwapchain, viewSpacePose1, 0.25f, pose2);
interactiveLayerManager.AddLayer(quad1);
auto quad2 = compositionHelper.CreateQuadLayer((i % 2) == 0 ? orangeSwapchain : yellowSwapchain, viewSpacePose2, 0.25f, pose1);
interactiveLayerManager.AddLayer(quad2);
}
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Validates alpha blending (both premultiplied and unpremultiplied).
TEST_CASE("Source Alpha Blending", "[composition][interactive]")
{
CompositionHelper compositionHelper("Source Alpha Blending");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "source_alpha_blending.png",
"All three squares should have an identical blue-green gradient.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
constexpr float QuadZ = -3; // How far away quads are placed.
// Creates image with correctly combined green and blue gradient (this is the the source of truth).
{
Conformance::RGBAImage blueGradientOverGreen(256, 256);
for (int y = 0; y < 256; y++) {
const float t = y / 255.0f;
const XrColor4f dst = Colors::Green;
const XrColor4f src{0, 0, t, t};
const XrColor4f blended{dst.r * (1 - src.a) + src.r, dst.g * (1 - src.a) + src.g, dst.b * (1 - src.a) + src.b, 1};
blueGradientOverGreen.DrawRect(0, y, blueGradientOverGreen.width, 1, blended);
}
const XrSwapchain answerSwapchain = compositionHelper.CreateStaticSwapchainImage(blueGradientOverGreen);
interactiveLayerManager.AddLayer(
compositionHelper.CreateQuadLayer(answerSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {0, 0, QuadZ}}));
}
auto createGradientTest = [&](bool premultiplied, float x, float y) {
// A solid green quad layer will be composited under a blue gradient.
{
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
interactiveLayerManager.AddLayer(
compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {x, y, QuadZ}}));
}
// Create gradient of blue lines from 0.0 to 1.0.
{
Conformance::RGBAImage blueGradient(256, 256);
for (int row = 0; row < blueGradient.height; row++) {
XrColor4f color{0, 0, 1, row / (float)blueGradient.height};
if (premultiplied) {
color = XrColor4f{color.r * color.a, color.g * color.a, color.b * color.a, color.a};
}
blueGradient.DrawRect(0, row, blueGradient.width, 1, color);
}
const XrSwapchain gradientSwapchain = compositionHelper.CreateStaticSwapchainImage(blueGradient);
XrCompositionLayerQuad* gradientQuad =
compositionHelper.CreateQuadLayer(gradientSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {x, y, QuadZ}});
gradientQuad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
if (!premultiplied) {
gradientQuad->layerFlags |= XR_COMPOSITION_LAYER_UNPREMULTIPLIED_ALPHA_BIT;
}
interactiveLayerManager.AddLayer(gradientQuad);
}
};
createGradientTest(true, -1.02f, 0); // Test premultiplied (left of center "answer")
createGradientTest(false, 1.02f, 0); // Test unpremultiplied (right of center "answer")
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
// Purpose: Validate eye visibility flags.
TEST_CASE("Eye Visibility", "[composition][interactive]")
{
CompositionHelper compositionHelper("Eye Visibility");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "eye_visibility.png",
"A green quad is shown in the left eye and a blue quad is shown in the right eye.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW);
const XrSwapchain greenSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Green);
XrCompositionLayerQuad* quad1 =
compositionHelper.CreateQuadLayer(greenSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {-1, 0, -2}});
quad1->eyeVisibility = XR_EYE_VISIBILITY_LEFT;
interactiveLayerManager.AddLayer(quad1);
const XrSwapchain blueSwapchain = compositionHelper.CreateStaticSwapchainSolidColor(Colors::Blue);
XrCompositionLayerQuad* quad2 =
compositionHelper.CreateQuadLayer(blueSwapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {1, 0, -2}});
quad2->eyeVisibility = XR_EYE_VISIBILITY_RIGHT;
interactiveLayerManager.AddLayer(quad2);
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
TEST_CASE("Subimage Tests", "[composition][interactive]")
{
CompositionHelper compositionHelper("Subimage Tests");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "subimage.png",
"Creates a 4x2 grid of quad layers testing subImage array index and imageRect. Red should not be visible except minor bleed in.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace viewSpace = compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_VIEW, XrPosef{Quat::Identity, {0, 0, -1}});
constexpr float QuadZ = -4; // How far away quads are placed.
constexpr int ImageColCount = 4;
constexpr int ImageArrayCount = 2;
constexpr int ImageWidth = 1024;
constexpr int ImageHeight = ImageWidth / ImageColCount;
constexpr int RedZoneBorderSize = 16;
constexpr int CellWidth = (ImageWidth / ImageColCount);
constexpr int CellHeight = CellWidth;
// Create an array swapchain
auto swapchainCreateInfo =
compositionHelper.DefaultColorSwapchainCreateInfo(ImageWidth, ImageHeight, XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT);
swapchainCreateInfo.format = GetGlobalData().graphicsPlugin->GetRGBA8Format(false /* sRGB */);
swapchainCreateInfo.arraySize = ImageArrayCount;
const XrSwapchain swapchain = compositionHelper.CreateSwapchain(swapchainCreateInfo);
// Render a grid of numbers (1,2,3,4) in slice 0 and (5,6,7,8) in slice 1 of the swapchain
// Create a quad layer referencing each number cell.
compositionHelper.AcquireWaitReleaseImage(swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
int number = 1;
for (int arraySlice = 0; arraySlice < ImageArrayCount; arraySlice++) {
Conformance::RGBAImage numberGridImage(ImageWidth, ImageHeight);
// All unused areas are red (should not be seen).
numberGridImage.DrawRect(0, 0, numberGridImage.width, numberGridImage.height, Colors::Red);
for (int x = 0; x < ImageColCount; x++) {
const auto& color = Colors::UniqueColors[number % Colors::UniqueColors.size()];
const XrRect2Di numberRect{{x * CellWidth + RedZoneBorderSize, RedZoneBorderSize},
{CellWidth - RedZoneBorderSize * 2, CellHeight - RedZoneBorderSize * 2}};
numberGridImage.DrawRect(numberRect.offset.x, numberRect.offset.y, numberRect.extent.width, numberRect.extent.height,
Colors::Transparent);
numberGridImage.PutText(numberRect, std::to_string(number).c_str(), CellHeight, color);
numberGridImage.DrawRectBorder(numberRect.offset.x, numberRect.offset.y, numberRect.extent.width,
numberRect.extent.height, 4, color);
number++;
const float quadX = Math::LinearMap(x, 0, ImageColCount - 1, -2.0f, 2.0f);
const float quadY = Math::LinearMap(arraySlice, 0, ImageArrayCount - 1, 0.75f, -0.75f);
XrCompositionLayerQuad* const quad =
compositionHelper.CreateQuadLayer(swapchain, viewSpace, 1.0f, XrPosef{Quat::Identity, {quadX, quadY, QuadZ}});
quad->layerFlags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
quad->subImage.imageArrayIndex = arraySlice;
quad->subImage.imageRect = numberRect;
quad->size.height = 1.0f; // Height needs to be corrected since the imageRect is customized.
interactiveLayerManager.AddLayer(quad);
}
GetGlobalData().graphicsPlugin->CopyRGBAImage(swapchainImage, format, arraySlice, numberGridImage);
}
});
RenderLoop(compositionHelper.GetSession(),
[&](const XrFrameState& frameState) { return interactiveLayerManager.EndFrame(frameState); })
.Loop();
}
TEST_CASE("Projection Array Swapchain", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Array Swapchain");
InteractiveLayerManager interactiveLayerManager(
compositionHelper, "projection_array.png",
"Uses a single texture array for a projection layer (each view is a different slice and each slice has a unique color).");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
// Because a single swapchain is being used for all views (each view is a slice of the texture array), the maximum dimensions must be used
// since the dimensions of all slices are the same.
const auto maxWidth = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectWidth < r.recommendedImageRectWidth;
})
->recommendedImageRectWidth;
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create swapchain with array type.
auto swapchainCreateInfo = compositionHelper.DefaultColorSwapchainCreateInfo(maxWidth, maxHeight);
swapchainCreateInfo.arraySize = (uint32_t)viewProperties.size() * 3;
const XrSwapchain swapchain = compositionHelper.CreateSwapchain(swapchainCreateInfo);
// Set up the projection layer
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
// Use non-contiguous array indices to ferret out any assumptions that implementations are making
// about array indices. In particular 0 != left and 1 != right, but this should test for other
// assumptions too.
uint32_t arrayIndex = swapchainCreateInfo.arraySize - (j * 2 + 1);
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = compositionHelper.MakeDefaultSubImage(swapchain, arrayIndex);
}
const std::vector<Cube> cubes = {Cube::Make({-1, 0, -2}), Cube::Make({1, 0, -2}), Cube::Make({0, -1, -2}), Cube::Make({0, 1, -2})};
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each slice of the array swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
for (uint32_t slice = 0; slice < (uint32_t)views.size(); slice++) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage,
projLayer->views[slice].subImage.imageArrayIndex, format);
const_cast<XrFovf&>(projLayer->views[slice].fov) = views[slice].fov;
const_cast<XrPosef&>(projLayer->views[slice].pose) = views[slice].pose;
GetGlobalData().graphicsPlugin->RenderView(projLayer->views[slice], swapchainImage, format, cubes);
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Wide Swapchain", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Wide Swapchain");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_wide.png",
"Uses a single wide texture for a projection layer.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
const auto totalWidth =
std::accumulate(viewProperties.begin(), viewProperties.end(), 0,
[](uint32_t l, const XrViewConfigurationView& r) { return l + r.recommendedImageRectWidth; });
// Because a single swapchain is being used for all views the maximum height must be used.
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create wide swapchain.
const XrSwapchain swapchain =
compositionHelper.CreateSwapchain(compositionHelper.DefaultColorSwapchainCreateInfo(totalWidth, maxHeight));
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
int x = 0;
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
XrSwapchainSubImage subImage = compositionHelper.MakeDefaultSubImage(swapchain, 0);
subImage.imageRect.offset = {x, 0};
subImage.imageRect.extent = {(int32_t)viewProperties[j].recommendedImageRectWidth,
(int32_t)viewProperties[j].recommendedImageRectHeight};
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = subImage;
x += subImage.imageRect.extent.width; // Each view is to the left of the previous view.
}
const std::vector<Cube> cubes = {Cube::Make({-1, 0, -2}), Cube::Make({1, 0, -2}), Cube::Make({0, -1, -2}), Cube::Make({0, 1, -2})};
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each view port of the wide swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage, 0, format);
for (size_t view = 0; view < views.size(); view++) {
const_cast<XrFovf&>(projLayer->views[view].fov) = views[view].fov;
const_cast<XrPosef&>(projLayer->views[view].pose) = views[view].pose;
GetGlobalData().graphicsPlugin->RenderView(projLayer->views[view], swapchainImage, format, cubes);
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Separate Swapchains", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Separate Swapchains");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_separate.png",
"Uses separate textures for each projection layer view.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
SimpleProjectionLayerHelper simpleProjectionLayerHelper(compositionHelper);
auto updateLayers = [&](const XrFrameState& frameState) {
simpleProjectionLayerHelper.UpdateProjectionLayer(frameState);
std::vector<XrCompositionLayerBaseHeader*> layers{simpleProjectionLayerHelper.GetProjectionLayer()};
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Quad Hands", "[composition][interactive]")
{
CompositionHelper compositionHelper("Quad Hands");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "quad_hands.png",
"10x10cm Quads labeled \'L\' and \'R\' should appear 10cm along the grip "
"positive Z in front of the center of 10cm cubes rendered at the controller "
"grip poses. "
"The quads should face you and be upright when the controllers are in "
"a thumbs-up pointing-into-screen pose. "
"Check that the quads are properly backface-culled, "
"that \'R\' is always rendered atop \'L\', "
"and both are atop the cubes when visible.");
const std::vector<XrPath> subactionPaths{StringToPath(compositionHelper.GetInstance(), "/user/hand/left"),
StringToPath(compositionHelper.GetInstance(), "/user/hand/right")};
XrActionSet actionSet;
XrAction gripPoseAction;
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy(actionSetInfo.actionSetName, "quad_hands");
strcpy(actionSetInfo.localizedActionSetName, "Quad Hands");
XRC_CHECK_THROW_XRCMD(xrCreateActionSet(compositionHelper.GetInstance(), &actionSetInfo, &actionSet));
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_POSE_INPUT;
strcpy(actionInfo.actionName, "grip_pose");
strcpy(actionInfo.localizedActionName, "Grip pose");
actionInfo.subactionPaths = subactionPaths.data();
actionInfo.countSubactionPaths = (uint32_t)subactionPaths.size();
XRC_CHECK_THROW_XRCMD(xrCreateAction(actionSet, &actionInfo, &gripPoseAction));
}
compositionHelper.GetInteractionManager().AddActionSet(actionSet);
XrPath simpleInteractionProfile = StringToPath(compositionHelper.GetInstance(), "/interaction_profiles/khr/simple_controller");
compositionHelper.GetInteractionManager().AddActionBindings(
simpleInteractionProfile,
{{
{gripPoseAction, StringToPath(compositionHelper.GetInstance(), "/user/hand/left/input/grip/pose")},
{gripPoseAction, StringToPath(compositionHelper.GetInstance(), "/user/hand/right/input/grip/pose")},
}});
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
SimpleProjectionLayerHelper simpleProjectionLayerHelper(compositionHelper);
// Spaces attached to the hand (subaction).
std::vector<XrSpace> gripSpaces;
// Create XrSpaces for each grip pose
for (XrPath subactionPath : subactionPaths) {
XrSpace space;
XrActionSpaceCreateInfo spaceCreateInfo{XR_TYPE_ACTION_SPACE_CREATE_INFO};
spaceCreateInfo.action = gripPoseAction;
spaceCreateInfo.subactionPath = subactionPath;
spaceCreateInfo.poseInActionSpace = {{0, 0, 0, 1}, {0, 0, 0}};
XRC_CHECK_THROW_XRCMD(xrCreateActionSpace(compositionHelper.GetSession(), &spaceCreateInfo, &space));
gripSpaces.push_back(std::move(space));
}
// Create 10x10cm L and R quads
XrCompositionLayerQuad* const leftQuadLayer =
compositionHelper.CreateQuadLayer(compositionHelper.CreateStaticSwapchainImage(CreateTextImage(64, 64, "L", 48)), gripSpaces[0],
0.1f, {Quat::Identity, {0, 0, 0.1f}});
XrCompositionLayerQuad* const rightQuadLayer =
compositionHelper.CreateQuadLayer(compositionHelper.CreateStaticSwapchainImage(CreateTextImage(64, 64, "R", 48)), gripSpaces[1],
0.1f, {Quat::Identity, {0, 0, 0.1f}});
interactiveLayerManager.AddLayer(leftQuadLayer);
interactiveLayerManager.AddLayer(rightQuadLayer);
const XrVector3f cubeSize{0.1f, 0.1f, 0.1f};
auto updateLayers = [&](const XrFrameState& frameState) {
std::vector<Cube> cubes;
for (const auto& space : gripSpaces) {
XrSpaceLocation location{XR_TYPE_SPACE_LOCATION};
if (XR_SUCCEEDED(
xrLocateSpace(space, simpleProjectionLayerHelper.GetLocalSpace(), frameState.predictedDisplayTime, &location))) {
if ((location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) &&
(location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)) {
cubes.emplace_back(Cube{location.pose, cubeSize});
}
}
}
simpleProjectionLayerHelper.UpdateProjectionLayer(frameState, cubes);
std::vector<XrCompositionLayerBaseHeader*> layers{simpleProjectionLayerHelper.GetProjectionLayer()};
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
TEST_CASE("Projection Mutable Field-of-View", "[composition][interactive]")
{
CompositionHelper compositionHelper("Projection Mutable Field-of-View");
InteractiveLayerManager interactiveLayerManager(compositionHelper, "projection_mutable.png",
"Uses mutable field-of-views for each projection layer view.");
compositionHelper.GetInteractionManager().AttachActionSets();
compositionHelper.BeginSession();
const XrSpace localSpace =
compositionHelper.CreateReferenceSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, XrPosef{Quat::Identity, {0, 0, 0}});
if (!compositionHelper.GetViewConfigurationProperties().fovMutable) {
return;
}
const std::vector<XrViewConfigurationView> viewProperties = compositionHelper.EnumerateConfigurationViews();
const auto totalWidth =
std::accumulate(viewProperties.begin(), viewProperties.end(), 0,
[](uint32_t l, const XrViewConfigurationView& r) { return l + r.recommendedImageRectWidth; });
// Because a single swapchain is being used for all views the maximum height must be used.
const auto maxHeight = std::max_element(viewProperties.begin(), viewProperties.end(),
[](const XrViewConfigurationView& l, const XrViewConfigurationView& r) {
return l.recommendedImageRectHeight < r.recommendedImageRectHeight;
})
->recommendedImageRectHeight;
// Create wide swapchain.
const XrSwapchain swapchain =
compositionHelper.CreateSwapchain(compositionHelper.DefaultColorSwapchainCreateInfo(totalWidth, maxHeight));
XrCompositionLayerProjection* const projLayer = compositionHelper.CreateProjectionLayer(localSpace);
int x = 0;
for (uint32_t j = 0; j < projLayer->viewCount; j++) {
XrSwapchainSubImage subImage = compositionHelper.MakeDefaultSubImage(swapchain, 0);
subImage.imageRect.offset = {x, 0};
subImage.imageRect.extent = {(int32_t)viewProperties[j].recommendedImageRectWidth,
(int32_t)viewProperties[j].recommendedImageRectHeight};
const_cast<XrSwapchainSubImage&>(projLayer->views[j].subImage) = subImage;
x += subImage.imageRect.extent.width; // Each view is to the left of the previous view.
}
const std::vector<Cube> cubes = {Cube::Make({-.2f, -.2f, -2}), Cube::Make({.2f, -.2f, -2}), Cube::Make({0, .1f, -2})};
const XrVector3f Forward{0, 0, 1};
XrQuaternionf roll180;
XrQuaternionf_CreateFromAxisAngle(&roll180, &Forward, MATH_PI);
auto updateLayers = [&](const XrFrameState& frameState) {
auto viewData = compositionHelper.LocateViews(localSpace, frameState.predictedDisplayTime);
const auto& viewState = std::get<XrViewState>(viewData);
std::vector<XrCompositionLayerBaseHeader*> layers;
if (viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT &&
viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) {
const auto& views = std::get<std::vector<XrView>>(viewData);
// Render into each view port of the wide swapchain using the projection layer view fov and pose.
compositionHelper.AcquireWaitReleaseImage(
swapchain, [&](const XrSwapchainImageBaseHeader* swapchainImage, uint64_t format) {
GetGlobalData().graphicsPlugin->ClearImageSlice(swapchainImage, 0, format);
for (size_t view = 0; view < views.size(); view++) {
// Copy over the provided FOV and pose but use 40% of the suggested FOV.
const_cast<XrFovf&>(projLayer->views[view].fov) = views[view].fov;
const_cast<XrPosef&>(projLayer->views[view].pose) = views[view].pose;
const_cast<float&>(projLayer->views[view].fov.angleUp) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleDown) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleLeft) *= 0.4f;
const_cast<float&>(projLayer->views[view].fov.angleRight) *= 0.4f;
// Render using a 180 degree roll on Z which effectively creates a flip on both the X and Y axis.
XrCompositionLayerProjectionView rolled = projLayer->views[view];
XrQuaternionf_Multiply(&rolled.pose.orientation, &roll180, &views[view].pose.orientation);
GetGlobalData().graphicsPlugin->RenderView(rolled, swapchainImage, format, cubes);
// After rendering, report a flipped FOV on X and Y without the 180 degree roll, which has the same
// effect. This switcheroo is necessary since rendering with flipped FOV will result in an inverted
// winding causing normally hidden triangles to be visible and visible triangles to be hidden.
const_cast<float&>(projLayer->views[view].fov.angleUp) = -projLayer->views[view].fov.angleUp;
const_cast<float&>(projLayer->views[view].fov.angleDown) = -projLayer->views[view].fov.angleDown;
const_cast<float&>(projLayer->views[view].fov.angleLeft) = -projLayer->views[view].fov.angleLeft;
const_cast<float&>(projLayer->views[view].fov.angleRight) = -projLayer->views[view].fov.angleRight;
}
});
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(projLayer));
}
return interactiveLayerManager.EndFrame(frameState, layers);
};
RenderLoop(compositionHelper.GetSession(), updateLayers).Loop();
}
} // namespace Conformance
| 56.088548
| 146
| 0.636832
|
JoeLudwig
|
283a80924b2defc573734b3ff42e7e7384c9cffb
| 9,532
|
cpp
|
C++
|
modules/base/rendering/renderablecartesianaxes.cpp
|
nbartzokas/OpenSpace
|
9df1e9b4821fade185b6e0a31b7cce1e67752a44
|
[
"MIT"
] | null | null | null |
modules/base/rendering/renderablecartesianaxes.cpp
|
nbartzokas/OpenSpace
|
9df1e9b4821fade185b6e0a31b7cce1e67752a44
|
[
"MIT"
] | null | null | null |
modules/base/rendering/renderablecartesianaxes.cpp
|
nbartzokas/OpenSpace
|
9df1e9b4821fade185b6e0a31b7cce1e67752a44
|
[
"MIT"
] | null | null | null |
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* 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 <modules/base/rendering/renderablecartesianaxes.h>
#include <modules/base/basemodule.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/updatestructures.h>
#include <openspace/documentation/verifier.h>
#include <ghoul/glm.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/opengl/programobject.h>
namespace {
constexpr const char* ProgramName = "CartesianAxesProgram";
const int NVertexIndices = 6;
constexpr openspace::properties::Property::PropertyInfo XColorInfo = {
"XColor",
"X Color",
"This value determines the color of the x axis."
};
constexpr openspace::properties::Property::PropertyInfo YColorInfo = {
"YColor",
"Y Color",
"This value determines the color of the y axis."
};
constexpr openspace::properties::Property::PropertyInfo ZColorInfo = {
"ZColor",
"Z Color",
"This value determines the color of the z axis."
};
} // namespace
namespace openspace {
documentation::Documentation RenderableCartesianAxes::Documentation() {
using namespace documentation;
return {
"CartesianAxesProgram",
"base_renderable_cartesianaxes",
{
{
XColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
XColorInfo.description
},
{
YColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
YColorInfo.description
},
{
ZColorInfo.identifier,
new DoubleVector4Verifier,
Optional::Yes,
ZColorInfo.description
}
}
};
}
RenderableCartesianAxes::RenderableCartesianAxes(const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _program(nullptr)
, _xColor(
XColorInfo,
glm::vec4(0.f, 0.f, 0.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
, _yColor(
YColorInfo,
glm::vec4(0.f, 1.f, 0.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
, _zColor(
ZColorInfo,
glm::vec4(0.f, 0.f, 1.f, 1.f),
glm::vec4(0.f),
glm::vec4(1.f)
)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableCartesianAxes"
);
if (dictionary.hasKey(XColorInfo.identifier)) {
_xColor = dictionary.value<glm::vec4>(XColorInfo.identifier);
}
_xColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_xColor);
if (dictionary.hasKey(XColorInfo.identifier)) {
_yColor = dictionary.value<glm::vec4>(YColorInfo.identifier);
}
_yColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_yColor);
if (dictionary.hasKey(ZColorInfo.identifier)) {
_zColor = dictionary.value<glm::vec4>(ZColorInfo.identifier);
}
_zColor.setViewOption(properties::Property::ViewOptions::Color);
addProperty(_zColor);
}
bool RenderableCartesianAxes::isReady() const {
bool ready = true;
ready &= (_program != nullptr);
return ready;
}
void RenderableCartesianAxes::initializeGL() {
_program = BaseModule::ProgramObjectManager.request(
ProgramName,
[]() -> std::unique_ptr<ghoul::opengl::ProgramObject> {
return global::renderEngine.buildRenderProgram(
ProgramName,
absPath("${MODULE_BASE}/shaders/axes_vs.glsl"),
absPath("${MODULE_BASE}/shaders/axes_fs.glsl")
);
}
);
glGenVertexArrays(1, &_vaoId);
glGenBuffers(1, &_vBufferId);
glGenBuffers(1, &_iBufferId);
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
std::vector<Vertex> vertices({
Vertex{0.f, 0.f, 0.f},
Vertex{1.f, 0.f, 0.f},
Vertex{0.f, 1.f, 0.f},
Vertex{0.f, 0.f, 1.f}
});
std::vector<int> indices = {
0, 1,
0, 2,
0, 3
};
glBindVertexArray(_vaoId);
glBindBuffer(GL_ARRAY_BUFFER, _vBufferId);
glBufferData(
GL_ARRAY_BUFFER,
vertices.size() * sizeof(Vertex),
vertices.data(),
GL_STATIC_DRAW
);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
indices.size() * sizeof(int),
indices.data(),
GL_STATIC_DRAW
);
}
void RenderableCartesianAxes::deinitializeGL() {
glDeleteVertexArrays(1, &_vaoId);
_vaoId = 0;
glDeleteBuffers(1, &_vBufferId);
_vBufferId = 0;
glDeleteBuffers(1, &_iBufferId);
_iBufferId = 0;
BaseModule::ProgramObjectManager.release(
ProgramName,
[](ghoul::opengl::ProgramObject* p) {
global::renderEngine.removeRenderProgram(p);
}
);
_program = nullptr;
}
void RenderableCartesianAxes::render(const RenderData& data, RendererTasks&){
_program->activate();
const glm::dmat4 modelTransform =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
glm::dmat4(data.modelTransform.rotation) *
glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale));
const glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() *
modelTransform;
_program->setUniform("modelViewTransform", glm::mat4(modelViewTransform));
_program->setUniform("projectionTransform", data.camera.projectionMatrix());
_program->setUniform("xColor", _xColor);
_program->setUniform("yColor", _yColor);
_program->setUniform("zColor", _zColor);
// Saves current state:
GLboolean isBlendEnabled = glIsEnabledi(GL_BLEND, 0);
GLboolean isLineSmoothEnabled = glIsEnabled(GL_LINE_SMOOTH);
GLfloat currentLineWidth;
glGetFloatv(GL_LINE_WIDTH, ¤tLineWidth);
GLenum blendEquationRGB, blendEquationAlpha, blendDestAlpha,
blendDestRGB, blendSrcAlpha, blendSrcRGB;
glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRGB);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDestAlpha);
glGetIntegerv(GL_BLEND_DST_RGB, &blendDestRGB);
glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha);
glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRGB);
// Changes GL state:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnablei(GL_BLEND, 0);
glEnable(GL_LINE_SMOOTH);
glBindVertexArray(_vaoId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferId);
glDrawElements(GL_LINES, NVertexIndices, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
_program->deactivate();
// Restores GL State
glLineWidth(currentLineWidth);
glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha);
glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha);
if (!isBlendEnabled) {
glDisablei(GL_BLEND, 0);
}
if (!isLineSmoothEnabled) {
glDisable(GL_LINE_SMOOTH);
}
}
} // namespace openspace
| 34.536232
| 90
| 0.593999
|
nbartzokas
|
283afec9ab13eba507692de14055621e68232683
| 3,020
|
hpp
|
C++
|
QuantExt/qle/instruments/makecds.hpp
|
PiotrSiejda/Engine
|
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
|
[
"BSD-3-Clause"
] | 1
|
2021-03-30T17:24:17.000Z
|
2021-03-30T17:24:17.000Z
|
QuantExt/qle/instruments/makecds.hpp
|
zhangjiayin/Engine
|
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
|
[
"BSD-3-Clause"
] | null | null | null |
QuantExt/qle/instruments/makecds.hpp
|
zhangjiayin/Engine
|
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
|
[
"BSD-3-Clause"
] | 1
|
2022-02-07T02:04:10.000Z
|
2022-02-07T02:04:10.000Z
|
/*
Copyright (C) 2017 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*
Copyright (C) 2014 Jose Aparicio
Copyright (C) 2014 Peter Caspers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file makecds.hpp
\brief Helper class to instantiate standard market cds.
\ingroup instruments
*/
#ifndef quantext_makecds_hpp
#define quantext_makecds_hpp
#include <boost/optional.hpp>
#include <qle/instruments/creditdefaultswap.hpp>
namespace QuantExt {
using namespace QuantLib;
//! helper class
/*! This class provides a more comfortable way
to instantiate standard cds.
\bug support last period dc
\ingroup instruments
*/
class MakeCreditDefaultSwap {
public:
MakeCreditDefaultSwap(const Period& tenor, const Real couponRate);
MakeCreditDefaultSwap(const Date& termDate, const Real couponRate);
operator CreditDefaultSwap() const;
operator boost::shared_ptr<CreditDefaultSwap>() const;
MakeCreditDefaultSwap& withUpfrontRate(Real);
MakeCreditDefaultSwap& withSide(Protection::Side);
MakeCreditDefaultSwap& withNominal(Real);
MakeCreditDefaultSwap& withCouponTenor(Period);
MakeCreditDefaultSwap& withDayCounter(DayCounter&);
// MakeCreditDefaultSwap& withLastPeriodDayCounter(DayCounter&);
MakeCreditDefaultSwap& withPricingEngine(const boost::shared_ptr<PricingEngine>&);
private:
Protection::Side side_;
Real nominal_;
boost::optional<Period> tenor_;
boost::optional<Date> termDate_;
Period couponTenor_;
Real couponRate_;
Real upfrontRate_;
DayCounter dayCounter_;
// DayCounter lastPeriodDayCounter_;
boost::shared_ptr<PricingEngine> engine_;
};
} // namespace QuantExt
#endif
| 33.555556
| 86
| 0.76755
|
PiotrSiejda
|
283cf5bab703ddbfe5d27d122222b8ffcb2343d6
| 86,167
|
cpp
|
C++
|
dev/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | null | null | null |
dev/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | null | null | null |
dev/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp
|
jeikabu/lumberyard
|
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
|
[
"AML"
] | null | null | null |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include "InstanceDataHierarchy.h"
#include <AzCore/std/bind/bind.h>
#include <AzCore/std/functional.h>
#include <AzCore/std/sort.h>
#include <AzCore/Serialization/Utils.h>
#include <AzCore/Math/MathUtils.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Debug/Profiler.h>
#include <AzCore/RTTI/AttributeReader.h>
#include <AzCore/Serialization/DynamicSerializableField.h>
#include <AzCore/Script/ScriptProperty.h>
#include <AzCore/Math/Crc.h>
#include <AzCore/Serialization/EditContextConstants.inl>
#include "ComponentEditor.hxx"
#include "PropertyEditorAPI.h"
#include <AzToolsFramework/ToolsComponents/TransformComponent.h>
namespace
{
AZ::Edit::Attribute* FindAttributeInNode(AzToolsFramework::InstanceDataNode* node, AZ::Edit::AttributeId attribId)
{
if (!node)
{
return nullptr;
}
AZ::Edit::Attribute* attr{};
const AZ::Edit::ElementData* elementEditData = node->GetElementEditMetadata();
if (elementEditData)
{
attr = elementEditData->FindAttribute(attribId);
}
// Attempt to look up the attribute on the node reflected class data.
// This look up is done via AZ::SerializeContext::ClassData -> AZ::Edit::ClassData -> EditorData element
if (!attr)
{
if (const AZ::SerializeContext::ClassData* classData = node->GetClassMetadata())
{
if (const auto* editClassData = classData->m_editData)
{
if (const auto* classEditorData = editClassData->FindElementData(AZ::Edit::ClassElements::EditorData))
{
attr = classEditorData->FindAttribute(attribId);
}
}
}
}
return attr;
}
template<typename ... Args>
AZStd::string GetStringFromAttributeWithParams(AzToolsFramework::InstanceDataNode* node, AZ::Edit::Attribute* attribute, Args&& ... params)
{
if (!node || !attribute)
{
return "";
}
// Read the string from the attribute found.
AZStd::string label;
for (size_t instIndex = 0; instIndex < node->GetNumInstances(); ++instIndex)
{
AzToolsFramework::PropertyAttributeReader reader(node->GetInstance(instIndex), attribute);
if (reader.Read<AZStd::string>(label, AZStd::forward<Args>(params) ...))
{
return label;
}
}
return "";
}
AZStd::string GetIndexedStringFromAttribute(AzToolsFramework::InstanceDataNode* parentNode, AzToolsFramework::InstanceDataNode* attributeNode, AZ::Edit::AttributeId attribId, int siblingIndex)
{
AZ::Edit::Attribute* attribute = FindAttributeInNode(attributeNode, attribId);
return GetStringFromAttributeWithParams(parentNode, attribute, siblingIndex);
}
AZStd::string GetStringFromAttribute(AzToolsFramework::InstanceDataNode* node, AZ::Edit::AttributeId attribId)
{
AZ::Edit::Attribute* attribute = FindAttributeInNode(node, attribId);
return GetStringFromAttributeWithParams(node, attribute);
}
template<typename Type>
Type GetFromAttribute(AzToolsFramework::InstanceDataNode* node, AZ::Edit::AttributeId attribId)
{
if (!node)
{
return Type();
}
AZ::Edit::Attribute* attr{};
const AZ::Edit::ElementData* elementEditData = node->GetElementEditMetadata();
if (elementEditData)
{
attr = elementEditData->FindAttribute(attribId);
}
// Attempt to look up the attribute on the node reflected class data.
// This look up is done via AZ::SerializeContext::ClassData -> AZ::Edit::ClassData -> EditorData element
if (!attr)
{
if (const AZ::SerializeContext::ClassData* classData = node->GetClassMetadata())
{
if (const auto* editClassData = classData->m_editData)
{
if (const auto* classEditorData = editClassData->FindElementData(AZ::Edit::ClassElements::EditorData))
{
attr = classEditorData->FindAttribute(attribId);
}
}
}
}
if (!attr)
{
return Type();
}
// Read the value from the attribute found.
Type retVal = Type();
for (size_t instIndex = 0; instIndex < node->GetNumInstances(); ++instIndex)
{
AzToolsFramework::PropertyAttributeReader reader(node->GetInstance(instIndex), attr);
if (reader.Read<Type>(retVal))
{
return retVal;
}
}
return Type();
}
AZStd::string GetDisplayLabel(AzToolsFramework::InstanceDataNode* node, int siblingIndex = 0)
{
if (!node)
{
return "";
}
AZStd::string label;
// We want to check to see if a name override was provided by our first real
// non-container parent.
//
// 'real' basically means something that is actually going to display.
//
// If we don't have a parent override, then we can take a look at applying out internal name override.
AzToolsFramework::InstanceDataNode* parentNode = node->GetParent();
while (parentNode)
{
bool nonContainerNodeFound = !parentNode->GetClassMetadata() || !parentNode->GetClassMetadata()->m_container;
if (nonContainerNodeFound)
{
const bool isSlicePushUI = false;
AzToolsFramework::NodeDisplayVisibility visibility = CalculateNodeDisplayVisibility((*parentNode), isSlicePushUI);
nonContainerNodeFound = (visibility == AzToolsFramework::NodeDisplayVisibility::Visible);
}
label = GetStringFromAttribute(parentNode, AZ::Edit::Attributes::ChildNameLabelOverride);
if (!label.empty() || nonContainerNodeFound)
{
break;
}
parentNode = parentNode->GetParent();
}
// If our parent isn't controlling us. Fall back to whatever we want to be called
if (label.empty())
{
label = GetStringFromAttribute(node, AZ::Edit::Attributes::NameLabelOverride);
}
if (label.empty())
{
parentNode = node;
do
{
parentNode = parentNode->GetParent();
}
while (parentNode && parentNode->GetClassMetadata() && parentNode->GetClassMetadata()->m_container);
// trying to get per-item name provided by real parent
label = GetIndexedStringFromAttribute(parentNode, node->GetParent(), AZ::Edit::Attributes::IndexedChildNameLabelOverride, siblingIndex);
}
return label;
}
}
namespace AzToolsFramework
{
//-----------------------------------------------------------------------------
void* ResolvePointer(void* ptr, const AZ::SerializeContext::ClassElement& classElement, const AZ::SerializeContext& context)
{
if (classElement.m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER)
{
// In the case of pointer-to-pointer, we'll deference.
ptr = *(void**)(ptr);
// Pointer-to-pointer fields may be base class / polymorphic, so cast pointer to actual type,
// safe for passing as 'this' to member functions.
if (ptr && classElement.m_azRtti)
{
AZ::Uuid actualClassId = classElement.m_azRtti->GetActualUuid(ptr);
if (actualClassId != classElement.m_typeId)
{
const AZ::SerializeContext::ClassData* classData = context.FindClassData(actualClassId);
if (classData)
{
ptr = classElement.m_azRtti->Cast(ptr, classData->m_azRtti->GetTypeId());
}
}
}
}
return ptr;
}
//-----------------------------------------------------------------------------
// InstanceDataNode
//-----------------------------------------------------------------------------
//! Read the value of the node.
//! Clones the node's value and returns its address into valuePtr. ValuePtr will be overridden.
bool InstanceDataNode::ReadRaw(void*& valuePtr, AZ::TypeId valueType)
{
void* firstInstanceCast = (GetSerializeContext()->DownCast(FirstInstance(), GetClassMetadata()->m_typeId, valueType));
if (!firstInstanceCast)
{
AZ_Error("InstanceDataHierarchy", false, "Could not downcast from the value typeid %s to the instance typeid %s required.",
GetClassMetadata()->m_typeId.ToString<AZStd::string>().c_str(),
valueType.ToString<AZStd::string>().c_str());
return false;
}
valuePtr = firstInstanceCast;
// check all instance values are the same
return std::all_of(m_instances.begin(), m_instances.end(), [this, valueType, firstInstanceCast](void* instance)
{
void* instanceCast = (GetSerializeContext()->DownCast(instance, GetClassMetadata()->m_typeId, valueType));
if (!instanceCast)
{
AZ_Error("InstanceDataHierarchy", false, "Could not downcast from the value typeid %s to the instance typeid %s required.",
GetClassMetadata()->m_typeId.ToString<AZStd::string>().c_str(),
valueType.ToString<AZStd::string>().c_str());
return false;
}
return (GetClassMetadata()->m_serializer && GetClassMetadata()->m_serializer->CompareValueData(instanceCast, firstInstanceCast)) ||
(!GetClassMetadata()->m_serializer && instanceCast == firstInstanceCast);
});
}
//! Write the value into the node.
void InstanceDataNode::WriteRaw(const void* valuePtr, AZ::TypeId valueType)
{
for (void* instance : m_instances)
{
// If type does not match, bail
if (valueType != GetClassMetadata()->m_typeId)
{
AZ_Error("InstanceDataHierarchy", false, "Could not downcast from the value typeid %s to the instance typeid %s required.",
GetClassMetadata()->m_typeId.ToString<AZStd::string>().c_str(),
valueType.ToString<AZStd::string>().c_str());
continue;
}
if (valueType == GetClassMetadata()->m_typeId)
{
GetSerializeContext()->CloneObjectInplace(instance, valuePtr, GetClassMetadata()->m_typeId);
}
}
}
void* InstanceDataNode::GetInstance(size_t idx) const
{
void* ptr = m_instances[idx];
if (m_classElement)
{
ptr = ResolvePointer(ptr, *m_classElement, *m_context);
}
return ptr;
}
//-----------------------------------------------------------------------------
void** InstanceDataNode::GetInstanceAddress(size_t idx) const
{
AZ_Assert(m_classElement && (m_classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER), "You can not call GetInstanceAddress() on a node that is not of a pointer type!");
return reinterpret_cast<void**>(m_instances[idx]);
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::CreateContainerElement(const SelectClassCallback& selectClass, const FillDataClassCallback& fillData)
{
AZ::SerializeContext::IDataContainer* container = m_classData->m_container;
AZ_Assert(container, "This node is NOT a container node!");
const AZ::SerializeContext::ClassElement* containerClassElement = container->GetElement(container->GetDefaultElementNameCrc());
AZ_Assert(containerClassElement != NULL, "We should have a valid default element in the container, otherwise we don't know what elements to make!");
if (containerClassElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER)
{
// TEMP until it's safe to pass 0 as type id
const AZ::Uuid& baseTypeId = containerClassElement->m_azRtti ? containerClassElement->m_azRtti->GetTypeId() : AZ::AzTypeInfo<int>::Uuid();
// ask the GUI and use to create one (if there is choice)
const AZ::SerializeContext::ClassData* classData = selectClass(containerClassElement->m_typeId, baseTypeId, m_context);
if (classData && classData->m_factory)
{
for (size_t i = 0; i < m_instances.size(); ++i)
{
// reserve entry in the container
void* dataAddress = container->ReserveElement(GetInstance(i), containerClassElement);
// create entry
void* newDataAddress = classData->m_factory->Create(classData->m_name);
AZ_Assert(newDataAddress, "Faliled to create new element for the continer!");
// cast to base type (if needed)
void* basePtr = m_context->DownCast(newDataAddress, classData->m_typeId, containerClassElement->m_typeId, classData->m_azRtti, containerClassElement->m_azRtti);
AZ_Assert(basePtr != NULL, "Can't cast container element %s to %s, make sure classes are registered in the system and not generics!", classData->m_name, containerClassElement->m_name);
*reinterpret_cast<void**>(dataAddress) = basePtr; // store the pointer in the class
/// Store the element in the container
container->StoreElement(GetInstance(i), dataAddress);
}
return true;
}
}
else if (containerClassElement->m_typeId == AZ::SerializeTypeInfo<AZ::DynamicSerializableField>::GetUuid())
{
// Dynamic serializable fields are capable of wrapping any type. Each one within a container can technically contain
// an entirely different type from the others. We're going to assume that we're getting here via
// ScriptPropertyGenericClassArray and that it strictly uses one type.
const AZ::SerializeContext::ClassData* classData = m_context->FindClassData(AZ::SerializeTypeInfo<AZ::DynamicSerializableField>::GetUuid());
const AZ::Edit::ElementData* element = m_parent->m_classData->m_editData->FindElementData(AZ::Edit::ClassElements::EditorData);
if (element)
{
// Grab the AttributeMemberFunction used to get the Uuid type of the element wrapped by the DynamicSerializableField
AZ::Edit::Attribute* assetTypeAttribute = element->FindAttribute(AZ::Edit::Attributes::DynamicElementType);
if (assetTypeAttribute)
{
//Invoke the function we just grabbed and pull the class data based on that Uuid
AZ_Assert(m_parent->GetNumInstances() <= 1, "ScriptPropertyGenericClassArray should not have more than one DynamicSerializableField vector");
AZ::AttributeReader elementTypeIdReader(m_parent->GetInstance(0), assetTypeAttribute);
AZ::Uuid dynamicClassUuid;
if (elementTypeIdReader.Read<AZ::Uuid>(dynamicClassUuid))
{
const AZ::SerializeContext::ClassData* dynamicClassData = m_context->FindClassData(dynamicClassUuid);
//Construct a new element based on the Uuid we just grabbed and wrap it in a DynamicSerializeableField for storage
if (classData && classData->m_factory &&
dynamicClassData && dynamicClassData->m_factory)
{
for (size_t i = 0; i < m_instances.size(); ++i)
{
// Reserve entry in the container
void* dataAddress = container->ReserveElement(GetInstance(i), containerClassElement);
// Create DynamicSerializeableField entry
void* newDataAddress = classData->m_factory->Create(classData->m_name);
AZ_Assert(newDataAddress, "Faliled to create new element for the continer!");
// Create dynamic element and populate entry with it
AZ::DynamicSerializableField* dynamicFieldDesc = reinterpret_cast<AZ::DynamicSerializableField*>(newDataAddress);
void* newDynamicData = dynamicClassData->m_factory->Create(dynamicClassData->m_name);
dynamicFieldDesc->m_data = newDynamicData;
dynamicFieldDesc->m_typeId = dynamicClassData->m_typeId;
/// Store the entry in the container
*reinterpret_cast<AZ::DynamicSerializableField*>(dataAddress) = *dynamicFieldDesc;
container->StoreElement(GetInstance(i), dataAddress);
}
return true;
}
}
}
}
}
else
{
for (size_t i = 0; i < m_instances.size(); ++i)
{
// check capacity of container before attempting to reserve an element
if (container->IsFixedCapacity() && !container->IsSmartPointer() && container->Size(GetInstance(i)) >= container->Capacity(GetInstance(i)))
{
AZ_Warning("Serializer", false, "Cannot add additional entries to the container as it is at its capacity of %zu", container->Capacity(GetInstance(i)));
return false;
}
// reserve entry in the container
void* dataAddress = container->ReserveElement(GetInstance(i), containerClassElement);
bool isAssociative = false;
ReadAttribute(AZ::Edit::Attributes::ShowAsKeyValuePairs, isAssociative, true);
bool noDefaultData = isAssociative || (containerClassElement->m_flags & AZ::SerializeContext::ClassElement::FLG_NO_DEFAULT_VALUE) != 0;
if (!dataAddress || !fillData(dataAddress, containerClassElement, noDefaultData, m_context) && noDefaultData) // fill default data
{
return false;
}
/// Store the element in the container
container->StoreElement(GetInstance(i), dataAddress);
}
return true;
}
return false;
}
bool InstanceDataNode::ChildMatchesAddress(const InstanceDataNode::Address& elementAddress) const
{
if (elementAddress.empty())
{
return false;
}
for (const InstanceDataNode& child : m_children)
{
if (elementAddress == child.ComputeAddress())
{
return true;
}
if (child.ChildMatchesAddress(elementAddress))
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void InstanceDataNode::MarkNewVersusComparison()
{
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::New);
}
//-----------------------------------------------------------------------------
void InstanceDataNode::MarkDifferentVersusComparison()
{
if (ShouldComparisonBeIgnored())
{
return;
}
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::Differs);
}
//-----------------------------------------------------------------------------
void InstanceDataNode::MarkRemovedVersusComparison()
{
m_comparisonFlags &= ~static_cast<AZ::u32>(ComparisonFlags::New);
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::Removed);
}
//-----------------------------------------------------------------------------
void InstanceDataNode::ClearComparisonData()
{
m_comparisonFlags = static_cast<AZ::u32>(ComparisonFlags::None);
m_comparisonNode = nullptr;
}
//-----------------------------------------------------------------------------
void InstanceDataNode::SetIgnoreComparisonResult(bool ignoreResult)
{
m_ignoreComparisonResult = ignoreResult;
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::IsNewVersusComparison() const
{
return 0 != (m_comparisonFlags & static_cast<AZ::u32>(ComparisonFlags::New));
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::IsDifferentVersusComparison() const
{
return 0 != (m_comparisonFlags & static_cast<AZ::u32>(ComparisonFlags::Differs));
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::IsRemovedVersusComparison() const
{
return 0 != (m_comparisonFlags & static_cast<AZ::u32>(ComparisonFlags::Removed));
}
//-----------------------------------------------------------------------------
const InstanceDataNode* InstanceDataNode::GetComparisonNode() const
{
return m_comparisonNode;
}
bool InstanceDataNode::HasChangesVersusComparison(bool includeChildren) const
{
if (m_comparisonFlags)
{
return true;
}
if (includeChildren)
{
for (auto child : m_children)
{
if (child.HasChangesVersusComparison(includeChildren))
{
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
bool InstanceDataNode::ShouldComparisonBeIgnored() const
{
return m_ignoreComparisonResult;
}
//-----------------------------------------------------------------------------
InstanceDataNode::Address InstanceDataNode::ComputeAddress() const
{
Address addressStack;
addressStack.reserve(32);
addressStack.push_back(m_identifier);
InstanceDataNode* parent = m_parent;
while (parent)
{
addressStack.push_back(parent->m_identifier);
parent = parent->m_parent;
}
return addressStack;
}
AZ::Edit::Attribute* InstanceDataNode::FindAttribute(AZ::Edit::AttributeId nameCrc) const
{
AZ::Edit::Attribute* attribute = nullptr;
// Edit Data > Class Element > Class Data in terms of specificity to what we're editing, so prioritize their attributes accordingly
if (m_elementEditData)
{
attribute = m_elementEditData->FindAttribute(nameCrc);
}
if (!attribute && m_classElement)
{
attribute = m_classElement->FindAttribute(nameCrc);
}
if (!attribute && m_classData)
{
attribute = m_classData->FindAttribute(nameCrc);
}
return attribute;
}
//-----------------------------------------------------------------------------
// InstanceDataHierarchy
//-----------------------------------------------------------------------------
InstanceDataHierarchy::InstanceDataHierarchy()
: m_curParentNode(nullptr)
, m_isMerging(false)
, m_nodeDiscarded(false)
, m_valueComparisonFunction(DefaultValueComparisonFunction)
{
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::AddRootInstance(void* instance, const AZ::Uuid& classId)
{
m_rootInstances.emplace_back(instance, classId);
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::AddComparisonInstance(void* instance, const AZ::Uuid& classId)
{
m_comparisonInstances.emplace_back(instance, classId);
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::ContainsRootInstance(const void* instance) const
{
for (InstanceDataArray::const_iterator it = m_rootInstances.begin(); it != m_rootInstances.end(); ++it)
{
if (it->m_instance == instance)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::SetBuildFlags(AZ::u8 flags)
{
m_buildFlags = flags;
}
void InstanceDataHierarchy::EnumerateUIElements(InstanceDataNode* node, DynamicEditDataProvider dynamicEditDataProvider)
{
for (InstanceDataNode& child : node->m_children)
{
EnumerateUIElements(&child, dynamicEditDataProvider);
}
AZ::Edit::ClassData* nodeEditData = node->GetClassMetadata() ? node->GetClassMetadata()->m_editData : nullptr;
if (nodeEditData)
{
const AZ::Edit::ElementData* groupData = nullptr;
const AZ::Edit::ElementData* previousData = nullptr;
for (auto& element : nodeEditData->m_elements)
{
if (element.IsClassElement() && element.m_elementId == AZ::Edit::ClassElements::Group)
{
groupData = (element.m_description && element.m_description[0]) ? &element : nullptr;
continue;
}
//create ui elements in their relative edit context positions
if (element.m_elementId == AZ::Edit::ClassElements::UIElement)
{
//if there is no matching, previous element, assume the UI element comes first
m_childIndexOverride = 0;
if (previousData)
{
//search for matching sibling element data by name
auto it = AZStd::find_if(
node->m_children.begin(),
node->m_children.end(),
[previousData](const InstanceDataNode& otherNode) {
return otherNode.m_classElement->m_editData == previousData;
});
if (it != node->m_children.end())
{
//if there is element data matching the previous entry, place the UI element after it
m_childIndexOverride = static_cast<int>(AZStd::distance(node->m_children.begin(), it)) + 1;
}
}
// For every UIElement, generate an InstanceDataNode pointed at our instance with the corresponding attributes
for (size_t i = 0, numInstances = node->GetNumInstances(); i < numInstances; ++i)
{
m_supplementalElementData.push_back();
auto& serializeFieldElement = m_supplementalElementData.back();
serializeFieldElement.m_name = element.m_description;
serializeFieldElement.m_nameCrc = AZ::Crc32(element.m_description);
serializeFieldElement.m_azRtti = nullptr;
serializeFieldElement.m_dataSize = sizeof(void*);
serializeFieldElement.m_offset = 0;
serializeFieldElement.m_typeId = AZ::Uuid::CreateNull();
serializeFieldElement.m_editData = &element;
serializeFieldElement.m_flags = AZ::SerializeContext::ClassElement::FLG_UI_ELEMENT;
m_curParentNode = node;
BeginNode(node->GetInstance(i), nullptr, &serializeFieldElement, dynamicEditDataProvider);
m_curParentNode->m_groupElementData = groupData;
EndNode();
}
}
previousData = &element;
}
m_childIndexOverride = -1;
m_curParentNode = nullptr;
}
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::Build(AZ::SerializeContext* sc, unsigned int accessFlags, DynamicEditDataProvider dynamicEditDataProvider, ComponentEditor* editorParent)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
AZ_Assert(sc, "sc can't be NULL!");
AZ_Assert(m_rootInstances.size() > 0, "No root instances have been added to this hierarchy!");
m_curParentNode = NULL;
m_isMerging = false;
m_instances.clear();
m_children.clear();
m_matched = true;
m_nodeDiscarded = false;
m_context = sc;
m_comparisonHierarchies.clear();
m_supplementalEditData.clear();
AZ::SerializeContext::EnumerateInstanceCallContext callContext(
AZStd::bind(&InstanceDataHierarchy::BeginNode, this, AZStd::placeholders::_1, AZStd::placeholders::_2, AZStd::placeholders::_3, dynamicEditDataProvider),
AZStd::bind(&InstanceDataHierarchy::EndNode, this),
sc,
AZ::SerializeContext::ENUM_ACCESS_FOR_READ,
nullptr
);
sc->EnumerateInstanceConst(
&callContext
, m_rootInstances[0].m_instance
, m_rootInstances[0].m_classId
, nullptr
, nullptr
);
for (size_t i = 1; i < m_rootInstances.size(); ++i)
{
m_curParentNode = NULL;
m_isMerging = true;
m_matched = false;
sc->EnumerateInstanceConst(
&callContext
, m_rootInstances[i].m_instance
, m_rootInstances[i].m_classId
, nullptr
, nullptr
);
}
EnumerateUIElements(this, dynamicEditDataProvider);
// Fixup our container edit data first, as we may specifically affect comparison data
bool foundRootParent = false;
FixupEditData(this, 0, foundRootParent);
bool dataIdentical = RefreshComparisonData(accessFlags, dynamicEditDataProvider);
if (editorParent)
{
editorParent->SetComponentOverridden(!dataIdentical);
}
}
namespace InstanceDataHierarchyHelper
{
template <class T>
bool GetEnumStringRepresentation(AZStd::string& value, const AZ::Edit::ElementData* data, void* instance, const AZ::Uuid& storageTypeId)
{
if (storageTypeId == azrtti_typeid<T>())
{
for (const AZ::AttributePair& attributePair : data->m_attributes)
{
PropertyAttributeReader reader(instance, attributePair.second);
AZ::Edit::EnumConstant<T> enumPair;
if (reader.Read<AZ::Edit::EnumConstant<T>>(enumPair))
{
T* enumValue = reinterpret_cast<T*>(instance);
if (enumPair.m_value == *enumValue)
{
value = enumPair.m_description;
return true;
}
}
}
}
return false;
}
// Try GetEnumStringRepresentation<Type> on all of the specified types
template <class T1, class T2, class... TRest>
bool GetEnumStringRepresentation(AZStd::string& value, const AZ::Edit::ElementData* data, void* instance, const AZ::Uuid& storageTypeId)
{
return GetEnumStringRepresentation<T1>(value, data, instance, storageTypeId) || GetEnumStringRepresentation<T2, TRest...>(value, data, instance, storageTypeId);
}
bool GetValueStringRepresentation(const InstanceDataNode* node, AZStd::string& value)
{
if (!node || !node->GetClassMetadata())
{
return false;
}
AZ::SerializeContext* serializeContext = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext);
// Get our enum string value from the edit context if we're actually an enum
AZ::Uuid enumId;
if (serializeContext && node->ReadAttribute(AZ::Edit::InternalAttributes::EnumType, enumId))
{
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
const AZ::Edit::ElementData* data = editContext->GetEnumElementData(enumId);
if (data)
{
// Check all underlying enum storage types
if (GetEnumStringRepresentation<
AZ::u8, AZ::u16, AZ::u32, AZ::u64,
AZ::s8, AZ::s16, AZ::s32, AZ::s64>(value, data, node->FirstInstance(), node->GetClassMetadata()->m_typeId))
{
return true;
}
}
}
}
// Just use our underlying AZStd::string if we're a string
if (node->GetClassMetadata()->m_typeId == azrtti_typeid<AZStd::string>())
{
value = *reinterpret_cast<AZStd::string*>(node->FirstInstance());
return true;
}
// Fall back on using our serializer's DataToText
if (node->GetElementMetadata())
{
if (auto& serializer = node->GetClassMetadata()->m_serializer)
{
AZ::IO::MemoryStream memStream(node->FirstInstance(), 0, node->GetElementMetadata()->m_dataSize);
AZStd::vector<char> buffer;
AZ::IO::ByteContainerStream<AZStd::vector<char>> outStream(&buffer);
serializer->DataToText(memStream, outStream, false);
value = AZStd::string(buffer.data(), buffer.size());
return !value.empty();
}
}
return false;
}
}
void InstanceDataHierarchy::FixupComparisonData(InstanceDataNode* node, bool& foundRootParent)
{
if (!foundRootParent)
{
bool isRootParentId = false;
if (node->GetClassMetadata() && node->GetClassMetadata()->m_typeId == AZ::AzTypeInfo<AZ::EntityId>::Uuid())
{
if (node->GetElementMetadata()->m_nameCrc == AzToolsFramework::Components::TransformComponent::GetParentEntityCRC())
{
isRootParentId = true;
}
}
if (isRootParentId && !ShouldComparisonBeIgnored())
{
node->SetIgnoreComparisonResult(true);
foundRootParent = true;
}
}
else if (node->GetParent() && node->GetParent()->ShouldComparisonBeIgnored())
{
node->SetIgnoreComparisonResult(true);
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::FixupEditData(InstanceDataNode* node, int siblingIdx, bool& foundRootParent)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
bool mergeElementEditData = node->m_classElement && node->m_classElement->m_editData && node->GetElementEditMetadata() != node->m_classElement->m_editData;
bool mergeContainerEditData = node->m_parent && node->m_parent->m_classData->m_container && node->m_parent->GetElementEditMetadata() && (node->m_classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER) == 0;
node->SetIgnoreComparisonResult(false);
FixupComparisonData(node, foundRootParent);
bool showAsKeyValue = false;
if (!(m_buildFlags & Flags::IgnoreKeyValuePairs))
{
// Default to showing as key values if we're an associative interface, but always respect ShowAsKeyValuePairs if it's specified
showAsKeyValue = node->m_parent && node->m_parent->m_classData->m_container && node->m_parent->m_classData->m_container->GetAssociativeContainerInterface();
node->ReadAttribute(AZ::Edit::Attributes::ShowAsKeyValuePairs, showAsKeyValue);
}
if (mergeElementEditData || mergeContainerEditData || showAsKeyValue)
{
AZStd::string label;
if (!showAsKeyValue)
{
label = GetDisplayLabel(node, siblingIdx);
}
// Grab a copy of our instances if we might need to move them to a key/value attribute.
// We need a copy because the current node may well be replaced in its entirety by one of its children.
AZStd::vector<void*> elementInstances;
if (showAsKeyValue)
{
elementInstances = node->m_instances;
}
// If our node is a pair, and we're not enumerating multiple instances, respect showAsKeyValue and promote the value data element with a label matching our instance's string representation
if (showAsKeyValue && node->m_children.size() == 2 && node->GetNumInstances() == 1)
{
// Make sure we can get a valid string representation before doing the conversion
if (label.empty())
{
showAsKeyValue = InstanceDataHierarchyHelper::GetValueStringRepresentation(&node->m_children.front(), label);
}
}
m_supplementalEditData.push_back();
AZ::Edit::ElementData* editData = &m_supplementalEditData.back().m_editElementData;
if (node->GetElementEditMetadata())
{
*editData = *node->GetElementEditMetadata();
}
node->m_elementEditData = editData;
// Flag our new key node with our original instances for any future element modification
if (showAsKeyValue)
{
node->m_identifier = AZ::Crc32(label.c_str());
auto attribute = aznew AZ::AttributeContainerType<AZStd::vector<void*>>(AZStd::move(elementInstances));
m_supplementalEditData.back().m_attributes.emplace_back(attribute); // Ensure the attribute gets cleaned up
editData->m_attributes.emplace_back(
AZ::Edit::InternalAttributes::ElementInstances,
attribute);
}
if (mergeElementEditData)
{
for (AZ::Edit::AttributeArray::const_iterator elemAttrIter = node->m_classElement->m_editData->m_attributes.begin(); elemAttrIter != node->m_classElement->m_editData->m_attributes.end(); ++elemAttrIter)
{
AZ::Edit::AttributeArray::iterator editAttrIter = editData->m_attributes.begin();
for (; editAttrIter != editData->m_attributes.end(); ++editAttrIter)
{
if (elemAttrIter->first == editAttrIter->first)
{
break;
}
}
if (editAttrIter == editData->m_attributes.end())
{
editData->m_attributes.push_back(*elemAttrIter);
}
}
}
if (mergeContainerEditData || !label.empty())
{
m_supplementalEditData.back().m_displayLabel = label.empty() ? AZStd::string::format("[%d]", siblingIdx) : label;
editData->m_description = nullptr;
editData->m_name = m_supplementalEditData.back().m_displayLabel.c_str();
if (mergeContainerEditData)
{
InstanceDataNode* container = node->m_parent;
for (AZ::Edit::AttributeArray::const_iterator containerAttrIter = container->GetElementEditMetadata()->m_attributes.begin(); containerAttrIter != container->GetElementEditMetadata()->m_attributes.end(); ++containerAttrIter)
{
if (!containerAttrIter->second->m_describesChildren)
{
continue;
}
AZ::Edit::AttributeArray::iterator editAttrIter = editData->m_attributes.begin();
for (; editAttrIter != editData->m_attributes.end(); ++editAttrIter)
{
if (containerAttrIter->first == editAttrIter->first)
{
break;
}
}
if (editAttrIter == editData->m_attributes.end())
{
editData->m_attributes.push_back(*containerAttrIter);
}
}
}
}
}
int childIdx = 0;
for (NodeContainer::iterator it = node->m_children.begin(); it != node->m_children.end(); ++it)
{
FixupEditData(&(*it), childIdx++, foundRootParent);
}
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::BeginNode(void* ptr, const AZ::SerializeContext::ClassData* classData, const AZ::SerializeContext::ClassElement* classElement, DynamicEditDataProvider dynamicEditDataProvider)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
const AZ::Edit::ElementData* elementEditData = nullptr;
if (classElement)
{
// Find the correct element edit data to use
elementEditData = classElement->m_editData;
if (dynamicEditDataProvider)
{
void* objectPtr = ResolvePointer(ptr, *classElement, *m_context);
const AZ::Edit::ElementData* labelData = dynamicEditDataProvider(objectPtr, classData);
if (labelData)
{
elementEditData = labelData;
}
}
else if (!m_editDataOverrides.empty())
{
const EditDataOverride& editDataOverride = m_editDataOverrides.back();
void* objectPtr = ResolvePointer(ptr, *classElement, *m_context);
void* overridingInstance = editDataOverride.m_overridingInstance;
const AZ::SerializeContext::ClassElement* overridingElementData = editDataOverride.m_overridingNode->GetElementMetadata();
if (overridingElementData)
{
overridingInstance = ResolvePointer(overridingInstance, *overridingElementData, *m_context);
}
if (classData)
{
const AZ::Edit::ElementData* useData = editDataOverride.m_override(overridingInstance, objectPtr, classData->m_typeId);
if (useData)
{
elementEditData = useData;
}
}
}
}
InstanceDataNode* node = NULL;
// Extra steps need to be taken when we are merging
if (m_isMerging)
{
if (!m_curParentNode)
{
// Only accept root instances that are of the same type
if (classData && classData->m_typeId == m_classData->m_typeId)
{
node = this;
}
}
else
{
// Search through the parent's class elements to find a match
for (NodeContainer::iterator it = m_curParentNode->m_children.begin(); it != m_curParentNode->m_children.end(); ++it)
{
InstanceDataNode* subElement = &(*it);
if (!subElement->m_matched &&
subElement->m_classElement->m_nameCrc == classElement->m_nameCrc &&
subElement->m_classData == classData &&
(subElement->m_elementEditData == elementEditData ||
(subElement->m_elementEditData && elementEditData &&
subElement->m_elementEditData->m_name && elementEditData->m_name &&
azstricmp(subElement->m_elementEditData->m_name, elementEditData->m_name) == 0)))
{
node = subElement;
break;
}
}
}
if (node)
{
// Add the new instance pointer to the list of mapped instances
node->m_instances.push_back(ptr);
// Flag the node as already matched for this pass.
node->m_matched = true;
// prepare the node's children for matching
// we set them all to false so that when we unwind the depth-first enumeration,
// any unmatched nodes can be discarded.
for (NodeContainer::iterator it = node->m_children.begin(); it != node->m_children.end(); ++it)
{
it->m_matched = false;
}
}
else
{
// Reject the node and everything under it
m_nodeDiscarded = true;
return false;
}
}
else
{
// Not merging, just add anything being enumerated to the hierarchy.
if (!m_curParentNode)
{
node = this;
}
else
{
if (m_childIndexOverride >= 0)
{
auto position = m_curParentNode->m_children.begin();
AZStd::advance(position, m_childIndexOverride);
auto iterator = m_curParentNode->m_children.insert(position);
node = &(*iterator);
}
else
{
m_curParentNode->m_children.push_back();
node = &m_curParentNode->m_children.back();
}
}
node->m_instances.push_back(ptr);
node->m_classData = classData;
// ClassElement pointers for DynamicSerializableFields are temporaries, so we need
// to maintain it locally.
if (classElement && (classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_DYNAMIC_FIELD))
{
m_supplementalElementData.push_back(*classElement);
classElement = &m_supplementalElementData.back();
}
node->m_classElement = classElement;
node->m_elementEditData = elementEditData;
node->m_parent = m_curParentNode;
node->m_root = this;
node->m_context = m_context;
// Compute node's identifier, which is used to compute full address within a hierarchy.
if (m_curParentNode)
{
if (m_curParentNode->GetClassMetadata() && m_curParentNode->GetClassMetadata()->m_container)
{
if (classData)
{
// Within a container, use persistentId if available, otherwise use a CRC of name and container index.
AZ::SerializeContext::ClassPersistentId persistentId = classData->GetPersistentId(*m_context);
if (persistentId)
{
node->m_identifier = static_cast<Identifier>(persistentId(ResolvePointer(ptr, *classElement, *m_context)));
}
else
{
AZStd::string indexedName = AZStd::string::format("%s_%d", classData->m_name, m_curParentNode->m_children.size() - 1);
node->m_identifier = static_cast<Identifier>(AZ::Crc32(indexedName.c_str()));
}
}
}
else
{
// Not in a container, just use crc.
node->m_identifier = classElement->m_nameCrc;
}
}
else if (classData)
{
// Root level, use crc of class type.
node->m_identifier = AZ_CRC(classData->m_name);
}
AZ_Assert(node->m_identifier != InvalidIdentifier, "InstanceDataNode has an invalid identifier. Addressing will not be valid.");
}
// if our data contains dynamic edit data handler, push it on the stack
if (classData && classData->m_editData && classData->m_editData->m_editDataProvider)
{
m_editDataOverrides.push_back();
m_editDataOverrides.back().m_override = classData->m_editData->m_editDataProvider;
m_editDataOverrides.back().m_overridingInstance = ptr;
m_editDataOverrides.back().m_overridingNode = node;
}
// Resolve the group metadata for this element
AZ::Edit::ClassData* parentEditData = (node->GetParent() && node->GetParent()->GetClassMetadata()) ? node->GetParent()->GetClassMetadata()->m_editData : nullptr;
if (parentEditData)
{
// Dig through the class elements in the parent structure looking for groups. Apply the last group created
// to this node
const AZ::Edit::ElementData* groupData = nullptr;
for (const AZ::Edit::ElementData& elementData : parentEditData->m_elements)
{
if (node->m_elementEditData == &elementData) // this element matches this node
{
// Record the last found group data
node->m_groupElementData = groupData;
break;
}
else if (elementData.IsClassElement() && elementData.m_elementId == AZ::Edit::ClassElements::Group)
{
if (!elementData.m_description || !elementData.m_description[0])
{ // close the group
groupData = nullptr;
}
else
{
groupData = &elementData;
}
}
}
}
m_curParentNode = node;
return true;
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::EndNode()
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
AZ_Assert(m_curParentNode, "EndEnum called without a matching BeginNode call!");
if (!m_nodeDiscarded)
{
if (m_isMerging)
{
for (NodeContainer::iterator it = m_curParentNode->m_children.begin(); it != m_curParentNode->m_children.end(); )
{
// If we are merging and we did not match this node, remove it from the hierarchy.
if (!it->m_matched)
{
it = m_curParentNode->m_children.erase(it);
}
else
{
++it;
}
}
}
// if the node we are leaving pushed an edit data override, then pop it.
if (!m_editDataOverrides.empty() && m_editDataOverrides.back().m_overridingNode == m_curParentNode)
{
m_editDataOverrides.pop_back();
}
m_curParentNode = m_curParentNode->m_parent;
}
m_nodeDiscarded = false;
return true;
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::RefreshComparisonData(unsigned int accessFlags, DynamicEditDataProvider dynamicEditDataProvider)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
if (!m_root || m_comparisonInstances.empty())
{
return false;
}
bool allDataMatches = true;
// Clear comparison data.
AZStd::vector<InstanceDataNode*> stack;
stack.reserve(32);
stack.push_back(this);
while (!stack.empty())
{
InstanceDataNode* node = stack.back();
stack.pop_back();
node->ClearComparisonData();
for (auto childIterator = node->m_children.begin(); childIterator != node->m_children.end();)
{
// Remove any fake nodes that have been added
if (childIterator->IsRemovedVersusComparison())
{
childIterator = node->m_children.erase(childIterator);
}
else
{
stack.push_back(&(*childIterator));
++childIterator;
}
}
}
// Generate a hierarchy for the comparison instance.
m_comparisonHierarchies.clear();
for (const InstanceData& comparisonInstance : m_comparisonInstances)
{
AZ_Assert(comparisonInstance.m_classId == m_rootInstances[0].m_classId, "Compare instance type does not match root instance type.");
m_comparisonHierarchies.emplace_back(aznew InstanceDataHierarchy());
auto& comparisonHierarchy = m_comparisonHierarchies.back();
comparisonHierarchy->AddRootInstance(comparisonInstance.m_instance, comparisonInstance.m_classId);
comparisonHierarchy->Build(m_root->GetSerializeContext(), accessFlags, dynamicEditDataProvider);
// Compare the two hierarchies...
if (comparisonHierarchy->m_root)
{
AZStd::vector<AZ::u8> sourceBuffer, targetBuffer;
CompareHierarchies(comparisonHierarchy->m_root, m_root, sourceBuffer, targetBuffer, m_valueComparisonFunction, m_root->GetSerializeContext(),
// New node
[&allDataMatches](InstanceDataNode* targetNode, AZStd::vector<AZ::u8>& data)
{
(void)data;
if (!targetNode->IsNewVersusComparison())
{
targetNode->MarkNewVersusComparison();
allDataMatches = false;
}
},
// Removed node (container element).
[&allDataMatches](const InstanceDataNode* sourceNode, InstanceDataNode* targetNodeParent)
{
(void)sourceNode;
// Mark the parent as modified.
if (targetNodeParent)
{
// Insert a node to mark the removed element, with no data, but relating to the node in the source hierarchy.
targetNodeParent->m_children.push_back();
InstanceDataNode& removedMarker = targetNodeParent->m_children.back();
removedMarker = *sourceNode;
removedMarker.m_instances.clear();
removedMarker.m_children.clear();
removedMarker.m_comparisonNode = sourceNode;
removedMarker.m_parent = targetNodeParent;
removedMarker.m_root = targetNodeParent->m_root;
removedMarker.m_context = targetNodeParent->m_context;
removedMarker.MarkRemovedVersusComparison();
targetNodeParent->MarkDifferentVersusComparison();
}
allDataMatches = false;
},
// Changed node
[&allDataMatches](const InstanceDataNode* sourceNode, InstanceDataNode* targetNode,
AZStd::vector<AZ::u8>& sourceData, AZStd::vector<AZ::u8>& targetData)
{
(void)sourceData;
(void)targetData;
if (!targetNode->IsDifferentVersusComparison())
{
targetNode->m_comparisonNode = sourceNode;
targetNode->MarkDifferentVersusComparison();
}
allDataMatches = false;
}
);
}
}
return allDataMatches;
}
//-----------------------------------------------------------------------------
InstanceDataNode* InstanceDataHierarchy::FindNodeByAddress(const InstanceDataNode::Address& address) const
{
if (m_root && !address.empty())
{
if (m_root->m_identifier != address.back())
{
// If this hierarchy's root isn't the same as the root in the address (the last entry), not going to find it here
return nullptr;
}
else if (address.size() == 1)
{
// The only address in the list is the root node, matches root node
return m_root;
}
InstanceDataNode* currentNode = m_root;
size_t addressIndex = address.size() - 2;
while (currentNode)
{
InstanceDataNode* parent = currentNode;
currentNode = nullptr;
for (InstanceDataNode& child : parent->m_children)
{
if (child.m_identifier == address[addressIndex])
{
currentNode = &child;
if (addressIndex > 0)
{
--addressIndex;
break;
}
else
{
return currentNode;
}
}
}
}
}
return nullptr;
}
/// Locate a node by partial address (bfs to find closest match)
InstanceDataNode* InstanceDataHierarchy::FindNodeByPartialAddress(const InstanceDataNode::Address& address) const
{
// ensure we have atleast a root and a valid address to search
if (m_root && !address.empty())
{
AZStd::queue<InstanceDataNode*> children;
children.push(m_root);
// work our way down the hierarchy in a bfs search
size_t addressIndex = address.size() - 1;
while (children.size() > 0)
{
InstanceDataNode* curr = children.front();
children.pop();
// if we find property - move down the hierarchy
if (curr->m_identifier == address[addressIndex])
{
if (addressIndex > 0)
{
// clear existing list as we don't care about
// these elements anymore
while (!children.empty())
{
children.pop();
}
children.push(curr);
--addressIndex;
}
else
{
return curr;
}
}
// build fifo list of children to search
for (InstanceDataNode& child : curr->m_children)
{
children.push(&child);
}
}
}
return nullptr;
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::DefaultValueComparisonFunction(const InstanceDataNode* sourceNode, const InstanceDataNode* targetNode)
{
// special case - while its possible for instance comparisons to differ, if one has an instance, and the other does not, they are definitely
// not equal!
if (sourceNode->GetNumInstances() == 0)
{
if (targetNode->GetNumInstances() == 0)
{
return true;
}
return false;
}
else if (targetNode->GetNumInstances() == 0)
{
return false;
}
else if (!targetNode->m_classData || !sourceNode->m_classData)
{
return targetNode->m_classData == sourceNode->m_classData;
}
return targetNode->m_classData->m_serializer->CompareValueData(sourceNode->FirstInstance(), targetNode->FirstInstance());
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::SetValueComparisonFunction(const ValueComparisonFunction& function)
{
m_valueComparisonFunction = function ? function : DefaultValueComparisonFunction;
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::CompareHierarchies(const InstanceDataNode* sourceNode, InstanceDataNode* targetNode,
const ValueComparisonFunction& valueComparisonFunction,
AZ::SerializeContext* context,
NewNodeCB newNodeCallback,
RemovedNodeCB removedNodeCallback,
ChangedNodeCB changedNodeCallback)
{
AZ_Assert(sourceNode->GetSerializeContext() == targetNode->GetSerializeContext(),
"Attempting to compare hierarchies from different serialization contexts.");
AZStd::vector<AZ::u8> sourceBuffer, targetBuffer;
CompareHierarchies(sourceNode, targetNode, sourceBuffer, targetBuffer, valueComparisonFunction, context, newNodeCallback, removedNodeCallback, changedNodeCallback);
}
//-----------------------------------------------------------------------------
void InstanceDataHierarchy::CompareHierarchies(const InstanceDataNode* sourceNode, InstanceDataNode* targetNode,
AZStd::vector<AZ::u8>& tempSourceBuffer,
AZStd::vector<AZ::u8>& tempTargetBuffer,
const ValueComparisonFunction& valueComparisonFunction,
AZ::SerializeContext* context,
NewNodeCB newNodeCallback,
RemovedNodeCB removedNodeCallback,
ChangedNodeCB changedNodeCallback)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
targetNode->m_comparisonNode = sourceNode;
if (!targetNode->m_classData || !sourceNode->m_classData)
{
return;
}
else if (targetNode->m_classData->m_typeId == sourceNode->m_classData->m_typeId)
{
if (targetNode->m_classData->m_container)
{
// Find elements in the container that have been added or modified.
for (InstanceDataNode& targetElementNode : targetNode->m_children)
{
if (targetElementNode.IsRemovedVersusComparison())
{
continue; // Don't compare removal placeholders.
}
const InstanceDataNode* sourceNodeMatch = nullptr;
for (const InstanceDataNode& sourceElementNode : sourceNode->m_children)
{
if (sourceElementNode.m_identifier == targetElementNode.m_identifier)
{
sourceNodeMatch = &sourceElementNode;
break;
}
}
if (sourceNodeMatch)
{
// The element exists, drill down.
CompareHierarchies(sourceNodeMatch, &targetElementNode, tempSourceBuffer, tempTargetBuffer, valueComparisonFunction, context,
newNodeCallback, removedNodeCallback, changedNodeCallback);
}
else
{
// This is a new element in the container.
AZStd::vector<AZ::u8> buffer;
AZ::IO::ByteContainerStream<AZStd::vector<AZ::u8> > stream(&buffer);
if (!AZ::Utils::SaveObjectToStream(stream, AZ::ObjectStream::ST_BINARY, targetElementNode.GetInstance(0), targetElementNode.m_classData->m_typeId, context, targetElementNode.m_classData))
{
AZ_Assert(false, "Unable to serialize class %s, SaveObjectToStream() failed.", targetElementNode.m_classData->m_name);
}
// Mark targetElementNode and all of its children, and their children, and their... as new
AZStd::vector<InstanceDataNode*> stack;
stack.reserve(32);
stack.push_back(&targetElementNode);
while (!stack.empty())
{
InstanceDataNode* node = stack.back();
stack.pop_back();
newNodeCallback(node, buffer);
// Don't do the children if the current node represents a component since it will add as one whole thing
if (!node->GetClassMetadata() || !node->GetClassMetadata()->m_azRtti || !node->GetClassMetadata()->m_azRtti->IsTypeOf(AZ::Component::RTTI_Type()))
{
for (InstanceDataNode& child : node->m_children)
{
stack.push_back(&child);
}
}
}
}
}
// Find elements that've been removed.
for (const InstanceDataNode& sourceElementNode : sourceNode->m_children)
{
bool isRemoved = true;
for (InstanceDataNode& targetElementNode : targetNode->m_children)
{
if (sourceElementNode.m_identifier == targetElementNode.m_identifier)
{
isRemoved = false;
break;
}
}
if (isRemoved)
{
removedNodeCallback(&sourceElementNode, targetNode);
}
}
}
else if (targetNode->m_classData->m_serializer)
{
AZ_Assert(targetNode->m_classData == sourceNode->m_classData, "Comparison raw data for mismatched types.");
if (!valueComparisonFunction(sourceNode, targetNode))
{
// This is a leaf element (has a direct serializer), so it's a data change.
tempSourceBuffer.clear();
tempTargetBuffer.clear();
AZ::IO::ByteContainerStream<AZStd::vector<AZ::u8> > sourceStream(&tempSourceBuffer), targetStream(&tempTargetBuffer);
targetNode->m_classData->m_serializer->Save(targetNode->GetInstance(0), targetStream);
sourceNode->m_classData->m_serializer->Save(sourceNode->GetInstance(0), sourceStream);
changedNodeCallback(sourceNode, targetNode, tempSourceBuffer, tempTargetBuffer);
}
}
else
{
// This isn't a container; just drill down on child elements.
if (targetNode->m_children.size() == sourceNode->m_children.size())
{
auto targetElementIt = targetNode->m_children.begin();
auto sourceElementIt = sourceNode->m_children.begin();
while (targetElementIt != targetNode->m_children.end())
{
CompareHierarchies(&(*sourceElementIt), &(*targetElementIt), tempSourceBuffer, tempTargetBuffer, valueComparisonFunction, context,
newNodeCallback, removedNodeCallback, changedNodeCallback);
++sourceElementIt;
++targetElementIt;
}
}
else
{
AZ_Error("Serializer", targetNode->m_children.size() == sourceNode->m_children.size(),
"Non-container elements have mismatched sub-element counts. This a recoverable error, "
"but the entire sub-hierarchy will be considered differing as no further drill-down is possible.");
tempSourceBuffer.clear();
tempTargetBuffer.clear();
changedNodeCallback(sourceNode, targetNode, tempSourceBuffer, tempTargetBuffer);
}
}
}
}
//-----------------------------------------------------------------------------
bool InstanceDataHierarchy::CopyInstanceData(const InstanceDataNode* sourceNode,
InstanceDataNode* targetNode,
AZ::SerializeContext* context,
ContainerChildNodeBeingRemovedCB containerChildNodeBeingRemovedCB,
ContainerChildNodeBeingCreatedCB containerChildNodeBeingCreatedCB,
const InstanceDataNode::Address& filterElementAddress)
{
AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework);
if (sourceNode->ShouldComparisonBeIgnored())
{
return true;
}
if (!context)
{
AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
AZ_Assert(context, "Failed to retrieve application serialization context");
}
const AZ::SerializeContext::ClassData* sourceClass = sourceNode->GetClassMetadata();
const AZ::SerializeContext::ClassData* targetClass = targetNode->GetClassMetadata();
if (!sourceClass || !targetClass)
{
return false;
}
if (sourceClass->m_typeId == targetClass->m_typeId)
{
// Drill down and apply adds/removes/copies as we go.
bool result = true;
if (targetClass->m_eventHandler)
{
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
targetClass->m_eventHandler->OnWriteBegin(targetNode->GetInstance(i));
}
}
if (sourceClass->m_serializer)
{
// These are leaf elements, we can just copy directly.
AZStd::vector<AZ::u8> sourceBuffer;
AZ::IO::ByteContainerStream<decltype(sourceBuffer)> sourceStream(&sourceBuffer);
sourceClass->m_serializer->Save(sourceNode->GetInstance(0), sourceStream);
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
sourceStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
targetClass->m_serializer->Load(targetNode->GetInstance(i), sourceStream, sourceClass->m_version);
}
}
else
{
// Storage to track elements to be added or removed to reflect differences between
// source and target container contents.
using InstancePair = AZStd::pair<void*, void*>;
AZStd::vector<InstancePair> elementsToRemove;
AZStd::vector<const InstanceDataNode*> elementsToAdd;
// If we're operating on a container, we need to identify any items in the target
// node that don't exist in the source, and remove them.
if (sourceClass->m_container)
{
for (auto targetChildIter = targetNode->GetChildren().begin(); targetChildIter != targetNode->GetChildren().end(); )
{
InstanceDataNode& targetChild = *targetChildIter;
// Skip placeholders, or if we're filtering for a different element.
if ((targetChild.IsRemovedVersusComparison()) ||
(!filterElementAddress.empty() && filterElementAddress != targetChild.ComputeAddress()))
{
++targetChildIter;
continue;
}
bool sourceFound = false;
bool removedElement = false;
for (const InstanceDataNode& sourceChild : sourceNode->GetChildren())
{
if (sourceChild.IsRemovedVersusComparison())
{
continue;
}
if (sourceChild.m_identifier == targetChild.m_identifier)
{
sourceFound = true;
break;
}
}
if (!sourceFound)
{
AZ_Assert(targetClass->m_container, "Hierarchy mismatch occurred, but not on a container element.");
if (targetClass->m_container)
{
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
elementsToRemove.push_back(AZStd::make_pair(targetNode->GetInstance(i), targetChild.m_instances[i]));
}
if (containerChildNodeBeingRemovedCB)
{
containerChildNodeBeingRemovedCB(&targetChild);
}
// The child hierarchy node can be deleted. We'll free the actual container elements in a safe manner below.
targetChildIter = targetNode->GetChildren().erase(targetChildIter);
removedElement = true;
}
}
if (!removedElement)
{
++targetChildIter;
}
}
}
// Recursively deep-copy any differences.
for (const InstanceDataNode& sourceChild : sourceNode->GetChildren())
{
bool matchedChild = false;
// Skip placeholders, or if we're filtering for an element that isn't the sourceChild or one of it's descendants.
if ((sourceChild.IsRemovedVersusComparison()) ||
(!filterElementAddress.empty() && filterElementAddress != sourceChild.ComputeAddress() && !sourceChild.ChildMatchesAddress(filterElementAddress)))
{
continue;
}
// For each source child, locate the respective target child and drill down.
for (InstanceDataNode& targetChild : targetNode->GetChildren())
{
if (targetChild.IsRemovedVersusComparison())
{
continue;
}
if (targetChild.m_identifier == sourceChild.m_identifier)
{
matchedChild = true;
const AZ::SerializeContext::ClassData* targetClassData = targetChild.GetClassMetadata();
const AZ::SerializeContext::ClassData* sourceClassData = sourceChild.GetClassMetadata();
// are these proxy nodes?
if (!targetClassData && !sourceClassData)
{
continue;
}
else if (targetClassData->m_typeId != sourceClassData->m_typeId)
{
AZStd::string sourceTypeId;
AZStd::string targetTypeId;
sourceClassData->m_typeId.ToString(sourceTypeId);
targetClassData->m_typeId.ToString(targetTypeId);
AZ_Error("Serializer", false, "Nodes with same identifier are not of the same serializable type: types \"%s\" : %s and \"%s\" : %s.",
sourceClassData->m_name, sourceTypeId.c_str(), targetClassData->m_name, targetTypeId.c_str());
return false;
}
// Recurse on child elements.
if (!CopyInstanceData(&sourceChild, &targetChild, context, containerChildNodeBeingRemovedCB, containerChildNodeBeingCreatedCB, filterElementAddress))
{
result = false;
break;
}
}
}
if (matchedChild)
{
continue;
}
// The target node was not found.
// This occurs if the source is a container, and contains an element that the target does not.
AZ_Assert(targetClass->m_container, "Hierarchy mismatch occurred, but not on a container element.");
if (result && targetClass->m_container)
{
elementsToAdd.push_back(&sourceChild);
}
}
// After iterating through all children to apply changes, it's now safe to commit element removals and additions.
// Containers may grow during additions, or shift during removals, so we can't do it while iterating and recursing
// on elements to apply data differences.
//
// Apply element removals.
//
// Sort element removals in reverse memory order for compatibility with contiguous-memory containers.
AZStd::sort(elementsToRemove.begin(), elementsToRemove.end(),
[](const InstancePair& lhs, const InstancePair& rhs)
{
return rhs.second < lhs.second;
}
);
// Finally, remove elements from the target container that weren't present in the source.
for (const auto& pair : elementsToRemove)
{
targetClass->m_container->RemoveElement(pair.first, pair.second, context);
}
//
// Apply element additions.
//
// After iterating through all children to apply changes, it's now safe to commit element additions.
// Containers may grow/reallocate, so we can't do it while iterating.
for (const InstanceDataNode* sourceChildToAdd : elementsToAdd)
{
if (containerChildNodeBeingCreatedCB)
{
containerChildNodeBeingCreatedCB(sourceChildToAdd, targetNode);
}
// Serialize out the entire source element.
AZStd::vector<AZ::u8> sourceBuffer;
AZ::IO::ByteContainerStream<decltype(sourceBuffer)> sourceStream(&sourceBuffer);
bool savedToStream = AZ::Utils::SaveObjectToStream(
sourceStream, AZ::DataStream::ST_BINARY, sourceChildToAdd->GetInstance(0), context, sourceChildToAdd->GetClassMetadata());
(void)savedToStream;
AZ_Assert(savedToStream, "Failed to save source element to data stream.");
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
// Add a new element to the target container.
void* targetInstance = targetNode->GetInstance(i);
void* targetPointer = targetClass->m_container->ReserveElement(targetInstance, sourceChildToAdd->m_classElement);
AZ_Assert(targetPointer, "Failed to allocate container element");
if (sourceChildToAdd->GetClassMetadata() && sourceChildToAdd->m_classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER)
{
// It's a container of pointers, so allocate a new target class instance.
AZ_Assert(sourceChildToAdd->GetClassMetadata()->m_factory != nullptr, "We are attempting to create '%s', but no factory is provided! Either provide factory or change data member '%s' to value not pointer!", sourceNode->m_classData->m_name, sourceNode->m_classElement->m_name);
void* newTargetPointer = sourceChildToAdd->m_classData->m_factory->Create(sourceChildToAdd->m_classData->m_name);
(void)newTargetPointer;
void* basePtr = context->DownCast(
newTargetPointer,
sourceChildToAdd->m_classData->m_typeId,
sourceChildToAdd->m_classElement->m_typeId,
sourceChildToAdd->m_classData->m_azRtti,
sourceChildToAdd->m_classElement->m_azRtti);
AZ_Assert(basePtr != nullptr, sourceClass->m_container
? "Can't cast container element %s(0x%x) to %s, make sure classes are registered in the system and not generics!"
: "Can't cast %s(0x%x) to %s, make sure classes are registered in the system and not generics!"
, sourceChildToAdd->m_classElement->m_name ? sourceChildToAdd->m_classElement->m_name : "NULL"
, sourceChildToAdd->m_classElement->m_nameCrc
, sourceChildToAdd->m_classData->m_name);
// Store ptr to the new instance in the container element.
*reinterpret_cast<void**>(targetPointer) = basePtr;
targetPointer = newTargetPointer;
}
// Deserialize in-place.
sourceStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
bool loadedFromStream = AZ::Utils::LoadObjectFromStreamInPlace(
sourceStream, context, sourceChildToAdd->GetClassMetadata(), targetPointer, AZ::ObjectStream::FilterDescriptor(AZ::Data::AssetFilterNoAssetLoading));
(void)loadedFromStream;
AZ_Assert(loadedFromStream, "Failed to copy element to target.");
// Some containers, such as AZStd::map require you to call StoreElement to actually consider the element part of the structure
// Since the container is unable to put an uninitialized element into its tree until the key is known
targetClass->m_container->StoreElement(targetInstance, targetPointer);
}
}
}
if (targetClass->m_eventHandler)
{
for (size_t i = 0; i < targetNode->GetNumInstances(); ++i)
{
targetClass->m_eventHandler->OnWriteEnd(targetNode->GetInstance(i));
}
}
return result;
}
return false;
}
//-----------------------------------------------------------------------------
} // namespace Property System
| 44.097748
| 304
| 0.527325
|
jeikabu
|
283d232e0cebdcfedf5e47e2e5af2153ff8b129a
| 7,202
|
cpp
|
C++
|
inference-engine/tests/functional/plugin/gna/Import_export_tests/import_export_act_conv_act.cpp
|
JOCh1958/openvino
|
070201feeec5550b7cf8ec5a0ffd72dc879750be
|
[
"Apache-2.0"
] | null | null | null |
inference-engine/tests/functional/plugin/gna/Import_export_tests/import_export_act_conv_act.cpp
|
JOCh1958/openvino
|
070201feeec5550b7cf8ec5a0ffd72dc879750be
|
[
"Apache-2.0"
] | 16
|
2021-04-19T13:03:04.000Z
|
2022-02-21T13:06:50.000Z
|
inference-engine/tests/functional/plugin/gna/Import_export_tests/import_export_act_conv_act.cpp
|
JOCh1958/openvino
|
070201feeec5550b7cf8ec5a0ffd72dc879750be
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include <memory>
#include <tuple>
#include <vector>
#include <string>
#include <fstream>
#include <ie_core.hpp>
#include <ie_layouts.h>
#include "shared_test_classes/base/layer_test_utils.hpp"
#include "functional_test_utils/blob_utils.hpp"
#include "ngraph_functions/utils/ngraph_helpers.hpp"
#include "ngraph_functions/builders.hpp"
typedef std::tuple<
std::vector<size_t>, // Input shape
InferenceEngine::Precision, // Network Precision
std::string, // Target Device
std::map<std::string, std::string>, // Export Configuration
std::map<std::string, std::string> // Import Configuration
> exportImportNetworkParams;
namespace LayerTestsDefinitions {
class ImportActConvActTest : public testing::WithParamInterface<exportImportNetworkParams>,
public LayerTestsUtils::LayerTestsCommon {
public:
static std::string getTestCaseName(testing::TestParamInfo<exportImportNetworkParams> obj) {
std::vector<size_t> inputShape;
InferenceEngine::Precision netPrecision;
std::string targetDevice;
std::map<std::string, std::string> exportConfiguration;
std::map<std::string, std::string> importConfiguration;
std::tie(inputShape, netPrecision, targetDevice, exportConfiguration, importConfiguration) = obj.param;
std::ostringstream result;
result << "netPRC=" << netPrecision.name() << "_";
result << "targetDevice=" << targetDevice << "_";
for (auto const &configItem : exportConfiguration) {
result << "_exportConfigItem=" << configItem.first << "_" << configItem.second;
}
for (auto const &configItem : importConfiguration) {
result << "_importConfigItem=" << configItem.first << "_" << configItem.second;
}
result << CommonTestUtils::vec2str(inputShape);
return result.str();
}
void Run() override {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
configuration.insert(exportConfiguration.begin(), exportConfiguration.end());
LoadNetwork();
GenerateInputs();
Infer();
executableNetwork.Export("exported_model.blob");
for (auto const &configItem : importConfiguration) {
configuration[configItem.first] = configItem.second;
}
std::fstream inputStream("exported_model.blob", std::ios_base::in | std::ios_base::binary);
if (inputStream.fail()) {
FAIL() << "Cannot open file to import model: exported_model.blob";
}
auto importedNetwork = core->ImportNetwork(inputStream, targetDevice, configuration);
// Generate inputs
std::vector<InferenceEngine::Blob::Ptr> inputs;
auto inputsInfo = importedNetwork.GetInputsInfo();
auto functionParams = function->get_parameters();
for (int i = 0; i < functionParams.size(); ++i) {
const auto& param = functionParams[i];
const auto infoIt = inputsInfo.find(param->get_friendly_name());
GTEST_ASSERT_NE(infoIt, inputsInfo.cend());
const auto& info = infoIt->second;
auto blob = GenerateInput(*info);
inputs.push_back(blob);
}
// Infer imported network
InferenceEngine::InferRequest importInfer = importedNetwork.CreateInferRequest();
inputsInfo = importedNetwork.GetInputsInfo();
functionParams = function->get_parameters();
for (int i = 0; i < functionParams.size(); ++i) {
const auto& param = functionParams[i];
const auto infoIt = inputsInfo.find(param->get_friendly_name());
GTEST_ASSERT_NE(infoIt, inputsInfo.cend());
const auto& info = infoIt->second;
auto blob = inputs[i];
importInfer.SetBlob(info->name(), blob);
}
importInfer.Infer();
// Validate
auto expectedOutputs = CalculateRefs();
auto actualOutputs = std::vector<InferenceEngine::Blob::Ptr>{};
for (const auto &output : importedNetwork.GetOutputsInfo()) {
const auto &name = output.first;
actualOutputs.push_back(importInfer.GetBlob(name));
}
IE_ASSERT(actualOutputs.size() == expectedOutputs.size())
<< "nGraph interpreter has " << expectedOutputs.size() << " outputs, while IE " << actualOutputs.size();
Compare(expectedOutputs, actualOutputs);
}
protected:
void SetUp() override {
std::vector<size_t> inputShape;
InferenceEngine::Precision netPrecision;
std::tie(inputShape, netPrecision, targetDevice, exportConfiguration, importConfiguration) = this->GetParam();
auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision);
auto params = ngraph::builder::makeParams(ngPrc, {inputShape});
auto relu1 = std::make_shared<ngraph::opset1::Relu>(params[0]);
size_t num_out_channels = 8;
size_t kernel_size = 8;
std::vector<float> filter_weights = CommonTestUtils::generate_float_numbers(num_out_channels * inputShape[1] * kernel_size,
-0.2f, 0.2f);
auto conv = ngraph::builder::makeConvolution(relu1, ngPrc, { 1, kernel_size }, { 1, 1 }, { 0, 0 }, { 0, 0 }, { 1, 1 },
ngraph::op::PadType::VALID, num_out_channels, true, filter_weights);
auto relu2 = std::make_shared<ngraph::opset1::Relu>(conv);
ngraph::ResultVector results{std::make_shared<ngraph::opset1::Result>(relu2)};
function = std::make_shared<ngraph::Function>(results, params, "ExportImportNetwork");
}
private:
std::map<std::string, std::string> exportConfiguration;
std::map<std::string, std::string> importConfiguration;
};
TEST_P(ImportActConvActTest, CompareWithRefImpl) {
Run();
};
const std::vector<std::vector<size_t>> inputShape = {
{1, 1, 1, 240},
{1, 1, 1, 160},
{1, 2, 1, 80}
};
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32,
InferenceEngine::Precision::FP16
};
const std::vector<std::map<std::string, std::string>> exportConfigs = {
{
{"GNA_DEVICE_MODE", "GNA_SW_EXACT"}
}
};
const std::vector<std::map<std::string, std::string>> importConfigs = {
{
{"GNA_DEVICE_MODE", "GNA_SW_EXACT"}
}
};
INSTANTIATE_TEST_CASE_P(smoke_ImportActConvAct, ImportActConvActTest,
::testing::Combine(
::testing::ValuesIn(inputShape),
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_GNA),
::testing::ValuesIn(exportConfigs),
::testing::ValuesIn(importConfigs)),
ImportActConvActTest::getTestCaseName);
} // namespace LayerTestsDefinitions
| 40.234637
| 131
| 0.620383
|
JOCh1958
|
2841971e0bff9a57c920a04ac25df9ef4a1e9c4d
| 5,126
|
cpp
|
C++
|
GEvent.cpp
|
abishek-sampath/SDL-GameFramework
|
0194540851eeaff6b4563feefb8edae7ca868700
|
[
"MIT"
] | null | null | null |
GEvent.cpp
|
abishek-sampath/SDL-GameFramework
|
0194540851eeaff6b4563feefb8edae7ca868700
|
[
"MIT"
] | null | null | null |
GEvent.cpp
|
abishek-sampath/SDL-GameFramework
|
0194540851eeaff6b4563feefb8edae7ca868700
|
[
"MIT"
] | null | null | null |
#include "GEvent.h"
GEvent::GEvent() {
}
GEvent::~GEvent() {
//Do nothing
}
void GEvent::OnEvent(SDL_Event* event) {
switch(event->type) {
case SDL_KEYDOWN: {
OnKeyDown(event->key.keysym.sym,event->key.keysym.mod);
break;
}
case SDL_KEYUP: {
OnKeyUp(event->key.keysym.sym,event->key.keysym.mod);
break;
}
case SDL_MOUSEMOTION: {
OnMouseMove(event->motion.x,event->motion.y,event->motion.xrel,event->motion.yrel,(event->motion.state&SDL_BUTTON(SDL_BUTTON_LEFT))!=0,(event->motion.state&SDL_BUTTON(SDL_BUTTON_RIGHT))!=0,(event->motion.state&SDL_BUTTON(SDL_BUTTON_MIDDLE))!=0);
break;
}
case SDL_MOUSEBUTTONDOWN: {
switch(event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonDown(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonDown(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonDown(event->button.x,event->button.y);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP: {
switch(event->button.button) {
case SDL_BUTTON_LEFT: {
OnLButtonUp(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_RIGHT: {
OnRButtonUp(event->button.x,event->button.y);
break;
}
case SDL_BUTTON_MIDDLE: {
OnMButtonUp(event->button.x,event->button.y);
break;
}
}
break;
}
case SDL_JOYAXISMOTION: {
OnJoyAxis(event->jaxis.which,event->jaxis.axis,event->jaxis.value);
break;
}
case SDL_JOYBALLMOTION: {
OnJoyBall(event->jball.which,event->jball.ball,event->jball.xrel,event->jball.yrel);
break;
}
case SDL_JOYHATMOTION: {
OnJoyHat(event->jhat.which,event->jhat.hat,event->jhat.value);
break;
}
case SDL_JOYBUTTONDOWN: {
OnJoyButtonDown(event->jbutton.which,event->jbutton.button);
break;
}
case SDL_JOYBUTTONUP: {
OnJoyButtonUp(event->jbutton.which,event->jbutton.button);
break;
}
case SDL_QUIT: {
OnExit();
break;
}
case SDL_SYSWMEVENT: {
//Ignore
break;
}
// case SDL_VIDEORESIZE: {
// OnResize(event->resize.w,event->resize.h);
// break;
// }
// case SDL_VIDEOEXPOSE: {
// OnExpose();
// break;
// }
default: {
OnUser(event->user.type,event->user.code,event->user.data1,event->user.data2);
break;
}
}
}
void GEvent::OnInputFocus() {
//Pure virtual, do nothing
}
void GEvent::OnInputBlur() {
//Pure virtual, do nothing
}
void GEvent::OnKeyDown(SDL_Keycode &sym, Uint16 &mod) {
//Pure virtual, do nothing
}
void GEvent::OnKeyUp(SDL_Keycode &sym, Uint16 &mod) {
//Pure virtual, do nothing
}
void GEvent::OnMouseFocus() {
//Pure virtual, do nothing
}
void GEvent::OnMouseBlur() {
//Pure virtual, do nothing
}
void GEvent::OnMouseMove(int mX, int mY, int relX, int relY, bool Left,bool Right,bool Middle) {
//Pure virtual, do nothing
}
void GEvent::OnMouseWheel(bool Up, bool Down) {
//Pure virtual, do nothing
}
void GEvent::OnLButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnLButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnRButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnRButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnMButtonDown(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnMButtonUp(int mX, int mY) {
//Pure virtual, do nothing
}
void GEvent::OnJoyAxis(Uint8 which,Uint8 axis,Sint16 value) {
//Pure virtual, do nothing
}
void GEvent::OnJoyButtonDown(Uint8 which,Uint8 button) {
//Pure virtual, do nothing
}
void GEvent::OnJoyButtonUp(Uint8 which,Uint8 button) {
//Pure virtual, do nothing
}
void GEvent::OnJoyHat(Uint8 which,Uint8 hat,Uint8 value) {
//Pure virtual, do nothing
}
void GEvent::OnJoyBall(Uint8 which,Uint8 ball,Sint16 xrel,Sint16 yrel) {
//Pure virtual, do nothing
}
void GEvent::OnMinimize() {
//Pure virtual, do nothing
}
void GEvent::OnRestore() {
//Pure virtual, do nothing
}
void GEvent::OnResize(int w,int h) {
//Pure virtual, do nothing
}
void GEvent::OnExpose() {
//Pure virtual, do nothing
}
void GEvent::OnExit() {
//Pure virtual, do nothing
}
void GEvent::OnUser(Uint8 type, int code, void* data1, void* data2) {
//Pure virtual, do nothing
}
| 23.953271
| 257
| 0.558525
|
abishek-sampath
|
2842442eca960d8309112fd16fcafecfcf29aab9
| 21,655
|
cc
|
C++
|
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/EmilyWindow.cc
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/EmilyWindow.cc,v 1.6 1992/09/08 16:40:43 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: EmilyWindow.cc,v $
* Revision 1.6 1992/09/08 16:40:43 lewis
* Renamed NULL -> Nil.
*
* Revision 1.5 1992/09/01 17:25:44 sterling
* Lots of Foundation changes.
*
* Revision 1.13 1992/02/19 17:31:05 sterling
* enabled setclasinfo when in surtomize mode
*
* Revision 1.11 1992/02/18 01:11:37 lewis
* Use new version support.
*
* Revision 1.9 1992/02/04 22:55:26 lewis
* Use GetShell().GetExtent (), not just GetExtent () for wiundows.
* (maybe should be referencing mainview??).
*
* Revision 1.6 1992/01/31 18:21:58 sterling
* Bootstrapped
*
*/
#include <fstream.h>
#include "Debug.hh"
#include "StreamUtils.hh"
#include "Version.hh"
#include "CommandNumbers.hh"
#include "Dialog.hh"
#include "NumberText.hh"
#include "MenuOwner.hh"
#include "Shell.hh"
#include "CheckBox.hh"
#include "DeskTop.hh"
#include "Language.hh"
#include "EmilyApplication.hh"
#include "ItemPallet.hh"
#include "EmilyWindow.hh"
#include "MainGroupItem.hh"
#include "ClassInfo.hh"
#if qMacUI
CommandNumber EmilyWindow::sCurrentGUI = eMacUI;
#elif qMotifUI
CommandNumber EmilyWindow::sCurrentGUI = eMotifUI;
#elif qWindowsGUI
CommandNumber EmilyWindow::sCurrentGUI = eWindowsGUI;
#endif
CommandNumber EmilyWindow::sCurrentLanguage = eEnglish;
Boolean EmilyWindow::sCustomizeOnly = False;
/*
********************************************************************************
*********************************** EmilyWindow ********************************
********************************************************************************
*/
EmilyWindow::EmilyWindow (EmilyDocument& document):
Window (),
Saveable (1),
fDocument (document),
fClassName ("foo"),
fBaseClass ("View"),
fHeaderPrepend (kEmptyString),
fHeaderAppend (kEmptyString),
fSourcePrepend (kEmptyString),
fSourceAppend (kEmptyString),
fDataPrepend (kEmptyString),
fStringCount (1),
fGrid (EmilyApplication::Get ().GetGrid ()),
fGridVisible (EmilyApplication::Get ().GetGridVisible ()),
#if qMacUI
fGUI (eMacUI),
#elif qMotifUI
fGUI (eMotifUI),
#elif qWindowsGUI
fGUI (eWindowsGUI),
#endif
fLanguage (eEnglish)
{
fMainGroup = new MainGroupItem (*this);
SetMainViewAndTargets (fMainGroup, fMainGroup, fMainGroup);
SetWindowController (&fDocument);
fMainGroup->ResetCustomizeOnly ();
}
EmilyWindow::~EmilyWindow ()
{
SetMainViewAndTargets (Nil, Nil, Nil);
}
EmilyDocument& EmilyWindow::GetDocument ()
{
return (fDocument);
}
void EmilyWindow::PrintPage (PageNumber /*pageNumber*/, class Printer& printer)
{
RequireNotNil (GetMainView ());
printer.DrawView (*GetMainView (), kZeroPoint);
}
void EmilyWindow::CalcPages (PageNumber& userStart, PageNumber& userEnd, const Rect& /*pageRect*/)
{
userStart = 1;
userEnd = 1;
}
PageNumber EmilyWindow::CalcAllPages (const Rect& /*pageRect*/)
{
return (1);
}
void EmilyWindow::DoSetupMenus ()
{
Window::DoSetupMenus ();
SetOn (GetGUI (), True);
SetOn (GetLanguage (), True);
SetOn (eCustomizeOnly, sCustomizeOnly);
EnableCommand (eSetClassInfo);
EnableCommand (eCustomizeOnly);
EnableCommand (eArrow);
EnableCommand (eThumb);
if (ItemPallet::GetEditMode () and (not sCustomizeOnly)) {
for (CommandNumber cmd = eFirstBuildItem; cmd <= eLastBuildItem; cmd++) {
EnableCommand (cmd, ItemPallet::ShouldEnable (cmd));
}
}
#if !qUseCustomMenu
if (ItemPallet::GetSelectedItem () != Nil) {
ItemPallet::GetSelectedItem ()->SetOn (Toggle::kOn, Panel::eNoUpdate);
}
#endif
}
class SetClassInfoCommand : public Command {
public:
SetClassInfoCommand (EmilyWindow& window, class ClassInfo& info);
~SetClassInfoCommand ();
override void DoIt ();
override void UnDoIt ();
private:
EmilyWindow& fWindow;
String fNewClassName;
String fOldClassName;
String fNewBaseClassName;
String fOldBaseClassName;
Point fNewSize;
Point fOldSize;
String fNewHelp;
String fOldHelp;
const Font* fNewFont;
const Font* fOldFont;
Boolean fOldAutoSize;
Boolean fNewAutoSize;
};
SetClassInfoCommand::SetClassInfoCommand (EmilyWindow& window, class ClassInfo& info) :
Command (eSetClassInfo, kUndoable),
fWindow (window),
fNewClassName (info.GetClassNameField ().GetText ()),
fOldClassName (window.fClassName),
fNewBaseClassName (info.GetBaseClassNameField ().GetText ()),
fOldBaseClassName (window.fBaseClass),
fNewSize (Point (info.GetSizeVField ().GetValue (), info.GetSizeHField ().GetValue ())),
fOldSize (window.GetMainGroup ().GetScrollSize ()),
fNewHelp (info.GetHelpField ().GetText ()),
fOldHelp (window.GetMainGroup ().GetHelp ()),
fNewFont (info.fFont),
fOldFont (window.GetMainGroup ().GetFont ()),
fOldAutoSize (window.GetMainGroup ().GetAutoSize ()),
fNewAutoSize (info.GetAutoSizeField ().GetOn ())
{
if (fNewFont != Nil) {
fNewFont = new Font (*fNewFont);
}
if (fOldFont != Nil) {
fOldFont = new Font (*fOldFont);
}
}
SetClassInfoCommand::~SetClassInfoCommand ()
{
delete fNewFont;
delete fOldFont;
}
void SetClassInfoCommand::DoIt ()
{
fWindow.fClassName = fNewClassName;
fWindow.fBaseClass = fNewBaseClassName;
fWindow.GetMainGroup ().SetHelp (fNewHelp);
if (fNewSize != fOldSize) {
if (not fNewAutoSize) {
fWindow.GetMainGroup ().SetScrollSize (fNewSize);
}
}
if (fNewFont != fOldFont) {
fWindow.GetMainGroup ().SetFont (fNewFont);
fWindow.GetMainGroup ().Refresh ();
}
fWindow.GetMainGroup ().SetAutoSize (fNewAutoSize);
fWindow.GetMainGroup ().ApplyCurrentParams ();
Command::DoIt ();
}
void SetClassInfoCommand::UnDoIt ()
{
fWindow.fClassName = fOldClassName;
fWindow.fBaseClass = fOldBaseClassName;
fWindow.GetMainGroup ().SetHelp (fOldHelp);
fWindow.GetMainGroup ().SetAutoSize (fOldAutoSize);
if ((fNewSize != fOldSize) or (fNewAutoSize != fOldAutoSize)) {
if (not fOldAutoSize) {
fWindow.GetMainGroup ().SetScrollSize (fOldSize);
}
}
if (fNewFont != fOldFont) {
fWindow.GetMainGroup ().SetFont (fOldFont);
fWindow.GetMainGroup ().Refresh ();
}
fWindow.GetMainGroup ().ApplyCurrentParams ();
Command::UnDoIt ();
}
Boolean EmilyWindow::DoCommand (const CommandSelection& selection)
{
switch (selection.GetCommandNumber ()) {
case eSetClassInfo:
{
ClassInfo info = ClassInfo (GetMainGroup ());
info.GetClassNameField ().SetText (fClassName);
info.GetBaseClassNameField ().SetText (fBaseClass);
info.GetSizeVField ().SetValue (GetMainGroup ().GetScrollSize ().GetV ());
info.GetSizeHField ().SetValue (GetMainGroup ().GetScrollSize ().GetH ());
info.GetHelpField ().SetText (GetMainGroup ().GetHelp ());
info.GetAutoSizeField ().SetOn (GetMainGroup ().GetAutoSize ());
Dialog d = Dialog (&info, &info, AbstractPushButton::kOKLabel, AbstractPushButton::kCancelLabel);
d.SetDefaultButton (d.GetOKButton ());
if (d.Pose ()) {
PostCommand (new SetClassInfoCommand (*this, info));
PostCommand (new DocumentDirtier (GetDocument ()));
}
}
return (True);
case eMacUI:
case eMotifUI:
case eWindowsGUI:
SetGUI (selection.GetCommandNumber ());
return (True);
case eEnglish:
case eFrench:
case eGerman:
case eItalian:
case eSpanish:
case eJapanese:
SetLanguage (selection.GetCommandNumber ());
return (True);
case eCustomizeOnly:
if (sCustomizeOnly) {
SetLanguage (fLanguage);
SetGUI (fGUI);
}
SetCustomizeOnly (not sCustomizeOnly);
return (True);
default:
return (Window::DoCommand (selection));
}
}
MainGroupItem& EmilyWindow::GetMainGroup () const
{
RequireNotNil (fMainGroup);
return (*fMainGroup);
}
static const String kMachineCodeStartString = "// text before here will be retained: Do not remove or modify this line!!!";
static const String kMachineCodeEndString = "// text past here will be retained: Do not remove or modify this line!!!";
void EmilyWindow::DoRead_ (class istream& from)
{
char bigBuf [1000];
fDataPrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fDataPrepend += s;
fDataPrepend += "\n";
}
}
char c;
from >> c;
from.putback (c);
if (c == 'D') {
// read off data file creation tag
from.getline (bigBuf, sizeof (bigBuf));
from.getline (bigBuf, sizeof (bigBuf));
}
Saveable::DoRead_ (from);
Rect extent = kZeroRect;
from >> extent;
WindowShellHints hints = GetShell ().GetWindowShellHints ();
#if 0
if (extent.GetOrigin () < DeskTop::Get ().GetBounds ().GetBounds ().GetOrigin ()) {
hints.SetDesiredOrigin (extent.GetOrigin ());
}
#endif
hints.SetDesiredSize (extent.GetSize ());
GetShell ().SetWindowShellHints (hints);
ReadString (from, fClassName);
ReadString (from, fBaseClass);
sCustomizeOnly = True;
GetMainGroup ().DoRead (from);
sCustomizeOnly = False;
GetMainGroup ().ResetCustomizeOnly ();
}
void EmilyWindow::DoWrite_ (class ostream& to, int tabCount) const
{
if (fDataPrepend != kEmptyString) {
to << fDataPrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline;
String appLongVersion = kApplicationVersion.GetLongVersionString ();
Assert (appLongVersion != kEmptyString);
to << "Data file written by " << appLongVersion << "." << newline;
to << newline << newline;
Saveable::DoWrite_ (to, tabCount);
to << newline;
to << GetShell ().GetExtent () << newline << newline;
WriteString (to, fClassName);
WriteString (to, fBaseClass);
GetMainGroup ().ResetFieldCounter ();
GetMainGroup ().DoWrite (to, tabCount);
to << newline;
}
void EmilyWindow::ReadHeaderFile (class istream& from)
{
char bigBuf [1000];
fHeaderPrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fHeaderPrepend += s;
fHeaderPrepend += "\n";
}
}
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeEndString) {
break;
}
}
}
fHeaderAppend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf), EOF)) {
fHeaderAppend += String (String::eReadOnly, bigBuf, from.gcount ());
}
}
}
void EmilyWindow::WriteHeaderFile (class ostream& to)
{
if (fHeaderPrepend != kEmptyString) {
to << fHeaderPrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline;
String compilationVariable = "__" + fClassName + "__";
if (EmilyApplication::Get ().GetCompileOnce ()) {
to << "#ifndef " << compilationVariable << newline;
to << "#define " << compilationVariable << newline << newline;
}
static const String kViewString = "View";
static const String kGroupViewString = "GroupView";
static const String kLabelGroupString = "LabeledGroup";
Boolean generateBaseClasses = Boolean ((fBaseClass == kViewString) or (fBaseClass == kGroupViewString) or (fBaseClass == kLabelGroupString));
if (generateBaseClasses) {
if (GetMainGroup ().IsButton ()) {
to << "#include " << quote << "Button.hh" << quote << newline;
}
if (GetMainGroup ().IsFocusItem (eAnyGUI)) {
to << "#include " << quote << "FocusItem.hh" << quote << newline;
}
if (GetMainGroup ().IsSlider ()) {
to << "#include " << quote << "Slider.hh" << quote << newline;
}
if (GetMainGroup ().IsText ()) {
to << "#include " << quote << "TextEdit.hh" << quote << newline;
}
to << "#include " << quote << "View.hh" << quote << newline;
to << newline;
}
GetMainGroup ().WriteIncludes (to, 0);
to << newline << newline;
to << "class "<< fClassName << " : public " << fBaseClass;
if (generateBaseClasses) {
if (GetMainGroup ().IsButton ()) {
to << ", public ButtonController";
}
if (GetMainGroup ().IsSlider ()) {
to << ", public SliderController";
}
if (GetMainGroup ().IsFocusItem (eAnyGUI)) {
to << ", public FocusOwner";
}
if (GetMainGroup ().IsText ()) {
to << ", public TextController";
}
}
to << " {" << newline << tab << "public:" << newline;
// declare constructor
to << tab (2) << fClassName << " ();" << newline;
// declare destructor
to << tab (2) << "~" << fClassName << " ();" << newline << newline;
// declare CalcDefaultSize method
to << tab (2) << "override" << tab << "Point" << tab << "CalcDefaultSize_ (const Point& defaultSize) const;" << newline << newline;
// declare layout method
to << tab << "protected:" << newline;
to << tab (2) << "override" << tab << "void" << tab << "Layout ();" << newline << newline;
// declare fields
GetMainGroup ().WriteDeclaration (to, 2);
to << newline << tab << "private:" << newline;
Boolean first = True;
for (CommandNumber gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << "#elif q";
}
to << directive << newline;
to << tab (2) << "nonvirtual void" << tab << "BuildFor" << directive << " ();" << newline;
}
}
Assert (not first); // must have at least one gui
to << "#else" << newline;
// to << tab (2) << "nonvirtual void" << tab << "BuildFor" << GetGUICompilationDirective (GetMainGroup ().GetBaseGUI ()) << " ();" << newline;
to << tab (2) << "nonvirtual void" << tab << "BuildForUnknownGUI ();" << newline;
to << "#endif /* GUI */" << newline << newline;
to << "};" << newline << newline;
if (EmilyApplication::Get ().GetCompileOnce ()) {
to << "#endif /* " << compilationVariable << " */" << newline;
}
to << newline << newline << kMachineCodeEndString << newline;
if (fHeaderAppend != kEmptyString) {
to << fHeaderAppend;
}
}
void EmilyWindow::ReadSourceFile (class istream& from)
{
char bigBuf [1000];
fSourcePrepend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeStartString) {
break;
}
fSourcePrepend += s;
fSourcePrepend += "\n";
}
}
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf))) {
String s = String (String::eReadOnly, bigBuf, from.gcount ()-1);
if (s == kMachineCodeEndString) {
break;
}
}
}
fSourceAppend = String (String::eBuffered, "");
while (from) {
if (from.getline (bigBuf, sizeof (bigBuf), EOF)) {
fSourceAppend += String (String::eReadOnly, bigBuf, from.gcount ());
}
}
}
void EmilyWindow::WriteSourceFile (class ostream& to)
{
if (fSourcePrepend != kEmptyString) {
to << fSourcePrepend;
}
else {
to << EmilyApplication::Get ().GetDefaultPrepend ();
}
to << kMachineCodeStartString << newline << newline << newline;
to << "#include " << quote << "Language.hh" << quote << newline;
to << "#include " << quote << "Shape.hh" << quote << newline;
to << newline;
to << "#include " << quote << fDocument.GetHeaderFilePathName ().GetFileName () << quote << newline << newline << newline;
// define constructor
to << fClassName << "::" << fClassName << " ()";
// init fields to zero, in case of exception so we do right thing freeing them...
StringStream tempTo; // we use a stringstream to nuke the trailing comma
tempTo << " :" << newline;
GetMainGroup ().WriteBuilder (tempTo, 1);
String initializers = String (tempTo);
if (initializers.GetLength () > 2) {
// still have bad stream bug where zero length returns -1
initializers.SetLength (initializers.GetLength () -2); // one for comma, one for newline
}
else {
initializers.SetLength (0);
}
to << initializers << newline;
to << "{" << newline;
Boolean first = True;
for (CommandNumber gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << "#elif q";
}
to << directive << newline;
to << tab << "BuildFor" << directive << " ();" << newline;
}
}
Assert (not first); // must have at least one gui
to << "#else" << newline;
// to << tab << "BuildFor" << GetGUICompilationDirective (GetMainGroup ().GetBaseGUI ()) << " ();" << newline;
to << tab << "BuildForUnknownGUI ();" << newline;
to << "#endif /* GUI */" << newline << "}" << newline << newline;
// define destructor
to << fClassName << "::~" << fClassName << " ()" << newline;
to << "{" << newline;
GetMainGroup ().WriteDestructor (to, 0, GetMainGroup ().GetBaseGUI ());
to << "}" << newline << newline;
// define GUI builders
first = True;
for (gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q";
first = False;
}
else {
to << newline;
to << "#elif q";
}
to << directive << newline << newline;
to << "void" << tab << fClassName << "::BuildFor" << directive << " ()" << newline << "{" << newline;
GetMainGroup ().WriteInitializer (to, 0, gui);
to << "}" << newline;
}
}
Assert (not first); // must have at least one gui
to << newline << "#else" << newline << newline;
to << "void" << tab << fClassName << "::BuildForUnknownGUI ();" << newline << "{" << newline;
GetMainGroup ().WriteInitializer (to, 0, GetMainGroup ().GetBaseGUI ());
to << "}" << newline << newline;
to << "#endif /* GUI */" << newline << newline;
// define CalcDefaultSize method
to << "Point" << tab << fClassName << "::CalcDefaultSize_ (const Point& /*defaultSize*/) const" << newline << "{" << newline;
first = True;
for (gui = eFirstGUI; gui <= eLastGUI; gui++) {
if (GetMainGroup ().ParamsExist (eAnyLanguage, gui)) {
String directive = GetGUICompilationDirective (gui);
if (first) {
to << "#if q" << directive << newline;
first = False;
}
else {
to << "#elif q" << directive << newline;
}
Point scrollSize = GetMainGroup ().GetScrollSize (GetMainGroup ().GetBaseLanguage (), gui);
to << tab << "return (Point (" << scrollSize.GetV () << ", " << scrollSize.GetH () << "));" << newline;
}
}
Assert (not first);
to << "#else" << newline;
Point scrollSize = GetMainGroup ().GetScrollSize (GetMainGroup ().GetBaseLanguage (), GetMainGroup ().GetBaseGUI ());
to << tab << "return (Point (" << scrollSize.GetV () << ", " << scrollSize.GetH () << "));" << newline;
to << "#endif /* GUI */" << newline << "}" << newline << newline;
// define layout method
to << "void" << tab << fClassName << "::Layout ()" << newline << "{" << newline;
GetMainGroup ().WriteLayout (to, 1);
to << tab << fBaseClass << "::Layout ();" << newline;
to << "}" << newline;
to << newline << newline << kMachineCodeEndString << newline;
if (fSourceAppend != kEmptyString) {
to << fSourceAppend;
}
}
void EmilyWindow::EditModeChanged (Boolean newEditMode)
{
MenuOwner::SetMenusOutOfDate ();
GetMainGroup ().EditModeChanged (newEditMode);
}
CommandNumber EmilyWindow::GetGUI ()
{
return (sCurrentGUI);
}
void EmilyWindow::SetGUI (CommandNumber gui)
{
if (sCurrentGUI != gui) {
CommandNumber oldGUI = sCurrentGUI;
sCurrentGUI = gui;
MenuOwner::SetMenusOutOfDate ();
if (sCurrentGUI == eMacUI) {
SetBackground (&kWhiteTile);
}
else if (sCurrentGUI == eMotifUI) {
Tile t = PalletManager::Get ().MakeTileFromColor (kGrayColor);
SetBackground (&t);
}
else if (sCurrentGUI == eWindowsGUI) {
SetBackground (&kWhiteTile);
}
GetMainGroup ().GUIChanged (oldGUI, sCurrentGUI);
GetMainGroup ().Refresh ();
SetMainView (fMainGroup); // what a ridiculous hack to get it to resize stuff!!!
GetMainGroup ().Refresh ();
Update ();
}
}
CommandNumber EmilyWindow::GetLanguage ()
{
return (sCurrentLanguage);
}
void EmilyWindow::SetLanguage (CommandNumber language)
{
if (sCurrentLanguage != language) {
CommandNumber oldLanguage = sCurrentLanguage;
sCurrentLanguage = language;
MenuOwner::SetMenusOutOfDate ();
if (sCurrentLanguage != fLanguage) {
SetCustomizeOnly (True);
}
else if (sCurrentGUI == fGUI) {
SetCustomizeOnly (False);
}
GetMainGroup ().LanguageChanged (oldLanguage, sCurrentLanguage);
}
}
Boolean EmilyWindow::GetCustomizeOnly ()
{
return (sCustomizeOnly);
}
Boolean EmilyWindow::GetFullEditing ()
{
return (not sCustomizeOnly);
}
void EmilyWindow::SetCustomizeOnly (Boolean customizeOnly)
{
if (sCustomizeOnly != customizeOnly) {
sCustomizeOnly = customizeOnly;
MenuOwner::SetMenusOutOfDate ();
}
}
String GetGUICompilationDirective (CommandNumber gui)
{
switch (gui) {
case eMacUI:
return ("MacUI");
case eMotifUI:
return ("MotifUI");
case eWindowsGUI:
return ("WindowsGUI");
default:
RequireNotReached ();
}
AssertNotReached (); return (kEmptyString);
}
String GetLanguageCompilationDirective (CommandNumber language)
{
switch (language) {
case eEnglish:
return ("English");
case eFrench:
return ("French");
case eGerman:
return ("German");
case eItalian:
return ("Italian");
case eSpanish:
return ("Spanish");
case eJapanese:
return ("Japanese");
default:
RequireNotReached ();
}
AssertNotReached (); return (kEmptyString);
}
| 27.136591
| 142
| 0.652274
|
SophistSolutions
|
2842d743a10cb05257b9106962481d8d684edc81
| 626
|
cpp
|
C++
|
LGPUtil/LGPExitSystem.cpp
|
chen0040/cpp-linear-genetic-programming
|
8b0bc8701110af0b7506546e527bd03f57d972fe
|
[
"MIT"
] | 3
|
2018-01-09T06:03:23.000Z
|
2020-12-29T20:09:44.000Z
|
LGPUtil/LGPExitSystem.cpp
|
chen0040/cpp-linear-genetic-programming
|
8b0bc8701110af0b7506546e527bd03f57d972fe
|
[
"MIT"
] | 1
|
2017-11-15T04:24:43.000Z
|
2017-11-18T02:17:12.000Z
|
LGPUtil/LGPExitSystem.cpp
|
chen0040/cpp-linear-genetic-programming
|
8b0bc8701110af0b7506546e527bd03f57d972fe
|
[
"MIT"
] | 2
|
2017-09-17T04:24:24.000Z
|
2020-01-29T05:35:49.000Z
|
#include "LGPExitSystem.h"
#include <cstdlib>
#include <iostream>
#include "LGPLogger.h"
#include "../LGPConstants/LGPFlags.h"
#include <cassert>
void LGPExitSystem(const char* fname, const char* ename)
{
std::cout << "An error has occurred in the LGP System..." << std::endl;
std::cout << "Source: " << fname << std::endl;
std::cout << "Error: " << ename << std::endl;
lgpLogger.err << "An error has occurred in the LGP System..." << std::endl;
lgpLogger.err << "Source: " << fname << std::endl;
lgpLogger.err << "Error: " << ename << std::endl;
#ifdef LGP_BUILD_DEBUG
assert(false);
#else
std::exit(0);
#endif
}
| 25.04
| 76
| 0.65016
|
chen0040
|
2843f15a5aaff39464478839a47483251844600c
| 998
|
cpp
|
C++
|
out/production/Hacktoberfest1/C++/pattern_prctice(CB).cpp
|
bluey-crypto/Hacktoberfest
|
c826d5faf1d1c860dbffe665e6a7cf1e35ba76ba
|
[
"MIT"
] | 4
|
2019-10-12T13:54:20.000Z
|
2021-07-06T22:41:12.000Z
|
out/production/Hacktoberfest1/C++/pattern_prctice(CB).cpp
|
bluey-crypto/Hacktoberfest
|
c826d5faf1d1c860dbffe665e6a7cf1e35ba76ba
|
[
"MIT"
] | 1
|
2020-10-01T18:03:45.000Z
|
2020-10-01T18:03:45.000Z
|
out/production/Hacktoberfest1/C++/pattern_prctice(CB).cpp
|
bluey-crypto/Hacktoberfest
|
c826d5faf1d1c860dbffe665e6a7cf1e35ba76ba
|
[
"MIT"
] | 8
|
2019-10-14T17:20:09.000Z
|
2020-10-03T17:27:49.000Z
|
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=0;j<n-i;j++)
cout<<" ";
for(int j=i;j<=2*i-1;j++)
cout<<j;
for(int j=i;j)
cout<<j;
cout<<endl;
}
}
/* #include <iostream>
using namespace std;
int main()
{
int rows, count = 0, count1 = 0, k = 0;
cin >> rows;
for(int i = 1; i <= rows; ++i)
{
for(int space = 1; space <= rows-i; ++space)
{
cout << " ";
++count;
}
while(k != 2*i-1)
{
if (count <= rows-1)
{
cout << i+k << " ";
++count;
}
else
{
++count1;
cout << i+k-2*count1 << " ";
}
++k;
}
count1 = count = k = 0;
cout << endl;
}
return 0;
}*/
| 16.360656
| 52
| 0.316633
|
bluey-crypto
|
2845626b754d5b1438c031a49a8a2ce15d1f8187
| 1,098
|
cpp
|
C++
|
library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp
|
tetengo/tetengo
|
66e0d03635583c25be4320171f3cc1e7f40a56e6
|
[
"MIT"
] | null | null | null |
library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp
|
tetengo/tetengo
|
66e0d03635583c25be4320171f3cc1e7f40a56e6
|
[
"MIT"
] | 41
|
2021-06-25T14:20:29.000Z
|
2022-01-16T02:50:50.000Z
|
library/lattice/cpp/src/tetengo.lattice.node_constraint_element.cpp
|
tetengo/tetengo
|
66e0d03635583c25be4320171f3cc1e7f40a56e6
|
[
"MIT"
] | null | null | null |
/*! \file
\brief A node constraint element.
Copyright (C) 2019-2022 kaoru https://www.tetengo.org/
*/
#include <memory>
#include <utility>
#include <boost/core/noncopyable.hpp>
#include <tetengo/lattice/node.hpp>
#include <tetengo/lattice/node_constraint_element.hpp>
namespace tetengo::lattice
{
class node_constraint_element::impl : private boost::noncopyable
{
public:
// constructors and destructor
explicit impl(node node_) : m_node{ std::move(node_) } {}
// functions
int matches_impl(const node& node_) const
{
return node_ == m_node ? 0 : -1;
}
private:
// variables
const node m_node;
};
node_constraint_element::node_constraint_element(node node_) : m_p_impl{ std::make_unique<impl>(std::move(node_)) }
{}
node_constraint_element::~node_constraint_element() = default;
int node_constraint_element::matches_impl(const node& node_) const
{
return m_p_impl->matches_impl(node_);
}
}
| 20.716981
| 120
| 0.618397
|
tetengo
|
284919a0184a7378e69887339cc4337bee738d8b
| 3,664
|
cpp
|
C++
|
src/software/sensor_fusion/filter/robot_team_filter_test.cpp
|
EvanMorcom/Software
|
586fb3cf8dc2d93de194d9815af5de63caa7e318
|
[
"MIT"
] | null | null | null |
src/software/sensor_fusion/filter/robot_team_filter_test.cpp
|
EvanMorcom/Software
|
586fb3cf8dc2d93de194d9815af5de63caa7e318
|
[
"MIT"
] | null | null | null |
src/software/sensor_fusion/filter/robot_team_filter_test.cpp
|
EvanMorcom/Software
|
586fb3cf8dc2d93de194d9815af5de63caa7e318
|
[
"MIT"
] | null | null | null |
/**
* This file contains the unit tests for the implementation of RobotTeamFilter class
*/
#include "software/sensor_fusion/filter/robot_team_filter.h"
#include <gtest/gtest.h>
#include <string.h>
TEST(RobotTeamFilterTest, one_robot_detection_update_test)
{
Team old_team = Team(Duration::fromMilliseconds(1000));
std::vector<RobotDetection> robot_detections;
RobotDetection robot_detection;
RobotTeamFilter robot_team_filter;
// old team starts with a robot with id = 0
old_team.updateRobots(
{Robot(0, Point(0, 1), Vector(-1, -2), Angle::half(),
AngularVelocity::threeQuarter(), Timestamp::fromSeconds(0))});
robot_detection.id = 0;
robot_detection.position = Point(1.0, -2.5);
robot_detection.orientation = Angle::fromRadians(0.5);
robot_detection.confidence = 1.0;
robot_detection.timestamp = Timestamp::fromSeconds(1);
robot_detections.push_back(robot_detection);
// robot detection also has id = 0
Team new_team = robot_team_filter.getFilteredData(old_team, robot_detections);
auto robots = new_team.getAllRobots();
EXPECT_EQ(1, robots.size());
EXPECT_EQ(robot_detection.position, robots[0].currentState().robotState().position());
EXPECT_EQ(robot_detection.orientation,
robots[0].currentState().robotState().orientation());
EXPECT_EQ(robot_detection.timestamp, robots[0].currentState().timestamp());
}
TEST(RobotTeamFilterTest, detections_with_same_timestamp_test)
{
Team old_team = Team(Duration::fromMilliseconds(1000));
std::vector<RobotDetection> robot_detections;
RobotDetection robot_detection;
RobotTeamFilter robot_team_filter;
unsigned int num_robots = 6;
for (unsigned int i = 0; i < num_robots; i++)
{
robot_detection.id = i;
robot_detection.position = Point(Vector(0.5, -0.25) * i);
robot_detection.orientation = Angle::fromRadians(0.1 * i);
robot_detection.confidence = i / ((double)num_robots);
robot_detection.timestamp = Timestamp::fromSeconds(.5);
robot_detections.push_back(robot_detection);
}
Team new_team = robot_team_filter.getFilteredData(old_team, robot_detections);
EXPECT_EQ(num_robots, new_team.numRobots());
for (unsigned int i = 0; i < num_robots; i++)
{
EXPECT_NE(std::nullopt, new_team.getRobotById(i));
Robot robot = *new_team.getRobotById(i);
EXPECT_EQ(robot_detections[i].position,
robot.currentState().robotState().position());
EXPECT_EQ(robot_detections[i].orientation,
robot.currentState().robotState().orientation());
EXPECT_EQ(robot_detections[i].timestamp, robot.currentState().timestamp());
}
}
TEST(RobotTeamFilterTest, detections_with_different_times_test)
{
Team old_team = Team(Duration::fromMilliseconds(1000));
std::vector<RobotDetection> robot_detections;
RobotDetection robot_detection;
RobotTeamFilter robot_team_filter;
unsigned int num_robots = 6;
for (unsigned int i = 0; i < num_robots; i++)
{
robot_detection.id = i;
robot_detection.position = Point(Vector(0.5, -0.25) * i);
robot_detection.orientation = Angle::fromRadians(0.1 * i);
robot_detection.confidence = i / ((double)num_robots);
// use different timestamps for each detection
robot_detection.timestamp = Timestamp::fromSeconds(i);
robot_detections.push_back(robot_detection);
}
Team new_team = robot_team_filter.getFilteredData(old_team, robot_detections);
EXPECT_EQ(1, new_team.numRobots());
}
| 37.387755
| 90
| 0.692959
|
EvanMorcom
|
284adc7198c21a8493c908069d40743f3fb42d30
| 73,997
|
cpp
|
C++
|
catboost/libs/model/model.cpp
|
notimesea/catboost
|
1d3e0744f1d6c6d74d724878dc9fe92076c8b1ce
|
[
"Apache-2.0"
] | null | null | null |
catboost/libs/model/model.cpp
|
notimesea/catboost
|
1d3e0744f1d6c6d74d724878dc9fe92076c8b1ce
|
[
"Apache-2.0"
] | null | null | null |
catboost/libs/model/model.cpp
|
notimesea/catboost
|
1d3e0744f1d6c6d74d724878dc9fe92076c8b1ce
|
[
"Apache-2.0"
] | null | null | null |
#include "model.h"
#include "flatbuffers_serializer_helper.h"
#include "model_import_interface.h"
#include "model_build_helper.h"
#include "static_ctr_provider.h"
#include <catboost/libs/model/flatbuffers/model.fbs.h>
#include <catboost/libs/cat_feature/cat_feature.h>
#include <catboost/libs/helpers/borders_io.h>
#include <catboost/libs/logging/logging.h>
#include <catboost/private/libs/options/enum_helpers.h>
#include <catboost/private/libs/options/json_helper.h>
#include <catboost/private/libs/options/loss_description.h>
#include <catboost/private/libs/options/class_label_options.h>
#include <library/cpp/json/json_reader.h>
#include <library/cpp/dbg_output/dump.h>
#include <library/cpp/dbg_output/auto.h>
#include <util/generic/algorithm.h>
#include <util/generic/cast.h>
#include <util/generic/fwd.h>
#include <util/generic/guid.h>
#include <util/generic/variant.h>
#include <util/generic/xrange.h>
#include <util/generic/ylimits.h>
#include <util/generic/ymath.h>
#include <util/string/builder.h>
#include <util/stream/str.h>
static const char MODEL_FILE_DESCRIPTOR_CHARS[4] = {'C', 'B', 'M', '1'};
static void ReferenceMainFactoryRegistrators() {
// We HAVE TO manually reference some pointers to make factory registrators work. Blessed static linking!
CB_ENSURE(NCB::NModelEvaluation::CPUEvaluationBackendRegistratorPointer);
CB_ENSURE(NCB::BinaryModelLoaderRegistratorPointer);
}
static ui32 GetModelFormatDescriptor() {
return *reinterpret_cast<const ui32*>(MODEL_FILE_DESCRIPTOR_CHARS);
}
static const char* CURRENT_CORE_FORMAT_STRING = "FlabuffersModel_v1";
void OutputModel(const TFullModel& model, IOutputStream* const out) {
Save(out, model);
}
void OutputModel(const TFullModel& model, const TStringBuf modelFile) {
TOFStream f(TString{modelFile}); // {} because of the most vexing parse
OutputModel(model, &f);
}
bool IsDeserializableModelFormat(EModelType format) {
return NCB::TModelLoaderFactory::Has(format);
}
static void CheckFormat(EModelType format) {
ReferenceMainFactoryRegistrators();
CB_ENSURE(
NCB::TModelLoaderFactory::Has(format),
"Model format " << format << " deserialization not supported or missing. Link with catboost/libs/model/model_export if you need CoreML or JSON"
);
}
TFullModel ReadModel(const TString& modelFile, EModelType format) {
CheckFormat(format);
THolder<NCB::IModelLoader> modelLoader(NCB::TModelLoaderFactory::Construct(format));
return modelLoader->ReadModel(modelFile);
}
TFullModel ReadModel(const void* binaryBuffer, size_t binaryBufferSize, EModelType format) {
CheckFormat(format);
THolder<NCB::IModelLoader> modelLoader(NCB::TModelLoaderFactory::Construct(format));
return modelLoader->ReadModel(binaryBuffer, binaryBufferSize);
}
TFullModel ReadZeroCopyModel(const void* binaryBuffer, size_t binaryBufferSize) {
TFullModel model;
model.InitNonOwning(binaryBuffer, binaryBufferSize);
return model;
}
TString SerializeModel(const TFullModel& model) {
TStringStream ss;
OutputModel(model, &ss);
return ss.Str();
}
TFullModel DeserializeModel(TMemoryInput serializedModel) {
TFullModel model;
Load(&serializedModel, model);
return model;
}
TFullModel DeserializeModel(const TString& serializedModel) {
return DeserializeModel(TMemoryInput{serializedModel.data(), serializedModel.size()});
}
struct TSolidModelTree : IModelTreeData {
TConstArrayRef<int> GetTreeSplits() const override;
TConstArrayRef<int> GetTreeSizes() const override;
TConstArrayRef<int> GetTreeStartOffsets() const override;
TConstArrayRef<TNonSymmetricTreeStepNode> GetNonSymmetricStepNodes() const override;
TConstArrayRef<ui32> GetNonSymmetricNodeIdToLeafId() const override;
TConstArrayRef<double> GetLeafValues() const override;
TConstArrayRef<double> GetLeafWeights() const override;
THolder<IModelTreeData> Clone(ECloningPolicy policy) const override;
void SetTreeSplits(const TVector<int>&) override;
void SetTreeSizes(const TVector<int>&) override;
void SetTreeStartOffsets(const TVector<int>&) override;
void SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode>&) override;
void SetNonSymmetricNodeIdToLeafId(const TVector<ui32>&) override;
void SetLeafValues(const TVector<double>&) override;
void SetLeafWeights(const TVector<double>&) override;
TVector<int> TreeSplits;
TVector<int> TreeSizes;
TVector<int> TreeStartOffsets;
TVector<TNonSymmetricTreeStepNode> NonSymmetricStepNodes;
TVector<ui32> NonSymmetricNodeIdToLeafId;
TVector<double> LeafValues;
TVector<double> LeafWeights;
};
static TSolidModelTree* CastToSolidTree(const TModelTrees& trees) {
auto ptr = dynamic_cast<TSolidModelTree*>(trees.GetModelTreeData().Get());
CB_ENSURE(ptr, "Only solid models are modifiable");
return ptr;
}
struct TOpaqueModelTree : IModelTreeData {
TConstArrayRef<int> GetTreeSplits() const override;
TConstArrayRef<int> GetTreeSizes() const override;
TConstArrayRef<int> GetTreeStartOffsets() const override;
TConstArrayRef<TNonSymmetricTreeStepNode> GetNonSymmetricStepNodes() const override;
TConstArrayRef<ui32> GetNonSymmetricNodeIdToLeafId() const override;
TConstArrayRef<double> GetLeafValues() const override;
TConstArrayRef<double> GetLeafWeights() const override;
THolder<IModelTreeData> Clone(ECloningPolicy policy) const override;
void SetTreeSplits(const TVector<int>&) override;
void SetTreeSizes(const TVector<int>&) override;
void SetTreeStartOffsets(const TVector<int>&) override;
void SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode>&) override;
void SetNonSymmetricNodeIdToLeafId(const TVector<ui32>&) override;
void SetLeafValues(const TVector<double>&) override;
void SetLeafWeights(const TVector<double>&) override;
TConstArrayRef<int> TreeSplits;
TConstArrayRef<int> TreeSizes;
TConstArrayRef<int> TreeStartOffsets;
TConstArrayRef<TNonSymmetricTreeStepNode> NonSymmetricStepNodes;
TConstArrayRef<ui32> NonSymmetricNodeIdToLeafId;
TConstArrayRef<double> LeafValues;
TConstArrayRef<double> LeafWeights;
};
static TOpaqueModelTree* CastToOpaqueTree(const TModelTrees& trees) {
auto ptr = dynamic_cast<TOpaqueModelTree*>(trees.GetModelTreeData().Get());
CB_ENSURE(ptr, "Not an opaque model");
return ptr;
}
TModelTrees::TModelTrees() {
ModelTreeData = MakeHolder<TSolidModelTree>();
UpdateRuntimeData();
}
void TModelTrees::ProcessSplitsSet(
const TSet<TModelSplit>& modelSplitSet,
const TVector<size_t>& floatFeaturesInternalIndexesMap,
const TVector<size_t>& catFeaturesInternalIndexesMap,
const TVector<size_t>& textFeaturesInternalIndexesMap,
const TVector<size_t>& embeddingFeaturesInternalIndexesMap
) {
THashSet<int> usedCatFeatureIndexes;
THashSet<int> usedTextFeatureIndexes;
THashSet<int> usedEmbeddingFeatureIndexes;
for (const auto& split : modelSplitSet) {
if (split.Type == ESplitType::FloatFeature) {
const size_t internalFloatIndex = floatFeaturesInternalIndexesMap.at((size_t)split.FloatFeature.FloatFeature);
FloatFeatures.at(internalFloatIndex).Borders.push_back(split.FloatFeature.Split);
} else if (split.Type == ESplitType::EstimatedFeature) {
const TEstimatedFeatureSplit estimatedFeatureSplit = split.EstimatedFeature;
EEstimatedSourceFeatureType featureType;
if (std::find(textFeaturesInternalIndexesMap.begin(),
textFeaturesInternalIndexesMap.end(),
estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureId) !=
textFeaturesInternalIndexesMap.end()) {
usedTextFeatureIndexes.insert(estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureId);
featureType = EEstimatedSourceFeatureType::Text;
} else {
usedEmbeddingFeatureIndexes.insert(estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureId);
featureType = EEstimatedSourceFeatureType::Embedding;
}
if (EstimatedFeatures.empty() ||
EstimatedFeatures.back().ModelEstimatedFeature != estimatedFeatureSplit.ModelEstimatedFeature
) {
TEstimatedFeature estimatedFeature(estimatedFeatureSplit.ModelEstimatedFeature);
Y_ASSERT(estimatedFeatureSplit.ModelEstimatedFeature.SourceFeatureType == featureType);
EstimatedFeatures.emplace_back(estimatedFeature);
}
EstimatedFeatures.back().Borders.push_back(estimatedFeatureSplit.Split);
} else if (split.Type == ESplitType::OneHotFeature) {
usedCatFeatureIndexes.insert(split.OneHotFeature.CatFeatureIdx);
if (OneHotFeatures.empty() || OneHotFeatures.back().CatFeatureIndex != split.OneHotFeature.CatFeatureIdx) {
auto& ref = OneHotFeatures.emplace_back();
ref.CatFeatureIndex = split.OneHotFeature.CatFeatureIdx;
}
OneHotFeatures.back().Values.push_back(split.OneHotFeature.Value);
} else {
const auto& projection = split.OnlineCtr.Ctr.Base.Projection;
usedCatFeatureIndexes.insert(projection.CatFeatures.begin(), projection.CatFeatures.end());
if (CtrFeatures.empty() || CtrFeatures.back().Ctr != split.OnlineCtr.Ctr) {
CtrFeatures.emplace_back();
CtrFeatures.back().Ctr = split.OnlineCtr.Ctr;
}
CtrFeatures.back().Borders.push_back(split.OnlineCtr.Border);
}
}
for (const int usedCatFeatureIdx : usedCatFeatureIndexes) {
CatFeatures[catFeaturesInternalIndexesMap.at(usedCatFeatureIdx)].SetUsedInModel(true);
}
for (const int usedTextFeatureIdx : usedTextFeatureIndexes) {
TextFeatures[textFeaturesInternalIndexesMap.at(usedTextFeatureIdx)].SetUsedInModel(true);
}
for (const int usedEmbeddingFeatureIdx : usedEmbeddingFeatureIndexes) {
EmbeddingFeatures[embeddingFeaturesInternalIndexesMap.at(usedEmbeddingFeatureIdx)].SetUsedInModel(true);
}
}
void TModelTrees::AddBinTree(const TVector<int>& binSplits) {
auto& data = *CastToSolidTree(*this);
Y_ASSERT(data.TreeSizes.size() == data.TreeStartOffsets.size() && data.TreeSplits.empty() == data.TreeSizes.empty());
data.TreeSplits.insert(data.TreeSplits.end(), binSplits.begin(), binSplits.end());
if (data.TreeStartOffsets.empty()) {
data.TreeStartOffsets.push_back(0);
} else {
data.TreeStartOffsets.push_back(data.TreeStartOffsets.back() + data.TreeSizes.back());
}
data.TreeSizes.push_back(binSplits.ysize());
}
void TModelTrees::ClearLeafWeights() {
CastToSolidTree(*this)->LeafWeights.clear();
}
void TModelTrees::AddTreeSplit(int treeSplit) {
CastToSolidTree(*this)->TreeSplits.push_back(treeSplit);
}
void TModelTrees::AddTreeSize(int treeSize) {
auto& data = *CastToSolidTree(*this);
if (data.TreeStartOffsets.empty()) {
data.TreeStartOffsets.push_back(0);
} else {
data.TreeStartOffsets.push_back(data.TreeStartOffsets.back() + data.TreeSizes.back());
}
data.TreeSizes.push_back(treeSize);
}
void TModelTrees::AddLeafValue(double leafValue) {
CastToSolidTree(*this)->LeafValues.push_back(leafValue);
}
void TModelTrees::AddLeafWeight(double leafWeight) {
CastToSolidTree(*this)->LeafWeights.push_back(leafWeight);
}
bool TModelTrees::IsSolid() const {
return dynamic_cast<TSolidModelTree*>(ModelTreeData.Get());
}
void TModelTrees::TruncateTrees(size_t begin, size_t end) {
//TODO(eermishkina): support non symmetric trees
CB_ENSURE(IsOblivious(), "Truncate support only symmetric trees");
CB_ENSURE(begin <= end, "begin tree index should be not greater than end tree index.");
CB_ENSURE(end <= GetModelTreeData()->GetTreeSplits().size(), "end tree index should be not greater than tree count.");
auto savedScaleAndBias = GetScaleAndBias();
TObliviousTreeBuilder builder(FloatFeatures,
CatFeatures,
TextFeatures,
EmbeddingFeatures,
ApproxDimension);
auto applyData = GetApplyData();
const auto& leafOffsets = applyData->TreeFirstLeafOffsets;
const auto treeSizes = GetModelTreeData()->GetTreeSizes();
const auto treeSplits = GetModelTreeData()->GetTreeSplits();
const auto leafValues = GetModelTreeData()->GetLeafValues();
const auto leafWeights = GetModelTreeData()->GetLeafWeights();
const auto treeStartOffsets = GetModelTreeData()->GetTreeStartOffsets();
for (size_t treeIdx = begin; treeIdx < end; ++treeIdx) {
TVector<TModelSplit> modelSplits;
for (int splitIdx = treeStartOffsets[treeIdx];
splitIdx < treeStartOffsets[treeIdx] + treeSizes[treeIdx];
++splitIdx)
{
modelSplits.push_back(GetBinFeatures()[treeSplits[splitIdx]]);
}
TConstArrayRef<double> leafValuesRef(
leafValues.begin() + leafOffsets[treeIdx],
leafValues.begin() + leafOffsets[treeIdx] + ApproxDimension * (1u << treeSizes[treeIdx])
);
builder.AddTree(
modelSplits,
leafValuesRef,
leafWeights.empty() ? TConstArrayRef<double>() : TConstArrayRef<double>(
leafWeights.begin() + leafOffsets[treeIdx] / ApproxDimension,
leafWeights.begin() + leafOffsets[treeIdx] / ApproxDimension + (1ull << treeSizes[treeIdx])
)
);
}
builder.Build(this);
this->SetScaleAndBias(savedScaleAndBias);
}
flatbuffers::Offset<NCatBoostFbs::TModelTrees>
TModelTrees::FBSerialize(TModelPartsCachingSerializer& serializer) const {
auto& builder = serializer.FlatbufBuilder;
std::vector<flatbuffers::Offset<NCatBoostFbs::TCatFeature>> catFeaturesOffsets;
for (const auto& catFeature : CatFeatures) {
catFeaturesOffsets.push_back(catFeature.FBSerialize(builder));
}
auto fbsCatFeaturesOffsets = builder.CreateVector(catFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TFloatFeature>> floatFeaturesOffsets;
for (const auto& floatFeature : FloatFeatures) {
floatFeaturesOffsets.push_back(floatFeature.FBSerialize(builder));
}
auto fbsFloatFeaturesOffsets = builder.CreateVector(floatFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TTextFeature>> textFeaturesOffsets;
for (const auto& textFeature : TextFeatures) {
textFeaturesOffsets.push_back(textFeature.FBSerialize(builder));
}
auto fbsTextFeaturesOffsets = builder.CreateVector(textFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TEmbeddingFeature>> embeddingFeaturesOffsets;
for (const auto& embeddingFeature : EmbeddingFeatures) {
embeddingFeaturesOffsets.push_back(embeddingFeature.FBSerialize(builder));
}
auto fbsEmbeddingFeaturesOffsets = builder.CreateVector(embeddingFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TEstimatedFeature>> estimatedFeaturesOffsets;
for (const auto& estimatedFeature : EstimatedFeatures) {
estimatedFeaturesOffsets.push_back(estimatedFeature.FBSerialize(builder));
}
auto fbsEstimatedFeaturesOffsets = builder.CreateVector(estimatedFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TOneHotFeature>> oneHotFeaturesOffsets;
for (const auto& oneHotFeature : OneHotFeatures) {
oneHotFeaturesOffsets.push_back(oneHotFeature.FBSerialize(builder));
}
auto fbsOneHotFeaturesOffsets = builder.CreateVector(oneHotFeaturesOffsets);
std::vector<flatbuffers::Offset<NCatBoostFbs::TCtrFeature>> ctrFeaturesOffsets;
for (const auto& ctrFeature : CtrFeatures) {
ctrFeaturesOffsets.push_back(ctrFeature.FBSerialize(serializer));
}
auto fbsCtrFeaturesOffsets = builder.CreateVector(ctrFeaturesOffsets);
TVector<NCatBoostFbs::TNonSymmetricTreeStepNode> nonSymmetricTreeStepNode;
nonSymmetricTreeStepNode.reserve(GetModelTreeData()->GetNonSymmetricStepNodes().size());
for (const auto& nonSymmetricStep: GetModelTreeData()->GetNonSymmetricStepNodes()) {
nonSymmetricTreeStepNode.emplace_back(NCatBoostFbs::TNonSymmetricTreeStepNode{
nonSymmetricStep.LeftSubtreeDiff,
nonSymmetricStep.RightSubtreeDiff
});
}
auto fbsNonSymmetricTreeStepNode = builder.CreateVectorOfStructs(nonSymmetricTreeStepNode);
TVector<NCatBoostFbs::TRepackedBin> repackedBins;
repackedBins.reserve(GetRepackedBins().size());
for (const auto& repackedBin: GetRepackedBins()) {
repackedBins.emplace_back(NCatBoostFbs::TRepackedBin{
repackedBin.FeatureIndex,
repackedBin.XorMask,
repackedBin.SplitIdx
});
}
auto fbsRepackedBins = builder.CreateVectorOfStructs(repackedBins);
auto& data = GetModelTreeData();
auto fbsTreeSplits = builder.CreateVector(data->GetTreeSplits().data(), data->GetTreeSplits().size());
auto fbsTreeSizes = builder.CreateVector(data->GetTreeSizes().data(), data->GetTreeSizes().size());
auto fbsTreeStartOffsets = builder.CreateVector(data->GetTreeStartOffsets().data(), data->GetTreeStartOffsets().size());
auto fbsLeafValues = builder.CreateVector(data->GetLeafValues().data(), data->GetLeafValues().size());
auto fbsLeafWeights = builder.CreateVector(data->GetLeafWeights().data(), data->GetLeafWeights().size());
auto fbsNonSymmetricNodeIdToLeafId = builder.CreateVector(data->GetNonSymmetricNodeIdToLeafId().data(), data->GetNonSymmetricNodeIdToLeafId().size());
auto bias = GetScaleAndBias().GetBiasRef();
auto fbsBias = builder.CreateVector(bias.data(), bias.size());
return NCatBoostFbs::CreateTModelTrees(
builder,
ApproxDimension,
fbsTreeSplits,
fbsTreeSizes,
fbsTreeStartOffsets,
fbsCatFeaturesOffsets,
fbsFloatFeaturesOffsets,
fbsOneHotFeaturesOffsets,
fbsCtrFeaturesOffsets,
fbsLeafValues,
fbsLeafWeights,
fbsNonSymmetricTreeStepNode,
fbsNonSymmetricNodeIdToLeafId,
fbsTextFeaturesOffsets,
fbsEstimatedFeaturesOffsets,
GetScaleAndBias().Scale,
0,
fbsBias,
fbsRepackedBins,
fbsEmbeddingFeaturesOffsets
);
}
static_assert(sizeof(TRepackedBin) == sizeof(NCatBoostFbs::TRepackedBin));
void TModelTrees::UpdateRuntimeData() {
CalcForApplyData();
CalcBinFeatures();
}
void TModelTrees::ProcessFloatFeatures() {
for (const auto& feature : FloatFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedFloatFeaturesCount;
ApplyData->MinimalSufficientFloatFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessCatFeatures() {
for (const auto& feature : CatFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedCatFeaturesCount;
ApplyData->MinimalSufficientCatFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessTextFeatures() {
for (const auto& feature : TextFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedTextFeaturesCount;
ApplyData->MinimalSufficientTextFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessEmbeddingFeatures() {
for (const auto& feature : TextFeatures) {
if (feature.UsedInModel()) {
++ApplyData->UsedEmbeddingFeaturesCount;
ApplyData->MinimalSufficientEmbeddingFeaturesVectorSize = static_cast<size_t>(feature.Position.Index) + 1;
}
}
}
void TModelTrees::ProcessEstimatedFeatures() {
ApplyData->UsedEstimatedFeaturesCount = EstimatedFeatures.size();
}
void TModelTrees::CalcBinFeatures() {
auto runtimeData = MakeAtomicShared<TRuntimeData>();
struct TFeatureSplitId {
ui32 FeatureIdx = 0;
ui32 SplitIdx = 0;
};
TVector<TFeatureSplitId> splitIds;
auto& ref = *runtimeData;
for (const auto& feature : FloatFeatures) {
if (!feature.UsedInModel()) {
continue;
}
for (int borderId = 0; borderId < feature.Borders.ysize(); ++borderId) {
TFloatSplit fs{feature.Position.Index, feature.Borders[borderId]};
ref.BinFeatures.emplace_back(fs);
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + borderId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (borderId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Borders.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
for (const auto& feature : EstimatedFeatures) {
for (int borderId = 0; borderId < feature.Borders.ysize(); ++borderId) {
TEstimatedFeatureSplit split{
feature.ModelEstimatedFeature,
feature.Borders[borderId]
};
ref.BinFeatures.emplace_back(split);
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + borderId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (borderId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Borders.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
for (const auto& feature : OneHotFeatures) {
for (int valueId = 0; valueId < feature.Values.ysize(); ++valueId) {
TOneHotSplit oh{feature.CatFeatureIndex, feature.Values[valueId]};
ref.BinFeatures.emplace_back(oh);
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + valueId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (valueId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Values.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
for (size_t i = 0; i < CtrFeatures.size(); ++i) {
const auto& feature = CtrFeatures[i];
if (i > 0) {
Y_ASSERT(CtrFeatures[i - 1] < feature);
}
for (int borderId = 0; borderId < feature.Borders.ysize(); ++borderId) {
TModelCtrSplit ctrSplit;
ctrSplit.Ctr = feature.Ctr;
ctrSplit.Border = feature.Borders[borderId];
ref.BinFeatures.emplace_back(std::move(ctrSplit));
auto& bf = splitIds.emplace_back();
bf.FeatureIdx = ref.EffectiveBinFeaturesBucketCount + borderId / MAX_VALUES_PER_BIN;
bf.SplitIdx = (borderId % MAX_VALUES_PER_BIN) + 1;
}
ref.EffectiveBinFeaturesBucketCount
+= (feature.Borders.size() + MAX_VALUES_PER_BIN - 1) / MAX_VALUES_PER_BIN;
}
RuntimeData = runtimeData;
TVector<TRepackedBin> repackedBins;
auto treeSplits = GetModelTreeData()->GetTreeSplits();
for (const auto& binSplit : treeSplits) {
const auto& feature = ref.BinFeatures[binSplit];
const auto& featureIndex = splitIds[binSplit];
Y_ENSURE(
featureIndex.FeatureIdx <= 0xffff,
"Too many features in model, ask catboost team for support"
);
TRepackedBin rb;
rb.FeatureIndex = featureIndex.FeatureIdx;
if (feature.Type != ESplitType::OneHotFeature) {
rb.SplitIdx = featureIndex.SplitIdx;
} else {
rb.XorMask = ((~featureIndex.SplitIdx) & 0xff);
rb.SplitIdx = 0xff;
}
repackedBins.push_back(rb);
}
RepackedBins = NCB::TMaybeOwningConstArrayHolder<TRepackedBin>::CreateOwning(std::move(repackedBins));
}
void TModelTrees::CalcUsedModelCtrs() {
auto& ref = ApplyData->UsedModelCtrs;
for (const auto& ctrFeature : CtrFeatures) {
ref.push_back(ctrFeature.Ctr);
}
}
void TModelTrees::CalcFirstLeafOffsets() {
auto treeSizes = GetModelTreeData()->GetTreeSizes();
auto treeStartOffsets = GetModelTreeData()->GetTreeStartOffsets();
auto& ref = ApplyData->TreeFirstLeafOffsets;
ref.resize(treeSizes.size());
if (IsOblivious()) {
size_t currentOffset = 0;
for (size_t i = 0; i < treeSizes.size(); ++i) {
ref[i] = currentOffset;
currentOffset += (1 << treeSizes[i]) * ApproxDimension;
}
} else {
for (size_t treeId = 0; treeId < treeSizes.size(); ++treeId) {
const int treeNodesStart = treeStartOffsets[treeId];
const int treeNodesEnd = treeNodesStart + treeSizes[treeId];
ui32 minLeafValueIndex = Max();
ui32 maxLeafValueIndex = 0;
ui32 valueNodeCount = 0; // count of nodes with values
for (auto nodeIndex = treeNodesStart; nodeIndex < treeNodesEnd; ++nodeIndex) {
const auto &node = GetModelTreeData()->GetNonSymmetricStepNodes()[nodeIndex];
if (node.LeftSubtreeDiff == 0 || node.RightSubtreeDiff == 0) {
const ui32 leafValueIndex = GetModelTreeData()->GetNonSymmetricNodeIdToLeafId()[nodeIndex];
Y_ASSERT(leafValueIndex != Max<ui32>());
Y_VERIFY_DEBUG(
leafValueIndex % ApproxDimension == 0,
"Expect that leaf values are aligned."
);
minLeafValueIndex = Min(minLeafValueIndex, leafValueIndex);
maxLeafValueIndex = Max(maxLeafValueIndex, leafValueIndex);
++valueNodeCount;
}
}
Y_ASSERT(valueNodeCount > 0);
Y_ASSERT(maxLeafValueIndex == minLeafValueIndex + (valueNodeCount - 1) * ApproxDimension);
ref[treeId] = minLeafValueIndex;
}
}
}
void TModelTrees::DropUnusedFeatures() {
EraseIf(FloatFeatures, [](const TFloatFeature& feature) { return !feature.UsedInModel();});
EraseIf(CatFeatures, [](const TCatFeature& feature) { return !feature.UsedInModel(); });
EraseIf(TextFeatures, [](const TTextFeature& feature) { return !feature.UsedInModel(); });
EraseIf(EmbeddingFeatures, [](const TEmbeddingFeature& feature) { return !feature.UsedInModel(); });
UpdateRuntimeData();
}
void TModelTrees::ConvertObliviousToAsymmetric() {
if (!IsOblivious() || !IsSolid()) {
return;
}
TVector<int> treeSplits;
TVector<int> treeSizes;
TVector<int> treeStartOffsets;
TVector<TNonSymmetricTreeStepNode> nonSymmetricStepNodes;
TVector<ui32> nonSymmetricNodeIdToLeafId;
size_t leafStartOffset = 0;
auto& data = *CastToSolidTree(*this);
for (size_t treeId = 0; treeId < data.TreeSizes.size(); ++treeId) {
size_t treeSize = 0;
treeStartOffsets.push_back(treeSplits.size());
for (int depth = 0; depth < data.TreeSizes[treeId]; ++depth) {
const auto split = data.TreeSplits[data.TreeStartOffsets[treeId] + data.TreeSizes[treeId] - 1 - depth];
for (size_t cloneId = 0; cloneId < (1ull << depth); ++cloneId) {
treeSplits.push_back(split);
nonSymmetricNodeIdToLeafId.push_back(Max<ui32>());
nonSymmetricStepNodes.emplace_back(TNonSymmetricTreeStepNode{static_cast<ui16>(treeSize + 1), static_cast<ui16>(treeSize + 2)});
++treeSize;
}
}
for (size_t cloneId = 0; cloneId < (1ull << data.TreeSizes[treeId]); ++cloneId) {
treeSplits.push_back(0);
nonSymmetricNodeIdToLeafId.push_back((leafStartOffset + cloneId) * ApproxDimension);
nonSymmetricStepNodes.emplace_back(TNonSymmetricTreeStepNode{0, 0});
++treeSize;
}
leafStartOffset += (1ull << data.TreeSizes[treeId]);
treeSizes.push_back(treeSize);
}
data.TreeSplits = std::move(treeSplits);
data.TreeSizes = std::move(treeSizes);
data.TreeStartOffsets = std::move(treeStartOffsets);
data.NonSymmetricStepNodes = std::move(nonSymmetricStepNodes);
data.NonSymmetricNodeIdToLeafId = std::move(nonSymmetricNodeIdToLeafId);
UpdateRuntimeData();
}
TVector<ui32> TModelTrees::GetTreeLeafCounts() const {
auto applyData = GetApplyData();
const auto& firstLeafOfsets = applyData->TreeFirstLeafOffsets;
Y_ASSERT(IsSorted(firstLeafOfsets.begin(), firstLeafOfsets.end()));
TVector<ui32> treeLeafCounts;
treeLeafCounts.reserve(GetTreeCount());
for (size_t treeNum = 0; treeNum < GetTreeCount(); ++treeNum) {
const size_t currTreeLeafValuesEnd = (
treeNum + 1 < GetTreeCount()
? firstLeafOfsets[treeNum + 1]
: GetModelTreeData()->GetLeafValues().size()
);
const size_t currTreeLeafValuesCount = currTreeLeafValuesEnd - firstLeafOfsets[treeNum];
Y_ASSERT(currTreeLeafValuesCount % ApproxDimension == 0);
treeLeafCounts.push_back(currTreeLeafValuesCount / ApproxDimension);
}
return treeLeafCounts;
}
void TModelTrees::SetScaleAndBias(const TScaleAndBias& scaleAndBias) {
CB_ENSURE(IsValidFloat(scaleAndBias.Scale), "Invalid scale " << scaleAndBias.Scale);
TVector<double> bias = scaleAndBias.GetBiasRef();
for (auto b: bias) {
CB_ENSURE(IsValidFloat(b), "Invalid bias " << b);
}
if (bias.empty()) {
bias.resize(GetDimensionsCount(), 0);
}
CB_ENSURE(
GetDimensionsCount() == bias.size(),
"Inappropraite dimension of bias, should be " << GetDimensionsCount() << " found " << bias.size());
ScaleAndBias = TScaleAndBias(scaleAndBias.Scale, bias);
}
void TModelTrees::SetScaleAndBias(const NCatBoostFbs::TModelTrees* fbObj) {
ApproxDimension = fbObj->ApproxDimension();
TVector<double> bias;
if (fbObj->MultiBias() && fbObj->MultiBias()->size()) {
bias.assign(fbObj->MultiBias()->data(), fbObj->MultiBias()->data() + fbObj->MultiBias()->size());
} else {
CB_ENSURE(ApproxDimension == 1 || fbObj->Bias() == 0,
"Inappropraite dimension of bias, should be " << GetDimensionsCount() << " found 1");
bias.resize(ApproxDimension, fbObj->Bias());
}
SetScaleAndBias({fbObj->Scale(), bias});
}
void TModelTrees::DeserializeFeatures(const NCatBoostFbs::TModelTrees* fbObj) {
#define FBS_ARRAY_DESERIALIZER(var) \
if (fbObj->var()) {\
var.resize(fbObj->var()->size());\
for (size_t i = 0; i < fbObj->var()->size(); ++i) {\
var[i].FBDeserialize(fbObj->var()->Get(i));\
}\
}
FBS_ARRAY_DESERIALIZER(CatFeatures)
FBS_ARRAY_DESERIALIZER(FloatFeatures)
FBS_ARRAY_DESERIALIZER(TextFeatures)
FBS_ARRAY_DESERIALIZER(EmbeddingFeatures)
FBS_ARRAY_DESERIALIZER(EstimatedFeatures)
FBS_ARRAY_DESERIALIZER(OneHotFeatures)
FBS_ARRAY_DESERIALIZER(CtrFeatures)
#undef FBS_ARRAY_DESERIALIZER
}
void TModelTrees::FBDeserializeOwning(const NCatBoostFbs::TModelTrees* fbObj) {
ApproxDimension = fbObj->ApproxDimension();
SetScaleAndBias(fbObj);
auto& data = *CastToSolidTree(*this);
if (fbObj->TreeSplits()) {
data.TreeSplits.assign(fbObj->TreeSplits()->begin(), fbObj->TreeSplits()->end());
}
if (fbObj->TreeSizes()) {
data.TreeSizes.assign(fbObj->TreeSizes()->begin(), fbObj->TreeSizes()->end());
}
if (fbObj->TreeStartOffsets()) {
data.TreeStartOffsets.assign(fbObj->TreeStartOffsets()->begin(), fbObj->TreeStartOffsets()->end());
}
if (fbObj->LeafValues()) {
data.LeafValues.assign(
fbObj->LeafValues()->data(),
fbObj->LeafValues()->data() + fbObj->LeafValues()->size()
);
}
if (fbObj->NonSymmetricStepNodes()) {
data.NonSymmetricStepNodes.resize(fbObj->NonSymmetricStepNodes()->size());
std::copy(
fbObj->NonSymmetricStepNodes()->begin(),
fbObj->NonSymmetricStepNodes()->end(),
data.NonSymmetricStepNodes.begin()
);
}
if (fbObj->NonSymmetricNodeIdToLeafId()) {
data.NonSymmetricNodeIdToLeafId.assign(
fbObj->NonSymmetricNodeIdToLeafId()->begin(), fbObj->NonSymmetricNodeIdToLeafId()->end()
);
}
if (fbObj->LeafWeights() && fbObj->LeafWeights()->size() > 0) {
data.LeafWeights.assign(
fbObj->LeafWeights()->data(),
fbObj->LeafWeights()->data() + fbObj->LeafWeights()->size()
);
}
if (fbObj->RepackedBins()) {
TVector<TRepackedBin> repackedBins(fbObj->RepackedBins()->size());
std::copy(
fbObj->RepackedBins()->begin(),
fbObj->RepackedBins()->end(),
repackedBins.begin()
);
RepackedBins = NCB::TMaybeOwningConstArrayHolder<TRepackedBin>::CreateOwning(std::move(repackedBins));
}
DeserializeFeatures(fbObj);
}
void TModelTrees::FBDeserializeNonOwning(const NCatBoostFbs::TModelTrees* fbObj) {
ModelTreeData = MakeHolder<TOpaqueModelTree>();
ApproxDimension = fbObj->ApproxDimension();
SetScaleAndBias(fbObj);
DeserializeFeatures(fbObj);
auto& data = *CastToOpaqueTree(*this);
if (fbObj->TreeSplits()) {
data.TreeSplits = TConstArrayRef<int>(fbObj->TreeSplits()->data(), fbObj->TreeSplits()->size());
}
if (fbObj->TreeSizes()) {
data.TreeSizes = TConstArrayRef<int>(fbObj->TreeSizes()->data(), fbObj->TreeSizes()->size());
}
if (fbObj->TreeStartOffsets()) {
data.TreeStartOffsets = TConstArrayRef<int>(fbObj->TreeStartOffsets()->data(), fbObj->TreeStartOffsets()->size());
}
if (fbObj->LeafValues()) {
data.LeafValues = TConstArrayRef<double>(fbObj->LeafValues()->data(), fbObj->LeafValues()->size());
}
if (fbObj->NonSymmetricStepNodes()) {
static_assert(sizeof(TNonSymmetricTreeStepNode) == sizeof(NCatBoostFbs::TNonSymmetricTreeStepNode));
auto ptr = reinterpret_cast<const TNonSymmetricTreeStepNode*>(fbObj->NonSymmetricStepNodes()->data());
data.NonSymmetricStepNodes = TConstArrayRef<TNonSymmetricTreeStepNode>(ptr, fbObj->NonSymmetricStepNodes()->size());
}
if (fbObj->NonSymmetricNodeIdToLeafId()) {
data.NonSymmetricNodeIdToLeafId = TConstArrayRef<ui32>(fbObj->NonSymmetricNodeIdToLeafId()->data(), fbObj->NonSymmetricNodeIdToLeafId()->size());
}
if (fbObj->LeafWeights() && fbObj->LeafWeights()->size() > 0) {
data.LeafWeights = TConstArrayRef<double>(fbObj->LeafWeights()->data(), fbObj->LeafWeights()->size());
}
if (fbObj->RepackedBins()) {
auto ptr = reinterpret_cast<const TRepackedBin*>(fbObj->RepackedBins()->data());
RepackedBins = NCB::TMaybeOwningConstArrayHolder<TRepackedBin>::CreateNonOwning(TArrayRef(ptr, fbObj->RepackedBins()->size()));
}
}
TConstArrayRef<int> TSolidModelTree::GetTreeSplits() const {
return TreeSplits;
}
TConstArrayRef<int> TSolidModelTree::GetTreeSizes() const {
return TreeSizes;
}
TConstArrayRef<int> TSolidModelTree::GetTreeStartOffsets() const {
return TreeStartOffsets;
}
TConstArrayRef<TNonSymmetricTreeStepNode> TSolidModelTree::GetNonSymmetricStepNodes() const {
return NonSymmetricStepNodes;
}
TConstArrayRef<ui32> TSolidModelTree::GetNonSymmetricNodeIdToLeafId() const {
return NonSymmetricNodeIdToLeafId;
}
TConstArrayRef<double> TSolidModelTree::GetLeafValues() const {
return LeafValues;
}
TConstArrayRef<double> TSolidModelTree::GetLeafWeights() const {
return LeafWeights;
}
THolder<IModelTreeData> TSolidModelTree::Clone(ECloningPolicy policy) const {
switch (policy) {
case ECloningPolicy::CloneAsOpaque: {
auto holder = MakeHolder<TOpaqueModelTree>();
holder->LeafValues = TConstArrayRef<double>(LeafValues.data(), LeafValues.size());
holder->LeafWeights = TConstArrayRef<double>(LeafWeights.data(), LeafWeights.size());
holder->NonSymmetricNodeIdToLeafId = TConstArrayRef<ui32>(NonSymmetricNodeIdToLeafId.data(), NonSymmetricNodeIdToLeafId.size());
holder->NonSymmetricStepNodes = TConstArrayRef<TNonSymmetricTreeStepNode>(NonSymmetricStepNodes.data(), NonSymmetricStepNodes.size());
holder->TreeSizes = TConstArrayRef<int>(TreeSizes.data(), TreeSizes.size());
holder->TreeSplits = TConstArrayRef<int>(TreeSplits.data(), TreeSplits.size());
holder->TreeStartOffsets = TConstArrayRef<int>(TreeStartOffsets.data(), TreeStartOffsets.size());
return holder;
}
default:
return MakeHolder<TSolidModelTree>(*this);
}
}
void TSolidModelTree::SetTreeSplits(const TVector<int> &v) {
TreeSplits = v;
}
void TSolidModelTree::SetTreeSizes(const TVector<int> &v) {
TreeSizes = v;
}
void TSolidModelTree::SetTreeStartOffsets(const TVector<int> &v) {
TreeStartOffsets = v;
}
void TSolidModelTree::SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode> &v) {
NonSymmetricStepNodes = v;
}
void TSolidModelTree::SetNonSymmetricNodeIdToLeafId(const TVector<ui32> &v) {
NonSymmetricNodeIdToLeafId = v;
}
void TSolidModelTree::SetLeafValues(const TVector<double> &v) {
LeafValues = v;
}
void TSolidModelTree::SetLeafWeights(const TVector<double> &v) {
LeafWeights = v;
}
TConstArrayRef<int> TOpaqueModelTree::GetTreeSplits() const {
return TreeSplits;
}
TConstArrayRef<int> TOpaqueModelTree::GetTreeSizes() const {
return TreeSizes;
}
TConstArrayRef<int> TOpaqueModelTree::GetTreeStartOffsets() const {
return TreeStartOffsets;
}
TConstArrayRef<TNonSymmetricTreeStepNode> TOpaqueModelTree::GetNonSymmetricStepNodes() const {
return NonSymmetricStepNodes;
}
TConstArrayRef<ui32> TOpaqueModelTree::GetNonSymmetricNodeIdToLeafId() const {
return NonSymmetricNodeIdToLeafId;
}
TConstArrayRef<double> TOpaqueModelTree::GetLeafValues() const {
return LeafValues;
}
TConstArrayRef<double> TOpaqueModelTree::GetLeafWeights() const {
return LeafWeights;
}
THolder<IModelTreeData> TOpaqueModelTree::Clone(ECloningPolicy policy) const {
switch (policy) {
case ECloningPolicy::CloneAsSolid: {
auto holder = MakeHolder<TSolidModelTree>();
holder->TreeSplits = TVector<int>(TreeSplits.begin(), TreeSplits.end());
holder->TreeSizes = TVector<int>(TreeSizes.begin(), TreeSizes.end());
holder->TreeStartOffsets = TVector<int>(TreeStartOffsets.begin(), TreeStartOffsets.end());
holder->NonSymmetricStepNodes = TVector<TNonSymmetricTreeStepNode>(NonSymmetricStepNodes.begin(), NonSymmetricStepNodes.end());
holder->NonSymmetricNodeIdToLeafId = TVector<ui32>(NonSymmetricNodeIdToLeafId.begin(), NonSymmetricNodeIdToLeafId.end());
holder->LeafValues = TVector<double>(LeafValues.begin(), LeafValues.end());
holder->LeafWeights = TVector<double>(LeafWeights.begin(), LeafWeights.end());
return holder;
}
default:
return MakeHolder<TOpaqueModelTree>(*this);
}
}
void TOpaqueModelTree::SetTreeSplits(const TVector<int>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetTreeSizes(const TVector<int>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetTreeStartOffsets(const TVector<int>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetNonSymmetricStepNodes(const TVector<TNonSymmetricTreeStepNode>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetNonSymmetricNodeIdToLeafId(const TVector<ui32>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetLeafValues(const TVector<double>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TOpaqueModelTree::SetLeafWeights(const TVector<double>&) {
CB_ENSURE(false, "Only solid models are modifiable");
}
void TFullModel::CalcFlat(
TConstArrayRef<TConstArrayRef<float>> features,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo) const {
GetCurrentEvaluator()->CalcFlat(features, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::CalcFlatSingle(
TConstArrayRef<float> features,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo) const {
GetCurrentEvaluator()->CalcFlatSingle(features, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::CalcFlatTransposed(
TConstArrayRef<TConstArrayRef<float>> transposedFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo) const {
GetCurrentEvaluator()->CalcFlatTransposed(transposedFeatures, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::Calc(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TConstArrayRef<int>> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo
) const {
GetCurrentEvaluator()->Calc(floatFeatures, catFeatures, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::Calc(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TVector<TStringBuf>> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo
) const {
TVector<TConstArrayRef<TStringBuf>> stringbufVecRefs{catFeatures.begin(), catFeatures.end()};
GetCurrentEvaluator()->Calc(floatFeatures, stringbufVecRefs, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::Calc(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TVector<TStringBuf>> catFeatures,
TConstArrayRef<TVector<TStringBuf>> textFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<double> results,
const TFeatureLayout* featureInfo
) const {
TVector<TConstArrayRef<TStringBuf>> stringbufCatVecRefs{catFeatures.begin(), catFeatures.end()};
TVector<TConstArrayRef<TStringBuf>> stringbufTextVecRefs{textFeatures.begin(), textFeatures.end()};
GetCurrentEvaluator()->Calc(floatFeatures, stringbufCatVecRefs, stringbufTextVecRefs, treeStart, treeEnd, results, featureInfo);
}
void TFullModel::CalcLeafIndexesSingle(
TConstArrayRef<float> floatFeatures,
TConstArrayRef<TStringBuf> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<ui32> indexes,
const TFeatureLayout* featureInfo
) const {
GetCurrentEvaluator()->CalcLeafIndexesSingle(floatFeatures, catFeatures, treeStart, treeEnd, indexes, featureInfo);
}
void TFullModel::CalcLeafIndexes(
TConstArrayRef<TConstArrayRef<float>> floatFeatures,
TConstArrayRef<TConstArrayRef<TStringBuf>> catFeatures,
size_t treeStart,
size_t treeEnd,
TArrayRef<ui32> indexes,
const TFeatureLayout* featureInfo
) const {
GetCurrentEvaluator()->CalcLeafIndexes(floatFeatures, catFeatures, treeStart, treeEnd, indexes, featureInfo);
}
void TFullModel::Save(IOutputStream* s) const {
using namespace flatbuffers;
using namespace NCatBoostFbs;
::Save(s, GetModelFormatDescriptor());
TModelPartsCachingSerializer serializer;
auto modelTreesOffset = ModelTrees->FBSerialize(serializer);
std::vector<flatbuffers::Offset<TKeyValue>> infoMap;
for (const auto& key_value : ModelInfo) {
auto keyValueOffset = CreateTKeyValue(
serializer.FlatbufBuilder,
serializer.FlatbufBuilder.CreateString(
key_value.first.c_str(),
key_value.first.size()
),
serializer.FlatbufBuilder.CreateString(
key_value.second.c_str(),
key_value.second.size()
)
);
infoMap.push_back(keyValueOffset);
}
std::vector<flatbuffers::Offset<flatbuffers::String>> modelPartIds;
if (!!CtrProvider && CtrProvider->IsSerializable()) {
modelPartIds.push_back(serializer.FlatbufBuilder.CreateString(CtrProvider->ModelPartIdentifier()));
}
if (!!TextProcessingCollection) {
modelPartIds.push_back(serializer.FlatbufBuilder.CreateString(TextProcessingCollection->GetStringIdentifier()));
}
if (!!EmbeddingProcessingCollection) {
modelPartIds.push_back(serializer.FlatbufBuilder.CreateString(EmbeddingProcessingCollection->GetStringIdentifier()));
}
auto coreOffset = CreateTModelCoreDirect(
serializer.FlatbufBuilder,
CURRENT_CORE_FORMAT_STRING,
modelTreesOffset,
infoMap.empty() ? nullptr : &infoMap,
modelPartIds.empty() ? nullptr : &modelPartIds
);
serializer.FlatbufBuilder.Finish(coreOffset);
SaveSize(s, serializer.FlatbufBuilder.GetSize());
s->Write(serializer.FlatbufBuilder.GetBufferPointer(), serializer.FlatbufBuilder.GetSize());
if (!!CtrProvider && CtrProvider->IsSerializable()) {
CtrProvider->Save(s);
}
if (!!TextProcessingCollection) {
TextProcessingCollection->Save(s);
}
if (!!EmbeddingProcessingCollection) {
EmbeddingProcessingCollection->Save(s);
}
}
void TFullModel::DefaultFullModelInit(const NCatBoostFbs::TModelCore* fbModelCore) {
CB_ENSURE(
fbModelCore->FormatVersion() && fbModelCore->FormatVersion()->str() == CURRENT_CORE_FORMAT_STRING,
"Unsupported model format: " << fbModelCore->FormatVersion()->str()
);
ModelInfo.clear();
if (fbModelCore->InfoMap()) {
for (auto keyVal : *fbModelCore->InfoMap()) {
ModelInfo[keyVal->Key()->str()] = keyVal->Value()->str();
}
}
}
void TFullModel::Load(IInputStream* s) {
ReferenceMainFactoryRegistrators();
using namespace flatbuffers;
using namespace NCatBoostFbs;
ui32 fileDescriptor;
::Load(s, fileDescriptor);
CB_ENSURE(fileDescriptor == GetModelFormatDescriptor(), "Incorrect model file descriptor");
auto coreSize = ::LoadSize(s);
TArrayHolder<ui8> arrayHolder(new ui8[coreSize]);
s->LoadOrFail(arrayHolder.Get(), coreSize);
{
flatbuffers::Verifier verifier(arrayHolder.Get(), coreSize, 64 /* max depth */, 256000000 /* max tables */);
CB_ENSURE(VerifyTModelCoreBuffer(verifier), "Flatbuffers model verification failed");
}
auto fbModelCore = GetTModelCore(arrayHolder.Get());
DefaultFullModelInit(fbModelCore);
if (fbModelCore->ModelTrees()) {
ModelTrees.GetMutable()->FBDeserializeOwning(fbModelCore->ModelTrees());
}
TVector<TString> modelParts;
if (fbModelCore->ModelPartIds()) {
for (auto part : *fbModelCore->ModelPartIds()) {
modelParts.emplace_back(part->str());
}
}
if (!modelParts.empty()) {
for (const auto& modelPartId : modelParts) {
if (modelPartId == TStaticCtrProvider::ModelPartId()) {
CtrProvider = new TStaticCtrProvider;
CtrProvider->Load(s);
} else if (modelPartId == NCB::TTextProcessingCollection::GetStringIdentifier()) {
TextProcessingCollection = new NCB::TTextProcessingCollection();
TextProcessingCollection->Load(s);
} else if (modelPartId == NCB::TEmbeddingProcessingCollection::GetStringIdentifier()) {
EmbeddingProcessingCollection = new NCB::TEmbeddingProcessingCollection();
EmbeddingProcessingCollection->Load(s);
} else {
CB_ENSURE(
false,
"Got unknown partId = " << modelPartId << " via deserialization"
<< "only static ctr and text processing collection model parts are supported"
);
}
}
}
UpdateDynamicData();
}
void TFullModel::InitNonOwning(const void* binaryBuffer, size_t binarySize) {
using namespace flatbuffers;
using namespace NCatBoostFbs;
TMemoryInput in(binaryBuffer, binarySize);
ui32 fileDescriptor;
::Load(&in, fileDescriptor);
CB_ENSURE(fileDescriptor == GetModelFormatDescriptor(), "Incorrect model file descriptor");
size_t coreSize = ::LoadSize(&in);
const ui8* fbPtr = reinterpret_cast<const ui8*>(in.Buf());
in.Skip(coreSize);
{
flatbuffers::Verifier verifier(fbPtr, coreSize, 64 /* max depth */, 256000000 /* max tables */);
CB_ENSURE(VerifyTModelCoreBuffer(verifier), "Flatbuffers model verification failed");
}
auto fbModelCore = GetTModelCore(fbPtr);
DefaultFullModelInit(fbModelCore);
if (fbModelCore->ModelTrees()) {
ModelTrees.GetMutable()->FBDeserializeNonOwning(fbModelCore->ModelTrees());
}
TVector<TString> modelParts;
if (fbModelCore->ModelPartIds()) {
for (auto part : *fbModelCore->ModelPartIds()) {
modelParts.emplace_back(part->str());
}
}
if (!modelParts.empty()) {
for (const auto& modelPartId : modelParts) {
if (modelPartId == TStaticCtrProvider::ModelPartId()) {
auto ptr = new TStaticCtrProvider;
CtrProvider = ptr;
ptr->LoadNonOwning(&in);
} else if (modelPartId == NCB::TTextProcessingCollection::GetStringIdentifier()) {
TextProcessingCollection = new NCB::TTextProcessingCollection();
TextProcessingCollection->LoadNonOwning(&in);
} else if (modelPartId == NCB::TEmbeddingProcessingCollection::GetStringIdentifier()) {
EmbeddingProcessingCollection = new NCB::TEmbeddingProcessingCollection();
EmbeddingProcessingCollection->LoadNonOwning(&in);
} else {
CB_ENSURE(
false,
"Got unknown partId = " << modelPartId << " via deserialization"
<< "only static ctr and text processing collection model parts are supported"
);
}
}
}
UpdateDynamicData();
}
void TFullModel::UpdateDynamicData() {
ModelTrees.GetMutable()->UpdateRuntimeData();
if (CtrProvider) {
CtrProvider->SetupBinFeatureIndexes(
ModelTrees->GetFloatFeatures(),
ModelTrees->GetOneHotFeatures(),
ModelTrees->GetCatFeatures());
}
with_lock(CurrentEvaluatorLock) {
Evaluator.Reset();
}
}
TVector<TString> GetModelUsedFeaturesNames(const TFullModel& model) {
TVector<int> featuresIdxs;
TVector<TString> featuresNames;
const TModelTrees& forest = *model.ModelTrees;
for (const TFloatFeature& feature : forest.GetFloatFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
for (const TCatFeature& feature : forest.GetCatFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
for (const TTextFeature& feature : forest.GetTextFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
for (const TEmbeddingFeature& feature : forest.GetEmbeddingFeatures()) {
featuresIdxs.push_back(feature.Position.FlatIndex);
featuresNames.push_back(
feature.FeatureId == "" ? ToString(feature.Position.FlatIndex) : feature.FeatureId
);
}
TVector<int> featuresOrder(featuresIdxs.size());
Iota(featuresOrder.begin(), featuresOrder.end(), 0);
Sort(featuresOrder.begin(), featuresOrder.end(),
[featuresIdxs](int index1, int index2) {
return featuresIdxs[index1] < featuresIdxs[index2];
}
);
TVector<TString> result(featuresNames.size());
for (int featureIdx = 0; featureIdx < featuresNames.ysize(); ++featureIdx) {
result[featureIdx] = featuresNames[featuresOrder[featureIdx]];
}
return result;
}
void SetModelExternalFeatureNames(const TVector<TString>& featureNames, TFullModel* model) {
TModelTrees& forest = *(model->ModelTrees.GetMutable());
CB_ENSURE(
(forest.GetFloatFeatures().empty() || featureNames.ysize() > forest.GetFloatFeatures().back().Position.FlatIndex) &&
(forest.GetCatFeatures().empty() || featureNames.ysize() > forest.GetCatFeatures().back().Position.FlatIndex),
"Features in model not corresponds to features names array length not correspond");
forest.ApplyFeatureNames(featureNames);
}
static TMaybe<NCatboostOptions::TLossDescription> GetLossDescription(const TFullModel& model) {
TMaybe<NCatboostOptions::TLossDescription> lossDescription;
if (model.ModelInfo.contains("loss_function")) {
lossDescription.ConstructInPlace();
lossDescription->Load(ReadTJsonValue(model.ModelInfo.at("loss_function")));
}
if (model.ModelInfo.contains("params")) {
const auto& params = ReadTJsonValue(model.ModelInfo.at("params"));
if (params.Has("loss_function")) {
lossDescription.ConstructInPlace();
lossDescription->Load(params["loss_function"]);
}
}
return lossDescription;
}
TString TFullModel::GetLossFunctionName() const {
const TMaybe<NCatboostOptions::TLossDescription> lossDescription = GetLossDescription(*this);
if (lossDescription.Defined()) {
return ToString(lossDescription->GetLossFunction());
}
return {};
}
static TVector<NJson::TJsonValue> GetSequentialIntegerClassLabels(size_t classCount) {
TVector<NJson::TJsonValue> classLabels;
classLabels.reserve(classCount);
for (int classIdx : xrange(SafeIntegerCast<int>(classCount))) {
classLabels.emplace_back(classIdx);
}
return classLabels;
}
TVector<NJson::TJsonValue> TFullModel::GetModelClassLabels() const {
TVector<NJson::TJsonValue> classLabels;
TMaybe<TClassLabelOptions> classOptions;
// "class_params" is new, more generic option, used for binclass as well
for (const auto& paramName : {"class_params", "multiclass_params"}) {
if (ModelInfo.contains(paramName)) {
classOptions.ConstructInPlace();
classOptions->Load(ReadTJsonValue(ModelInfo.at(paramName)));
break;
}
}
if (classOptions.Defined()) {
if (classOptions->ClassLabels.IsSet()) {
classLabels = classOptions->ClassLabels.Get();
if (!classLabels.empty()) {
return classLabels;
}
}
if (classOptions->ClassesCount.IsSet()) {
const size_t classesCount = SafeIntegerCast<size_t>(classOptions->ClassesCount.Get());
if (classesCount) {
return GetSequentialIntegerClassLabels(classesCount);
}
}
if (classOptions->ClassToLabel.IsSet()) {
classLabels.reserve(classOptions->ClassToLabel->size());
for (float label : classOptions->ClassToLabel.Get()) {
classLabels.emplace_back(int(label));
}
return classLabels;
}
}
if (ModelInfo.contains("params")) {
const TString& modelInfoParams = ModelInfo.at("params");
NJson::TJsonValue paramsJson = ReadTJsonValue(modelInfoParams);
if (paramsJson.Has("data_processing_options")
&& paramsJson["data_processing_options"].Has("class_names")) {
const NJson::TJsonValue::TArray& classLabelsJsonArray
= paramsJson["data_processing_options"]["class_names"].GetArraySafe();
if (!classLabelsJsonArray.empty()) {
classLabels.assign(classLabelsJsonArray.begin(), classLabelsJsonArray.end());
return classLabels;
}
}
}
const TMaybe<NCatboostOptions::TLossDescription> lossDescription = GetLossDescription(*this);
if (lossDescription.Defined() && IsClassificationObjective(lossDescription->GetLossFunction())) {
const size_t dimensionsCount = GetDimensionsCount();
return GetSequentialIntegerClassLabels((dimensionsCount == 1) ? 2 : dimensionsCount);
}
return classLabels;
}
void TFullModel::UpdateEstimatedFeaturesIndices(TVector<TEstimatedFeature>&& newEstimatedFeatures) {
CB_ENSURE(
TextProcessingCollection || EmbeddingProcessingCollection,
"UpdateEstimatedFeatureIndices called when ProcessingCollections aren't defined"
);
ModelTrees.GetMutable()->SetEstimatedFeatures(std::move(newEstimatedFeatures));
ModelTrees.GetMutable()->UpdateRuntimeData();
}
bool TFullModel::IsPosteriorSamplingModel() const {
if (ModelInfo.contains("params")) {
const TString& modelInfoParams = ModelInfo.at("params");
NJson::TJsonValue paramsJson = ReadTJsonValue(modelInfoParams);
if (paramsJson.Has("boosting_options") && paramsJson["boosting_options"].Has("posterior_sampling")) {
return paramsJson["boosting_options"]["posterior_sampling"].GetBoolean();
}
}
return false;
}
float TFullModel::GetActualShrinkCoef() const {
CB_ENSURE(ModelInfo.contains("params"), "No params in model");
const TString& modelInfoParams = ModelInfo.at("params");
NJson::TJsonValue paramsJson = ReadTJsonValue(modelInfoParams);
CB_ENSURE(paramsJson.Has("boosting_options"), "No boosting_options parameters in model");
CB_ENSURE(paramsJson["boosting_options"].Has("learning_rate"),
"No parameter learning_rate in model boosting_options");
CB_ENSURE(paramsJson["boosting_options"].Has("model_shrink_rate"),
"No parameter model_shrink_rate in model boosting_options");
return paramsJson["boosting_options"]["learning_rate"].GetDouble() * paramsJson["boosting_options"]["model_shrink_rate"].GetDouble();
}
namespace {
struct TUnknownFeature {};
struct TFlatFeature {
TVariant<TUnknownFeature, TFloatFeature, TCatFeature> FeatureVariant;
public:
TFlatFeature() = default;
template <class TFeatureType>
void SetOrCheck(const TFeatureType& other) {
if (HoldsAlternative<TUnknownFeature>(FeatureVariant)) {
FeatureVariant = other;
}
CB_ENSURE(HoldsAlternative<TFeatureType>(FeatureVariant),
"Feature type mismatch: Categorical != Float for flat feature index: " <<
other.Position.FlatIndex
);
TFeatureType& feature = Get<TFeatureType>(FeatureVariant);
CB_ENSURE(feature.Position.FlatIndex == other.Position.FlatIndex);
CB_ENSURE(
feature.Position.Index == other.Position.Index,
"Internal feature index mismatch: " << feature.Position.Index << " != "
<< other.Position.Index << " flat feature index: " << feature.Position.FlatIndex
);
CB_ENSURE(
feature.FeatureId.empty() || feature.FeatureId == other.FeatureId,
"Feature name mismatch: " << feature.FeatureId << " != " << other.FeatureId
<< " flat feature index: " << feature.Position.FlatIndex
);
feature.FeatureId = other.FeatureId;
if constexpr (std::is_same_v<TFeatureType, TFloatFeature>) {
constexpr auto asFalse = TFloatFeature::ENanValueTreatment::AsFalse;
constexpr auto asIs = TFloatFeature::ENanValueTreatment::AsIs;
if (
(feature.NanValueTreatment == asIs && other.NanValueTreatment == asFalse) ||
(feature.NanValueTreatment == asFalse && other.NanValueTreatment == asIs)
) {
// We can relax Nan treatmen comparison as nans within AsIs strategy are always treated like AsFalse
// TODO(kirillovs): later implement splitted storage for float feautres with different Nan treatment
feature.NanValueTreatment = asFalse;
} else {
CB_ENSURE(
feature.NanValueTreatment == other.NanValueTreatment,
"Nan value treatment differs: " << (int) feature.NanValueTreatment << " != " <<
(int) other.NanValueTreatment
);
}
feature.HasNans |= other.HasNans;
}
}
};
struct TFlatFeatureMergerVisitor {
void operator()(TUnknownFeature&) {
}
void operator()(TFloatFeature& s) {
MergedFloatFeatures.push_back(s);
}
void operator()(TCatFeature& x) {
MergedCatFeatures.push_back(x);
}
TVector<TFloatFeature> MergedFloatFeatures;
TVector<TCatFeature> MergedCatFeatures;
};
}
static void StreamModelTreesWithoutScaleAndBiasToBuilder(
const TModelTrees& trees,
double leafMultiplier,
TObliviousTreeBuilder* builder,
bool streamLeafWeights)
{
auto& data = trees.GetModelTreeData();
const auto& binFeatures = trees.GetBinFeatures();
auto applyData = trees.GetApplyData();
const auto& leafOffsets = applyData->TreeFirstLeafOffsets;
for (size_t treeIdx = 0; treeIdx < data->GetTreeSizes().size(); ++treeIdx) {
TVector<TModelSplit> modelSplits;
for (int splitIdx = data->GetTreeStartOffsets()[treeIdx];
splitIdx < data->GetTreeStartOffsets()[treeIdx] + data->GetTreeSizes()[treeIdx];
++splitIdx)
{
modelSplits.push_back(binFeatures[data->GetTreeSplits()[splitIdx]]);
}
if (leafMultiplier == 1.0) {
TConstArrayRef<double> leafValuesRef(
data->GetLeafValues().begin() + leafOffsets[treeIdx],
data->GetLeafValues().begin() + leafOffsets[treeIdx]
+ trees.GetDimensionsCount() * (1ull << data->GetTreeSizes()[treeIdx])
);
builder->AddTree(
modelSplits,
leafValuesRef,
!streamLeafWeights ? TConstArrayRef<double>() : TConstArrayRef<double>(
data->GetLeafWeights().begin() + leafOffsets[treeIdx] / trees.GetDimensionsCount(),
data->GetLeafWeights().begin() + leafOffsets[treeIdx] / trees.GetDimensionsCount()
+ (1ull << data->GetTreeSizes()[treeIdx])
)
);
} else {
TVector<double> leafValues(
data->GetLeafValues().begin() + leafOffsets[treeIdx],
data->GetLeafValues().begin() + leafOffsets[treeIdx]
+ trees.GetDimensionsCount() * (1ull << data->GetTreeSizes()[treeIdx])
);
for (auto& leafValue: leafValues) {
leafValue *= leafMultiplier;
}
builder->AddTree(
modelSplits,
leafValues,
!streamLeafWeights ? TConstArrayRef<double>() : TConstArrayRef<double>(
data->GetLeafWeights().begin() + leafOffsets[treeIdx] / trees.GetDimensionsCount(),
(1ull << data->GetTreeSizes()[treeIdx])
)
);
}
}
}
static void SumModelsParams(
const TVector<const TFullModel*> modelVector,
THashMap<TString, TString>* modelInfo
) {
TMaybe<TString> classParams;
auto dimensionsCount = modelVector.back()->GetDimensionsCount();
for (auto modelIdx : xrange(modelVector.size())) {
const auto& modelInfo = modelVector[modelIdx]->ModelInfo;
bool paramFound = false;
for (const auto& paramName : {"class_params", "multiclass_params"}) {
if (modelInfo.contains(paramName)) {
if (classParams) {
CB_ENSURE(
modelInfo.at(paramName) == *classParams,
"Cannot sum models with different class params"
);
} else if ((modelIdx == 0) || (dimensionsCount == 1)) {
// it is ok only for 1-dimensional models to have only some classParams specified
classParams = modelInfo.at(paramName);
} else {
CB_ENSURE(false, "Cannot sum multidimensional models with and without class params");
}
paramFound = true;
break;
}
}
if ((modelIdx != 0) && classParams && !paramFound && (dimensionsCount > 1)) {
CB_ENSURE(false, "Cannot sum multidimensional models with and without class params");
}
}
if (classParams) {
(*modelInfo)["class_params"] = *classParams;
} else {
/* One-dimensional models.
* If class labels for binary classification are present they must be the same
*/
TMaybe<TVector<NJson::TJsonValue>> sumClassLabels;
for (const TFullModel* model : modelVector) {
TVector<NJson::TJsonValue> classLabels = model->GetModelClassLabels();
if (classLabels) {
Y_VERIFY(classLabels.size() == 2);
if (sumClassLabels) {
CB_ENSURE(classLabels == *sumClassLabels, "Cannot sum models with different class labels");
} else {
sumClassLabels = std::move(classLabels);
}
}
}
if (sumClassLabels) {
TString& paramsString = (*modelInfo)["params"];
NJson::TJsonValue paramsJson;
if (paramsString) {
paramsJson = ReadTJsonValue(paramsString);
}
NJson::TJsonValue classNames;
classNames.AppendValue((*sumClassLabels)[0]);
classNames.AppendValue((*sumClassLabels)[1]);
paramsJson["data_processing_options"]["class_names"] = std::move(classNames);
paramsString = ToString(paramsJson);
}
}
const auto lossDescription = GetLossDescription(*modelVector.back());
if (lossDescription.Defined()) {
const bool allLossesAreSame = AllOf(
modelVector,
[&lossDescription](const TFullModel* model) {
const auto currentLossDescription = GetLossDescription(*model);
return currentLossDescription.Defined() && ((*currentLossDescription) == (*lossDescription));
}
);
if (allLossesAreSame) {
NJson::TJsonValue lossDescriptionJson;
lossDescription->Save(&lossDescriptionJson);
(*modelInfo)["loss_function"] = ToString(lossDescriptionJson);
}
}
if (!AllOf(modelVector, [&](const TFullModel* model) {
return model->GetScaleAndBias().IsIdentity();
}))
{
NJson::TJsonValue summandScaleAndBiases;
for (const auto& model : modelVector) {
NJson::TJsonValue scaleAndBias;
scaleAndBias.InsertValue("scale", model->GetScaleAndBias().Scale);
NJson::TJsonValue biasValue;
auto bias = model->GetScaleAndBias().GetBiasRef();
for (auto b : bias) {
biasValue.AppendValue(b);
}
scaleAndBias.InsertValue("bias", biasValue);
summandScaleAndBiases.AppendValue(scaleAndBias);
}
(*modelInfo)["summand_scale_and_biases"] = summandScaleAndBiases.GetStringRobust();
}
}
TFullModel SumModels(
const TVector<const TFullModel*> modelVector,
const TVector<double>& weights,
ECtrTableMergePolicy ctrMergePolicy)
{
CB_ENSURE(!modelVector.empty(), "empty model vector unexpected");
CB_ENSURE(modelVector.size() == weights.size());
const auto approxDimension = modelVector.back()->GetDimensionsCount();
size_t maxFlatFeatureVectorSize = 0;
TVector<TIntrusivePtr<ICtrProvider>> ctrProviders;
bool allModelsHaveLeafWeights = true;
bool someModelHasLeafWeights = false;
for (const auto& model : modelVector) {
Y_ASSERT(model != nullptr);
//TODO(eermishkina): support non symmetric trees
CB_ENSURE(model->IsOblivious(), "Models summation supported only for symmetric trees");
CB_ENSURE(
model->ModelTrees->GetTextFeatures().empty(),
"Models summation is not supported for models with text features"
);
CB_ENSURE(
model->GetDimensionsCount() == approxDimension,
"Approx dimensions don't match: " << model->GetDimensionsCount() << " != "
<< approxDimension
);
maxFlatFeatureVectorSize = Max(
maxFlatFeatureVectorSize,
model->ModelTrees->GetFlatFeatureVectorExpectedSize()
);
ctrProviders.push_back(model->CtrProvider);
// empty model does not disable LeafWeights:
if (model->ModelTrees->GetModelTreeData()->GetLeafWeights().size() < model->GetTreeCount()) {
allModelsHaveLeafWeights = false;
}
if (!model->ModelTrees->GetModelTreeData()->GetLeafWeights().empty()) {
someModelHasLeafWeights = true;
}
}
if (!allModelsHaveLeafWeights && someModelHasLeafWeights) {
CATBOOST_WARNING_LOG << "Leaf weights for some models are ignored " <<
"because not all models have leaf weights" << Endl;
}
TVector<TFlatFeature> flatFeatureInfoVector(maxFlatFeatureVectorSize);
for (const auto& model : modelVector) {
for (const auto& floatFeature : model->ModelTrees->GetFloatFeatures()) {
flatFeatureInfoVector[floatFeature.Position.FlatIndex].SetOrCheck(floatFeature);
}
for (const auto& catFeature : model->ModelTrees->GetCatFeatures()) {
flatFeatureInfoVector[catFeature.Position.FlatIndex].SetOrCheck(catFeature);
}
}
TFlatFeatureMergerVisitor merger;
for (auto& flatFeature: flatFeatureInfoVector) {
Visit(merger, flatFeature.FeatureVariant);
}
TObliviousTreeBuilder builder(merger.MergedFloatFeatures, merger.MergedCatFeatures, {}, {}, approxDimension);
TVector<double> totalBias(approxDimension);
for (const auto modelId : xrange(modelVector.size())) {
TScaleAndBias normer = modelVector[modelId]->GetScaleAndBias();
auto normerBias = normer.GetBiasRef();
if (!normerBias.empty()) {
CB_ENSURE(totalBias.size() == normerBias.size(), "Bias dimensions missmatch");
for (auto dim : xrange(totalBias.size())) {
totalBias[dim] += weights[modelId] * normerBias[dim];
}
}
StreamModelTreesWithoutScaleAndBiasToBuilder(
*modelVector[modelId]->ModelTrees,
weights[modelId] * normer.Scale,
&builder,
allModelsHaveLeafWeights
);
}
TFullModel result;
builder.Build(result.ModelTrees.GetMutable());
for (const auto modelIdx : xrange(modelVector.size())) {
TStringBuilder keyPrefix;
keyPrefix << "model" << modelIdx << ":";
for (const auto& [key, value]: modelVector[modelIdx]->ModelInfo) {
result.ModelInfo[keyPrefix + key] = value;
}
}
result.CtrProvider = MergeCtrProvidersData(ctrProviders, ctrMergePolicy);
result.UpdateDynamicData();
result.ModelInfo["model_guid"] = CreateGuidAsString();
result.SetScaleAndBias({1, totalBias});
SumModelsParams(modelVector, &result.ModelInfo);
return result;
}
void SaveModelBorders(
const TString& file,
const TFullModel& model) {
TOFStream out(file);
for (const auto& feature : model.ModelTrees->GetFloatFeatures()) {
NCB::OutputFeatureBorders(
feature.Position.FlatIndex,
feature.Borders,
NanValueTreatmentToNanMode(feature.NanValueTreatment),
&out
);
}
}
THashMap<int, TFloatFeature::ENanValueTreatment> GetNanTreatments(const TFullModel& model) {
THashMap<int, TFloatFeature::ENanValueTreatment> nanTreatments;
for (const auto& feature : model.ModelTrees->GetFloatFeatures()) {
nanTreatments[feature.Position.FlatIndex] = feature.NanValueTreatment;
}
return nanTreatments;
}
DEFINE_DUMPER(TRepackedBin, FeatureIndex, XorMask, SplitIdx)
DEFINE_DUMPER(TNonSymmetricTreeStepNode, LeftSubtreeDiff, RightSubtreeDiff)
DEFINE_DUMPER(
TModelTrees::TRuntimeData,
BinFeatures,
EffectiveBinFeaturesBucketCount
)
DEFINE_DUMPER(
TModelTrees::TForApplyData,
UsedFloatFeaturesCount,
UsedCatFeaturesCount,
MinimalSufficientFloatFeaturesVectorSize,
MinimalSufficientCatFeaturesVectorSize,
UsedModelCtrs,
TreeFirstLeafOffsets
)
//DEFINE_DUMPER(TModelTrees),
// TreeSplits, TreeSizes,
// TreeStartOffsets, NonSymmetricStepNodes,
// NonSymmetricNodeIdToLeafId, LeafValues);
TNonSymmetricTreeStepNode& TNonSymmetricTreeStepNode::operator=(const NCatBoostFbs::TNonSymmetricTreeStepNode* stepNode) {
LeftSubtreeDiff = stepNode->LeftSubtreeDiff();
RightSubtreeDiff = stepNode->RightSubtreeDiff();
return *this;
}
TRepackedBin& TRepackedBin::operator=(const NCatBoostFbs::TRepackedBin* repackedBin) {
std::tie(
FeatureIndex,
XorMask,
SplitIdx
) = std::forward_as_tuple(
repackedBin->FeatureIndex(),
repackedBin->XorMask(),
repackedBin->SplitIdx()
);
return *this;
}
| 40.792172
| 154
| 0.672392
|
notimesea
|
28524420cfa7183d7514ffa340993f720ee587fe
| 4,255
|
cc
|
C++
|
quic/quic_transport/quic_transport_stream.cc
|
fawdlstty/quiche
|
dfabdfb6884bf8ccd92c6f818aa8764a84f5a984
|
[
"BSD-3-Clause"
] | 1
|
2021-10-17T09:43:24.000Z
|
2021-10-17T09:43:24.000Z
|
quic/quic_transport/quic_transport_stream.cc
|
fawdlstty/quiche
|
dfabdfb6884bf8ccd92c6f818aa8764a84f5a984
|
[
"BSD-3-Clause"
] | null | null | null |
quic/quic_transport/quic_transport_stream.cc
|
fawdlstty/quiche
|
dfabdfb6884bf8ccd92c6f818aa8764a84f5a984
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2019 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 "net/third_party/quiche/src/quic/quic_transport/quic_transport_stream.h"
#include <sys/types.h>
#include "net/third_party/quiche/src/quic/core/quic_buffer_allocator.h"
#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
namespace quic {
QuicTransportStream::QuicTransportStream(
QuicStreamId id,
QuicSession* session,
QuicTransportSessionInterface* session_interface)
: QuicStream(id,
session,
/*is_static=*/false,
QuicUtils::GetStreamType(id,
session->connection()->perspective(),
session->IsIncomingStream(id))),
session_interface_(session_interface) {}
size_t QuicTransportStream::Read(char* buffer, size_t buffer_size) {
if (!session_interface_->IsSessionReady()) {
return 0;
}
iovec iov;
iov.iov_base = buffer;
iov.iov_len = buffer_size;
const size_t result = sequencer()->Readv(&iov, 1);
if (sequencer()->IsClosed() && visitor_ != nullptr) {
visitor_->OnFinRead();
}
return result;
}
size_t QuicTransportStream::Read(std::string* output) {
const size_t old_size = output->size();
const size_t bytes_to_read = ReadableBytes();
output->resize(old_size + bytes_to_read);
size_t bytes_read = Read(&(*output)[old_size], bytes_to_read);
DCHECK_EQ(bytes_to_read, bytes_read);
output->resize(old_size + bytes_read);
return bytes_read;
}
bool QuicTransportStream::Write(quiche::QuicheStringPiece data) {
if (!CanWrite()) {
return false;
}
QuicUniqueBufferPtr buffer = MakeUniqueBuffer(
session()->connection()->helper()->GetStreamSendBufferAllocator(),
data.size());
memcpy(buffer.get(), data.data(), data.size());
QuicMemSlice memslice(std::move(buffer), data.size());
QuicConsumedData consumed =
WriteMemSlices(QuicMemSliceSpan(&memslice), /*fin=*/false);
if (consumed.bytes_consumed == data.size()) {
return true;
}
if (consumed.bytes_consumed == 0) {
return false;
}
// QuicTransportStream::Write() is an all-or-nothing write API. To achieve
// that property, it relies on WriteMemSlices() being an all-or-nothing API.
// If WriteMemSlices() fails to provide that guarantee, we have no way to
// communicate a partial write to the caller, and thus it's safer to just
// close the connection.
QUIC_BUG << "WriteMemSlices() unexpectedly partially consumed the input "
"data, provided: "
<< data.size() << ", written: " << consumed.bytes_consumed;
CloseConnectionWithDetails(
QUIC_INTERNAL_ERROR,
"WriteMemSlices() unexpectedly partially consumed the input data");
return false;
}
bool QuicTransportStream::SendFin() {
if (!CanWrite()) {
return false;
}
QuicMemSlice empty;
QuicConsumedData consumed =
WriteMemSlices(QuicMemSliceSpan(&empty), /*fin=*/true);
DCHECK_EQ(consumed.bytes_consumed, 0u);
return consumed.fin_consumed;
}
bool QuicTransportStream::CanWrite() const {
return session_interface_->IsSessionReady() && CanWriteNewData() &&
!write_side_closed();
}
size_t QuicTransportStream::ReadableBytes() const {
if (!session_interface_->IsSessionReady()) {
return 0;
}
return sequencer()->ReadableBytes();
}
void QuicTransportStream::OnDataAvailable() {
if (sequencer()->IsClosed()) {
if (visitor_ != nullptr) {
visitor_->OnFinRead();
}
OnFinRead();
return;
}
if (visitor_ == nullptr) {
return;
}
if (ReadableBytes() == 0) {
return;
}
visitor_->OnCanRead();
}
void QuicTransportStream::OnCanWriteNewData() {
// Ensure the origin check has been completed, as the stream can be notified
// about being writable before that.
if (!CanWrite()) {
return;
}
if (visitor_ != nullptr) {
visitor_->OnCanWrite();
}
}
} // namespace quic
| 29.964789
| 81
| 0.682961
|
fawdlstty
|
28530a40e5accd8f31daea09b54aff0474526fb5
| 3,707
|
hpp
|
C++
|
src/ui/AboutDialog/AboutDialog.hpp
|
ATiltedTree/APASSTools
|
1702e082ae3b95ec10f3c5c084ef9396de5c3833
|
[
"MIT"
] | null | null | null |
src/ui/AboutDialog/AboutDialog.hpp
|
ATiltedTree/APASSTools
|
1702e082ae3b95ec10f3c5c084ef9396de5c3833
|
[
"MIT"
] | 4
|
2020-02-25T00:21:58.000Z
|
2020-07-03T11:12:03.000Z
|
src/ui/AboutDialog/AboutDialog.hpp
|
ATiltedTree/APASSTools
|
1702e082ae3b95ec10f3c5c084ef9396de5c3833
|
[
"MIT"
] | null | null | null |
#pragma once
#include "common/Icon.hpp"
#include <QApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QLayout>
#include <config.hpp>
constexpr int ICON_SIZE = 100;
namespace Ui {
class AboutDialog {
public:
QGridLayout *gridLayout;
QLabel *lableTitle;
QLabel *lableIcon;
QLabel *lableDesc;
QDialogButtonBox *buttonBox;
QDialog *parent;
AboutDialog(QDialog *parent)
: gridLayout(new QGridLayout(parent)), lableTitle(new QLabel(parent)),
lableIcon(new QLabel(parent)), lableDesc(new QLabel(parent)),
buttonBox(new QDialogButtonBox(parent)), parent(parent) {}
void setupUi() const {
parent->window()->layout()->setSizeConstraint(
QLayout::SizeConstraint::SetFixedSize);
parent->setWindowFlag(Qt::WindowType::MSWindowsFixedSizeDialogHint, true);
parent->setWindowIcon(getIcon(Icon::HelpAbout));
lableTitle->setText(
QObject::tr("<p><span style=\"font-size: 14pt; "
"font-weight:600;\">%1<span/><p/>"
"<p>Version: %2"
"<br/>Build with: %4 %5, %6"
"<br/>Copyright (c) 2020 Tilmann Meyer<p/>")
.arg(CONFIG_APP_NAME, CONFIG_APP_VERSION, CONFIG_COMPILER,
CONFIG_COMPILER_VERSION, CONFIG_COMPILER_ARCH));
lableDesc->setText(
"Permission is hereby granted, free of charge, to any person "
"obtaining a copy\n"
"of this software and associated documentation files (the "
"\"Software\"), to deal\n"
"in the Software without restriction, including without limitation "
"the rights\n"
"to use, copy, modify, merge, publish, distribute, sublicense, "
"and/or sell\n"
"copies of the Software, and to permit persons to whom the Software "
"is\n"
"furnished to do so, subject to the following conditions:\n"
"\n"
"The above copyright notice and this permission notice shall be "
"included in all\n"
"copies or substantial portions of the Software.\n"
"\n"
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
"EXPRESS OR\n"
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
"MERCHANTABILITY,\n"
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
"SHALL THE\n"
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
"OTHER\n"
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
"ARISING FROM,\n"
"OUT OF OR IN CONNECTION WI"
"TH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n"
"SOFTWARE\n");
lableIcon->setMaximumSize(QSize(ICON_SIZE, ICON_SIZE));
lableIcon->setPixmap(getIcon(Icon::Logo).pixmap(ICON_SIZE));
lableIcon->setScaledContents(true);
buttonBox->setOrientation(Qt::Orientation::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::StandardButton::Ok);
gridLayout->addWidget(buttonBox, 2, 0, 1, 2);
gridLayout->addWidget(lableIcon, 0, 0, 1, 1);
gridLayout->addWidget(lableDesc, 1, 0, 1, 2);
gridLayout->addWidget(lableTitle, 0, 1, 1, 1);
retranslateUi();
}
void retranslateUi() const {
parent->setWindowTitle(
QCoreApplication::translate("AboutDialog", "About", nullptr));
}
};
} // namespace Ui
class AboutDialog : public QDialog {
Q_OBJECT
public:
explicit AboutDialog(QWidget *parent);
private:
Ui::AboutDialog *ui;
};
| 34.64486
| 80
| 0.626113
|
ATiltedTree
|
2853a4fae21d10d113c59f1e5e720e1c399ab643
| 3,304
|
cpp
|
C++
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp
|
AlexVlk/ifcplusplus
|
2f8cd5457312282b8d90b261dbf8fb66e1c84057
|
[
"MIT"
] | 426
|
2015-04-12T10:00:46.000Z
|
2022-03-29T11:03:02.000Z
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp
|
AlexVlk/ifcplusplus
|
2f8cd5457312282b8d90b261dbf8fb66e1c84057
|
[
"MIT"
] | 124
|
2015-05-15T05:51:00.000Z
|
2022-02-09T15:25:12.000Z
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcActuatorTypeEnum.cpp
|
AlexVlk/ifcplusplus
|
2f8cd5457312282b8d90b261dbf8fb66e1c84057
|
[
"MIT"
] | 214
|
2015-05-06T07:30:37.000Z
|
2022-03-26T16:14:04.000Z
|
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcActuatorTypeEnum.h"
// TYPE IfcActuatorTypeEnum = ENUMERATION OF (ELECTRICACTUATOR ,HANDOPERATEDACTUATOR ,HYDRAULICACTUATOR ,PNEUMATICACTUATOR ,THERMOSTATICACTUATOR ,USERDEFINED ,NOTDEFINED);
shared_ptr<BuildingObject> IfcActuatorTypeEnum::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcActuatorTypeEnum> copy_self( new IfcActuatorTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcActuatorTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCACTUATORTYPEENUM("; }
switch( m_enum )
{
case ENUM_ELECTRICACTUATOR: stream << ".ELECTRICACTUATOR."; break;
case ENUM_HANDOPERATEDACTUATOR: stream << ".HANDOPERATEDACTUATOR."; break;
case ENUM_HYDRAULICACTUATOR: stream << ".HYDRAULICACTUATOR."; break;
case ENUM_PNEUMATICACTUATOR: stream << ".PNEUMATICACTUATOR."; break;
case ENUM_THERMOSTATICACTUATOR: stream << ".THERMOSTATICACTUATOR."; break;
case ENUM_USERDEFINED: stream << ".USERDEFINED."; break;
case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break;
}
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcActuatorTypeEnum::toString() const
{
switch( m_enum )
{
case ENUM_ELECTRICACTUATOR: return L"ELECTRICACTUATOR";
case ENUM_HANDOPERATEDACTUATOR: return L"HANDOPERATEDACTUATOR";
case ENUM_HYDRAULICACTUATOR: return L"HYDRAULICACTUATOR";
case ENUM_PNEUMATICACTUATOR: return L"PNEUMATICACTUATOR";
case ENUM_THERMOSTATICACTUATOR: return L"THERMOSTATICACTUATOR";
case ENUM_USERDEFINED: return L"USERDEFINED";
case ENUM_NOTDEFINED: return L"NOTDEFINED";
}
return L"";
}
shared_ptr<IfcActuatorTypeEnum> IfcActuatorTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcActuatorTypeEnum>(); }
if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcActuatorTypeEnum>(); }
shared_ptr<IfcActuatorTypeEnum> type_object( new IfcActuatorTypeEnum() );
if( std_iequal( arg, L".ELECTRICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_ELECTRICACTUATOR;
}
else if( std_iequal( arg, L".HANDOPERATEDACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_HANDOPERATEDACTUATOR;
}
else if( std_iequal( arg, L".HYDRAULICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_HYDRAULICACTUATOR;
}
else if( std_iequal( arg, L".PNEUMATICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_PNEUMATICACTUATOR;
}
else if( std_iequal( arg, L".THERMOSTATICACTUATOR." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_THERMOSTATICACTUATOR;
}
else if( std_iequal( arg, L".USERDEFINED." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_USERDEFINED;
}
else if( std_iequal( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcActuatorTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
| 39.807229
| 172
| 0.740315
|
AlexVlk
|
2853bc1c7cf0246f945c77713f29bb9cdbda037c
| 2,067
|
cpp
|
C++
|
GOOGLETEST/AccountTest/main.cpp
|
Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake
|
f1a3951c5fb9c29cc3de7deadb34caea5c8829d0
|
[
"MIT"
] | null | null | null |
GOOGLETEST/AccountTest/main.cpp
|
Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake
|
f1a3951c5fb9c29cc3de7deadb34caea5c8829d0
|
[
"MIT"
] | null | null | null |
GOOGLETEST/AccountTest/main.cpp
|
Amit-Khobragade/Google-Test-And-Mock-Examples-Using-Cmake
|
f1a3951c5fb9c29cc3de7deadb34caea5c8829d0
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <gtest/gtest.h>
#include <stdexcept>
#include "account.h"
///////////////////////////////////////////////////////////////////
//fixture class for Account
class AccountTestFixtures: public testing::Test
{
public:
AccountTestFixtures();
static void SetUpTestCase();
void SetUp() override;
void TearDown() override;
static void TearDownTestCase();
virtual ~AccountTestFixtures(){
std::cout<<"\n\ndestructor\n\n";
}
protected:
Account accobj;
};
//method implementations
AccountTestFixtures::AccountTestFixtures()
:accobj{"amit", 198}
{
std::cout<<"\n\nconstructor\n\n";
}
void AccountTestFixtures::SetUpTestCase(){
std::cout<<"\n\nsetup test case\n\n";
}
void AccountTestFixtures::SetUp() {
std::cout<<"\n\nsetup\n\n";
accobj.setBalance( 198.0 );
}
void AccountTestFixtures::TearDown() {
std::cout<<"\n\nTearDown\n\n";
}
void AccountTestFixtures::TearDownTestCase(){
std::cout<<"\n\ntear down test case\n\n";
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 1 :: deposit :: normal deposit
TEST_F( AccountTestFixtures, Testdeposit ){
ASSERT_EQ( 188.0, accobj.withdrawl( 10 ));
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 2 :: deposit :: exception check
TEST_F( AccountTestFixtures, TestdepositSmallerThan0 ){
ASSERT_THROW( accobj.withdrawl( -10 ), std::invalid_argument);
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
//test 3 :: deposit :: exception check
TEST_F( AccountTestFixtures, TestdepositNotEnoughBalance ){
ASSERT_THROW( accobj.withdrawl( 2000 ), std::runtime_error);
}
///////////////////////////////////////////////////////////////////
int main( int argc, char* argv[] ){
testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}
| 27.197368
| 67
| 0.507499
|
Amit-Khobragade
|
285412303ff4ca73ddb2bcb65033969e40b6acab
| 32,986
|
cpp
|
C++
|
src/mongo/db/query/lite_parsed_query_test.cpp
|
joprice/mongo
|
c8171e7f969519af8b87a43425ae291ee69a0191
|
[
"Apache-2.0"
] | 1
|
2015-11-06T05:55:10.000Z
|
2015-11-06T05:55:10.000Z
|
src/mongo/db/query/lite_parsed_query_test.cpp
|
wujf/mongo
|
f2f48b749ded0c5585c798c302f6162f19336670
|
[
"Apache-2.0"
] | null | null | null |
src/mongo/db/query/lite_parsed_query_test.cpp
|
wujf/mongo
|
f2f48b749ded0c5585c798c302f6162f19336670
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (C) 2013 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
/**
* This file contains tests for mongo/db/query/list_parsed_query.h
*/
#include "mongo/db/query/lite_parsed_query.h"
#include "mongo/db/json.h"
#include "mongo/unittest/unittest.h"
using namespace mongo;
namespace {
TEST(LiteParsedQueryTest, InitSortOrder) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 1, 0, BSONObj(), BSONObj(),
fromjson("{a: 1}"), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
delete lpq;
}
TEST(LiteParsedQueryTest, InitSortOrderString) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 1, 0, BSONObj(), BSONObj(),
fromjson("{a: \"\"}"), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
TEST(LiteParsedQueryTest, GetFilter) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 5, 6, 9, BSON( "x" << 5 ), BSONObj(),
BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
ASSERT_EQUALS(BSON("x" << 5 ), lpq->getFilter());
delete lpq;
}
TEST(LiteParsedQueryTest, NumToReturn) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 5, 6, 9, BSON( "x" << 5 ), BSONObj(),
BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
ASSERT_EQUALS(6, lpq->getNumToReturn());
ASSERT(lpq->wantMore());
delete lpq;
lpq = NULL;
result = LiteParsedQuery::make("testns", 5, -6, 9, BSON( "x" << 5 ), BSONObj(),
BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpq);
ASSERT_OK(result);
ASSERT_EQUALS(6, lpq->getNumToReturn());
ASSERT(!lpq->wantMore());
delete lpq;
}
TEST(LiteParsedQueryTest, MinFieldsNotPrefixOfMax) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
fromjson("{a: 1}"), fromjson("{b: 1}"),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
TEST(LiteParsedQueryTest, MinFieldsMoreThanMax) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
fromjson("{a: 1, b: 1}"), fromjson("{a: 1}"),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
TEST(LiteParsedQueryTest, MinFieldsLessThanMax) {
LiteParsedQuery* lpq = NULL;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, BSONObj(), BSONObj(),
BSONObj(), BSONObj(),
fromjson("{a: 1}"), fromjson("{a: 1, b: 1}"),
false, // snapshot
false, // explain
&lpq);
ASSERT_NOT_OK(result);
}
// Helper function which returns the Status of creating a LiteParsedQuery object with the given
// parameters.
Status makeLiteParsedQuery(const BSONObj& query, const BSONObj& proj, const BSONObj& sort) {
LiteParsedQuery* lpqRaw;
Status result = LiteParsedQuery::make("testns", 0, 0, 0, query, proj, sort, BSONObj(),
BSONObj(), BSONObj(),
false, // snapshot
false, // explain
&lpqRaw);
if (result.isOK()) {
boost::scoped_ptr<LiteParsedQuery> lpq(lpqRaw);
}
return result;
}
//
// Test compatibility of various projection and sort objects.
//
TEST(LiteParsedQueryTest, ValidSortProj) {
Status result = Status::OK();
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: 1}"),
fromjson("{a: 1}"));
ASSERT_OK(result);
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: {$meta: \"textScore\"}}"),
fromjson("{a: {$meta: \"textScore\"}}"));
ASSERT_OK(result);
}
TEST(LiteParsedQueryTest, ForbidNonMetaSortOnFieldWithMetaProject) {
Status result = Status::OK();
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: {$meta: \"textScore\"}}"),
fromjson("{a: 1}"));
ASSERT_NOT_OK(result);
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: {$meta: \"textScore\"}}"),
fromjson("{b: 1}"));
ASSERT_OK(result);
}
TEST(LiteParsedQueryTest, ForbidMetaSortOnFieldWithoutMetaProject) {
Status result = Status::OK();
result = makeLiteParsedQuery(BSONObj(),
fromjson("{a: 1}"),
fromjson("{a: {$meta: \"textScore\"}}"));
ASSERT_NOT_OK(result);
result = makeLiteParsedQuery(BSONObj(),
fromjson("{b: 1}"),
fromjson("{a: {$meta: \"textScore\"}}"));
ASSERT_NOT_OK(result);
}
//
// Text meta BSON element validation
//
bool isFirstElementTextScoreMeta(const char* sortStr) {
BSONObj sortObj = fromjson(sortStr);
BSONElement elt = sortObj.firstElement();
bool result = LiteParsedQuery::isTextScoreMeta(elt);
return result;
}
// Check validation of $meta expressions
TEST(LiteParsedQueryTest, IsTextScoreMeta) {
// Valid textScore meta sort
ASSERT(isFirstElementTextScoreMeta("{a: {$meta: \"textScore\"}}"));
// Invalid textScore meta sorts
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$meta: 1}}"));
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$meta: \"image\"}}"));
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$world: \"textScore\"}}"));
ASSERT_FALSE(isFirstElementTextScoreMeta("{a: {$meta: \"textScore\", b: 1}}"));
}
//
// Sort order validation
// In a valid sort order, each element satisfies one of:
// 1. a number with value 1
// 2. a number with value -1
// 3. isTextScoreMeta
//
TEST(LiteParsedQueryTest, ValidateSortOrder) {
// Valid sorts
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{}")));
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{a: 1}")));
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{a: -1}")));
ASSERT(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: \"textScore\"}}")));
// Invalid sorts
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: 100}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: 0}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: -100}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: Infinity}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: -Infinity}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: true}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: false}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: null}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {b: 1}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: []}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: [1, 2, 3]}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: \"\"}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: \"bb\"}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: 1}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: \"image\"}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$world: \"textScore\"}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{a: {$meta: \"textScore\","
" b: 1}}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{'': 1}")));
ASSERT_FALSE(LiteParsedQuery::isValidSortOrder(fromjson("{'': -1}")));
}
//
// Tests for parsing a lite parsed query from a command BSON object.
//
TEST(LiteParsedQueryTest, ParseFromCommandBasic) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 3},"
"sort: {a: 1},"
"projection: {_id: 0, a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseFromCommandWithOptions) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 3},"
"sort: {a: 1},"
"projection: {_id: 0, a: 1},"
"options: {showDiskLoc: true, maxScan: 1000}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
// Make sure the values from the command BSON are reflected in the LPQ.
ASSERT(lpq->getOptions().showDiskLoc);
ASSERT_EQUALS(1000, lpq->getMaxScan());
}
TEST(LiteParsedQueryTest, ParseFromCommandHintAsString) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"hint: 'foo_1'}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
ASSERT_EQUALS("foo_1", lpq->getHint().firstElement().str());
}
TEST(LiteParsedQueryTest, ParseFromCommandValidSortProj) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"projection: {a: 1},"
"sort: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseFromCommandValidSortProjMeta) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"projection: {a: {$meta: 'textScore'}},"
"sort: {a: {$meta: 'textScore'}}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseFromCommandAllFlagsTrue) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {"
"tailable: true,"
"slaveOk: true,"
"oplogReplay: true,"
"noCursorTimeout: true,"
"awaitData: true,"
"exhaust: true,"
"partial: true"
"}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
// Test that all the flags got set to true.
ASSERT(lpq->getOptions().tailable);
ASSERT(lpq->getOptions().slaveOk);
ASSERT(lpq->getOptions().oplogReplay);
ASSERT(lpq->getOptions().noCursorTimeout);
ASSERT(lpq->getOptions().awaitData);
ASSERT(lpq->getOptions().exhaust);
ASSERT(lpq->getOptions().partial);
}
TEST(LiteParsedQueryTest, ParseFromCommandCommentWithValidMinMax) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {"
"comment: 'the comment',"
"min: {a: 1},"
"max: {a: 2}"
"}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
ASSERT_EQUALS("the comment", lpq->getOptions().comment);
BSONObj expectedMin = BSON("a" << 1);
ASSERT_EQUALS(0, expectedMin.woCompare(lpq->getMin()));
BSONObj expectedMax = BSON("a" << 2);
ASSERT_EQUALS(0, expectedMax.woCompare(lpq->getMax()));
}
TEST(LiteParsedQueryTest, ParseFromCommandAllNonOptionFields) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"sort: {b: 1},"
"projection: {c: 1},"
"hint: {d: 1},"
"limit: 3,"
"skip: 5,"
"batchSize: 90,"
"singleBatch: false}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
// Check the values inside the LPQ.
BSONObj expectedQuery = BSON("a" << 1);
ASSERT_EQUALS(0, expectedQuery.woCompare(lpq->getFilter()));
BSONObj expectedSort = BSON("b" << 1);
ASSERT_EQUALS(0, expectedSort.woCompare(lpq->getSort()));
BSONObj expectedProj = BSON("c" << 1);
ASSERT_EQUALS(0, expectedProj.woCompare(lpq->getProj()));
BSONObj expectedHint = BSON("d" << 1);
ASSERT_EQUALS(0, expectedHint.woCompare(lpq->getHint()));
ASSERT_EQUALS(3, lpq->getLimit());
ASSERT_EQUALS(5, lpq->getSkip());
ASSERT_EQUALS(90, lpq->getBatchSize());
ASSERT(lpq->wantMore());
}
//
// Parsing errors where a field has the wrong type.
//
TEST(LiteParsedQueryTest, ParseFromCommandQueryWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: 3}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSortWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"sort: 3}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandProjWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"projection: 'foo'}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSkipWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"skip: '5',"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandLimitWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"limit: '5',"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSingleBatchWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"singleBatch: 'false',"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandOptionsWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: [{snapshot: true}],"
"projection: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandCommentWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {comment: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMaxScanWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {maxScan: true, comment: 'foo'}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMaxTimeMSWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {maxTimeMS: true}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMaxWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {max: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandMinWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {min: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandReturnKeyWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {returnKey: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandShowDiskLocWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {showDiskLoc: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSnapshotWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {snapshot: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandTailableWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {tailable: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSlaveOkWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {slaveOk: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandOplogReplayWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {oplogReplay: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandNoCursorTimeoutWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {noCursorTimeout: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandAwaitDataWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {awaitData: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandExhaustWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {exhaust: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandPartialWrongType) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"filter: {a: 1},"
"options: {exhaust: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
//
// Parsing errors where a field has the right type but a bad value.
//
TEST(LiteParsedQueryTest, ParseFromCommandNegativeSkipError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"skip: -3,"
"filter: {a: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandNegativeLimitError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"limit: -3,"
"filter: {a: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandNegativeBatchSizeError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"batchSize: -10,"
"filter: {a: 3}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
//
// Errors checked in LiteParsedQuery::validate().
//
TEST(LiteParsedQueryTest, ParseFromCommandMinMaxDifferentFieldsError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {min: {a: 3}, max: {b: 4}}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSnapshotPlusSortError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"sort: {a: 3},"
"options: {snapshot: true}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandSnapshotPlusHintError) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {snapshot: true},"
"hint: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseCommandForbidNonMetaSortOnFieldWithMetaProject) {
Status status = Status::OK();
BSONObj cmdObj;
cmdObj = fromjson("{find: 'testns',"
"projection: {a: {$meta: 'textScore'}},"
"sort: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
cmdObj = fromjson("{find: 'testns',"
"projection: {a: {$meta: 'textScore'}},"
"sort: {b: 1}}");
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_OK(status);
scoped_ptr<LiteParsedQuery> lpq(rawLpq);
}
TEST(LiteParsedQueryTest, ParseCommandForbidMetaSortOnFieldWithoutMetaProject) {
Status status = Status::OK();
BSONObj cmdObj;
cmdObj = fromjson("{find: 'testns',"
"projection: {a: 1},"
"sort: {a: {$meta: 'textScore'}}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
cmdObj = fromjson("{find: 'testns',"
"projection: {b: 1},"
"sort: {a: {$meta: 'textScore'}}}");
status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
//
// Extra fields cause the parse to fail.
//
TEST(LiteParsedQueryTest, ParseFromCommandForbidExtraField) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {snapshot: true},"
"foo: {a: 1}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
TEST(LiteParsedQueryTest, ParseFromCommandForbidExtraOption) {
BSONObj cmdObj = fromjson("{find: 'testns',"
"options: {snapshot: true, foo: true}}");
LiteParsedQuery* rawLpq;
bool isExplain = false;
Status status = LiteParsedQuery::make("testns", cmdObj, isExplain, &rawLpq);
ASSERT_NOT_OK(status);
}
} // namespace
| 41.078456
| 99
| 0.518008
|
joprice
|
28547d18f64675f20e099d4d409b3a5608668593
| 2,434
|
hpp
|
C++
|
VNFs/DPPD-PROX/tools/flow_extract/stream.hpp
|
plvisiondevs/samplevnf
|
ffdcfa6b834d3ad00188ee9805370d6aefc44b4b
|
[
"Apache-2.0"
] | 19
|
2017-10-13T11:14:19.000Z
|
2022-02-13T12:26:42.000Z
|
VNFs/DPPD-PROX/tools/flow_extract/stream.hpp
|
plvisiondevs/samplevnf
|
ffdcfa6b834d3ad00188ee9805370d6aefc44b4b
|
[
"Apache-2.0"
] | 1
|
2022-01-25T12:33:52.000Z
|
2022-01-25T12:33:52.000Z
|
VNFs/DPPD-PROX/tools/flow_extract/stream.hpp
|
plvisiondevs/samplevnf
|
ffdcfa6b834d3ad00188ee9805370d6aefc44b4b
|
[
"Apache-2.0"
] | 22
|
2017-09-21T01:54:35.000Z
|
2021-11-07T06:40:11.000Z
|
/*
// Copyright (c) 2010-2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#ifndef _STREAM_H_
#define _STREAM_H_
#include <list>
#include <string>
#include <fstream>
#include <cstring>
#include <vector>
#include <cstdlib>
#include <sys/time.h>
#include "pcappktref.hpp"
#include "pcappkt.hpp"
#include "netsocket.hpp"
#include "timestamp.hpp"
#include "halfstream.hpp"
using namespace std;
class PcapReader;
class Stream {
public:
struct Header {
uint32_t streamId;
uint16_t clientHdrLen;
uint32_t clientContentLen;
uint16_t serverHdrLen;
uint32_t serverContentLen;
uint32_t actionCount;
uint32_t clientIP;
uint16_t clientPort;
uint32_t serverIP;
uint16_t serverPort;
double upRate;
double dnRate;
uint8_t protocol;
uint8_t completedTCP;
void toFile(ofstream *f) const;
int fromFile(ifstream *f);
size_t getStreamLen() const;
};
struct ActionEntry {
uint8_t peer;
uint32_t beg;
uint32_t len;
} __attribute__((packed));
Stream(uint32_t id = -1, uint32_t sizeHint = 0);
void addPkt(const PcapPkt &pkt);
void toFile(ofstream *f);
void toPcap(const string& outFile);
double getRate() const;
size_t actionCount() const {return m_actions.size();}
private:
Header getHeader() const;
void actionsToFile(ofstream *f) const;
void clientHdrToFile(ofstream *f) const;
void serverHdrToFile(ofstream *f) const;
void contentsToFile(ofstream *f, bool isClient) const;
bool isClient(const PcapPkt &pkt) const;
size_t pktCount() const;
struct pkt_tuple m_pt;
void setTupleFromPkt(const PcapPkt &pkt);
void addToClient(const PcapPkt &pkt);
void addToServer(const PcapPkt &pkt);
void addAction(HalfStream *half, HalfStream::Action::Part p, bool isClientPkt);
int m_id;
vector<PcapPkt> m_pkts;
vector<HalfStream::Action> m_actions;
HalfStream m_client;
HalfStream m_server;
bool m_prevPktIsClient;
};
#endif /* _STREAM_H_ */
| 25.621053
| 80
| 0.741988
|
plvisiondevs
|
2854d4ff3ddbc2c5e17ae5989f6087554f272d9f
| 2,183
|
hpp
|
C++
|
lib/STL+/containers/matrix.hpp
|
knela96/Game-Engine
|
06659d933c4447bd8d6c8536af292825ce4c2ab1
|
[
"Unlicense"
] | 65
|
2021-01-06T12:36:22.000Z
|
2021-06-21T10:30:09.000Z
|
deps/stlplus/containers/matrix.hpp
|
evpo/libencryptmsg
|
fa1ea59c014c0a9ce339d7046642db4c80fc8701
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 4
|
2021-12-06T16:00:00.000Z
|
2022-03-18T07:40:33.000Z
|
deps/stlplus/containers/matrix.hpp
|
evpo/libencryptmsg
|
fa1ea59c014c0a9ce339d7046642db4c80fc8701
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 11
|
2021-01-07T02:57:02.000Z
|
2021-05-31T06:10:56.000Z
|
#ifndef STLPLUS_MATRIX
#define STLPLUS_MATRIX
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// General-purpose 2D matrix data structure
////////////////////////////////////////////////////////////////////////////////
#include "containers_fixes.hpp"
#include <stdexcept>
namespace stlplus
{
////////////////////////////////////////////////////////////////////////////////
template<typename T> class matrix
{
public:
matrix(unsigned rows = 0, unsigned cols = 0, const T& fill = T()) ;
~matrix(void) ;
matrix(const matrix&) ;
matrix& operator =(const matrix&) ;
void resize(unsigned rows, unsigned cols, const T& fill = T()) ;
unsigned rows(void) const ;
unsigned columns(void) const ;
void erase(const T& fill = T()) ;
// exceptions: std::out_of_range
void erase(unsigned row, unsigned col, const T& fill = T()) ;
// exceptions: std::out_of_range
void insert(unsigned row, unsigned col, const T&) ;
// exceptions: std::out_of_range
const T& item(unsigned row, unsigned col) const ;
// exceptions: std::out_of_range
T& item(unsigned row, unsigned col) ;
// exceptions: std::out_of_range
const T& operator()(unsigned row, unsigned col) const ;
// exceptions: std::out_of_range
T& operator()(unsigned row, unsigned col) ;
void fill(const T& item = T()) ;
// exceptions: std::out_of_range
void fill_column(unsigned col, const T& item = T()) ;
// exceptions: std::out_of_range
void fill_row(unsigned row, const T& item = T()) ;
void fill_leading_diagonal(const T& item = T()) ;
void fill_trailing_diagonal(const T& item = T()) ;
void make_identity(const T& one, const T& zero = T()) ;
void transpose(void) ;
private:
unsigned m_rows;
unsigned m_cols;
T** m_data;
};
////////////////////////////////////////////////////////////////////////////////
} // end namespace stlplus
#include "matrix.tpp"
#endif
| 30.319444
| 82
| 0.55016
|
knela96
|
2855669ef1d39b987605349694dc6e7653d21e67
| 4,667
|
hpp
|
C++
|
src/buffer_cache/evicter.hpp
|
zadcha/rethinkdb
|
bb4f5cc28242dc1e29e9a46a8a931ec54420070c
|
[
"Apache-2.0"
] | 21,684
|
2015-01-01T03:42:20.000Z
|
2022-03-30T13:32:44.000Z
|
src/buffer_cache/evicter.hpp
|
RethonkDB/rethonkdb
|
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
|
[
"Apache-2.0"
] | 4,067
|
2015-01-01T00:04:51.000Z
|
2022-03-30T13:42:56.000Z
|
src/buffer_cache/evicter.hpp
|
RethonkDB/rethonkdb
|
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
|
[
"Apache-2.0"
] | 1,901
|
2015-01-01T21:05:59.000Z
|
2022-03-21T08:14:25.000Z
|
#ifndef BUFFER_CACHE_EVICTER_HPP_
#define BUFFER_CACHE_EVICTER_HPP_
#include <stdint.h>
#include <functional>
#include "buffer_cache/eviction_bag.hpp"
#include "concurrency/auto_drainer.hpp"
#include "concurrency/cache_line_padded.hpp"
#include "concurrency/pubsub.hpp"
#include "threading.hpp"
#include "time.hpp"
class cache_balancer_t;
class alt_txn_throttler_t;
namespace alt {
class page_cache_t;
class evicter_t : public home_thread_mixin_debug_only_t {
public:
void add_not_yet_loaded(page_t *page);
void add_deferred_loaded(page_t *page);
void catch_up_deferred_load(page_t *page);
void add_to_evictable_unbacked(page_t *page);
void add_to_evictable_disk_backed(page_t *page);
bool page_is_in_unevictable_bag(page_t *page) const;
bool page_is_in_evicted_bag(page_t *page) const;
void move_unevictable_to_evictable(page_t *page);
void change_to_correct_eviction_bag(eviction_bag_t *current_bag, page_t *page);
eviction_bag_t *correct_eviction_category(page_t *page);
eviction_bag_t *evicted_category() { return &evicted_; }
void remove_page(page_t *page);
void reloading_page(page_t *page);
// Evicter will be unusable until initialize is called
evicter_t();
~evicter_t();
void initialize(page_cache_t *page_cache,
cache_balancer_t *balancer,
alt_txn_throttler_t *throttler);
void update_memory_limit(uint64_t new_memory_limit,
int64_t bytes_loaded_accounted_for,
uint64_t access_count_accounted_for,
bool read_ahead_ok);
uint64_t next_access_time() {
guarantee_initialized();
return ++access_time_counter_;
}
uint64_t memory_limit() const {
guarantee_initialized();
return memory_limit_;
}
uint64_t access_count() const {
guarantee_initialized();
return access_count_counter_;
}
uint64_t unevictable_size() const {
guarantee_initialized();
return unevictable_.size();
}
uint64_t evictable_disk_backed_size() const {
guarantee_initialized();
return evictable_disk_backed_.size();
}
uint64_t evictable_unbacked_size() const {
guarantee_initialized();
return evictable_unbacked_.size();
}
int64_t get_bytes_loaded() const {
guarantee_initialized();
return bytes_loaded_counter_;
}
uint64_t in_memory_size() const;
// This is decremented past UINT64_MAX to force code to be aware of access time
// rollovers.
static const uint64_t INITIAL_ACCESS_TIME = UINT64_MAX - 100;
private:
void guarantee_initialized() const {
assert_thread();
guarantee(initialized_);
}
friend class usage_adjuster_t;
// Tells the cache balancer about a page being loaded
void notify_bytes_loading(int64_t ser_buf_change);
// Evicts any evictable pages until under the memory limit
void evict_if_necessary() THROWS_NOTHING;
bool initialized_;
page_cache_t *page_cache_;
cache_balancer_t *balancer_;
bool *balancer_notify_activity_boolean_;
alt_txn_throttler_t *throttler_;
uint64_t memory_limit_;
// These are updated every time a page is loaded, created, or destroyed, and
// cleared when cache memory limits are re-evaluated. This value can go
// negative, if you keep deleting blocks or suddenly drop a snapshot.
int64_t bytes_loaded_counter_;
uint64_t access_count_counter_;
// This gets incremented every time a page is accessed.
uint64_t access_time_counter_;
// This is set to true while `evict_if_necessary()` is active.
// It avoids reentrant calls to that function.
bool evict_if_necessary_active_;
// These track every page's eviction status.
eviction_bag_t unevictable_;
eviction_bag_t evictable_disk_backed_;
eviction_bag_t evictable_unbacked_;
eviction_bag_t evicted_;
ticks_t last_force_flush_time_;
auto_drainer_t drainer_;
DISABLE_COPYING(evicter_t);
};
// This adjusts the memory usage in the destructor, with the _same_ eviction bag the
// page had in the constructor -- its lifespan ends before the page would have its
// eviction bag changed.
class usage_adjuster_t {
public:
usage_adjuster_t(page_cache_t *page_cache, page_t *page);
~usage_adjuster_t();
private:
page_cache_t *const page_cache_;
page_t *const page_;
eviction_bag_t *const eviction_bag_;
const uint32_t original_usage_;
DISABLE_COPYING(usage_adjuster_t);
};
} // namespace alt
#endif // BUFFER_CACHE_EVICTER_HPP_
| 29.726115
| 84
| 0.719091
|
zadcha
|
2855cd96d30b58bbd0de294310c725c9e760088b
| 6,641
|
cc
|
C++
|
mojo/edk/system/dispatcher.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
mojo/edk/system/dispatcher.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
mojo/edk/system/dispatcher.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 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 "mojo/edk/system/dispatcher.h"
#include "base/logging.h"
#include "mojo/edk/system/configuration.h"
#include "mojo/edk/system/data_pipe_consumer_dispatcher.h"
#include "mojo/edk/system/data_pipe_producer_dispatcher.h"
#include "mojo/edk/system/message_pipe_dispatcher.h"
#include "mojo/edk/system/platform_handle_dispatcher.h"
#include "mojo/edk/system/ports/event.h"
#include "mojo/edk/system/shared_buffer_dispatcher.h"
namespace mojo {
namespace edk {
Dispatcher::DispatcherInTransit::DispatcherInTransit() {}
Dispatcher::DispatcherInTransit::DispatcherInTransit(
const DispatcherInTransit& other) = default;
Dispatcher::DispatcherInTransit::~DispatcherInTransit() {}
MojoResult Dispatcher::WatchDispatcher(scoped_refptr<Dispatcher> dispatcher,
MojoHandleSignals signals,
MojoWatchCondition condition,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::CancelWatch(uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::Arm(uint32_t* num_ready_contexts,
uintptr_t* ready_contexts,
MojoResult* ready_results,
MojoHandleSignalsState* ready_signals_states) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::WriteMessage(
std::unique_ptr<ports::UserMessageEvent> message,
MojoWriteMessageFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::ReadMessage(
std::unique_ptr<ports::UserMessageEvent>* message) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::DuplicateBufferHandle(
const MojoDuplicateBufferHandleOptions* options,
scoped_refptr<Dispatcher>* new_dispatcher) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::MapBuffer(
uint64_t offset,
uint64_t num_bytes,
MojoMapBufferFlags flags,
std::unique_ptr<PlatformSharedBufferMapping>* mapping) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::ReadData(void* elements,
uint32_t* num_bytes,
MojoReadDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::BeginReadData(const void** buffer,
uint32_t* buffer_num_bytes,
MojoReadDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::EndReadData(uint32_t num_bytes_read) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::WriteData(const void* elements,
uint32_t* num_bytes,
MojoWriteDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::BeginWriteData(void** buffer,
uint32_t* buffer_num_bytes,
MojoWriteDataFlags flags) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::EndWriteData(uint32_t num_bytes_written) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::AddWaitingDispatcher(
const scoped_refptr<Dispatcher>& dispatcher,
MojoHandleSignals signals,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::RemoveWaitingDispatcher(
const scoped_refptr<Dispatcher>& dispatcher) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::GetReadyDispatchers(uint32_t* count,
DispatcherVector* dispatchers,
MojoResult* results,
uintptr_t* contexts) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
HandleSignalsState Dispatcher::GetHandleSignalsState() const {
return HandleSignalsState();
}
MojoResult Dispatcher::AddWatcherRef(
const scoped_refptr<WatcherDispatcher>& watcher,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
MojoResult Dispatcher::RemoveWatcherRef(WatcherDispatcher* watcher,
uintptr_t context) {
return MOJO_RESULT_INVALID_ARGUMENT;
}
void Dispatcher::StartSerialize(uint32_t* num_bytes,
uint32_t* num_ports,
uint32_t* num_platform_handles) {
*num_bytes = 0;
*num_ports = 0;
*num_platform_handles = 0;
}
bool Dispatcher::EndSerialize(void* destination,
ports::PortName* ports,
PlatformHandle* handles) {
LOG(ERROR) << "Attempting to serialize a non-transferrable dispatcher.";
return true;
}
bool Dispatcher::BeginTransit() {
return true;
}
void Dispatcher::CompleteTransitAndClose() {}
void Dispatcher::CancelTransit() {}
// static
scoped_refptr<Dispatcher> Dispatcher::Deserialize(
Type type,
const void* bytes,
size_t num_bytes,
const ports::PortName* ports,
size_t num_ports,
PlatformHandle* platform_handles,
size_t num_platform_handles) {
switch (type) {
case Type::MESSAGE_PIPE:
return MessagePipeDispatcher::Deserialize(bytes, num_bytes, ports,
num_ports, platform_handles,
num_platform_handles);
case Type::SHARED_BUFFER:
return SharedBufferDispatcher::Deserialize(bytes, num_bytes, ports,
num_ports, platform_handles,
num_platform_handles);
case Type::DATA_PIPE_CONSUMER:
return DataPipeConsumerDispatcher::Deserialize(
bytes, num_bytes, ports, num_ports, platform_handles,
num_platform_handles);
case Type::DATA_PIPE_PRODUCER:
return DataPipeProducerDispatcher::Deserialize(
bytes, num_bytes, ports, num_ports, platform_handles,
num_platform_handles);
case Type::PLATFORM_HANDLE:
return PlatformHandleDispatcher::Deserialize(bytes, num_bytes, ports,
num_ports, platform_handles,
num_platform_handles);
default:
LOG(ERROR) << "Deserializing invalid dispatcher type.";
return nullptr;
}
}
Dispatcher::Dispatcher() {}
Dispatcher::~Dispatcher() {}
} // namespace edk
} // namespace mojo
| 33.205
| 79
| 0.660593
|
metux
|
2857e6515c8cc11801506a908c7252d93ba529c1
| 62
|
hpp
|
C++
|
modules/jip/functions/JIP/script_component.hpp
|
Bear-Cave-ArmA/Olsen-Framework-ArmA-3
|
1c1715f0e4ed8f2b655a66999754256fa42ca6bf
|
[
"MIT"
] | 4
|
2020-05-04T18:03:59.000Z
|
2020-05-06T19:40:27.000Z
|
modules/jip/functions/JIP/script_component.hpp
|
Bear-Cave-ArmA/Olsen-Framework-ArmA-3
|
1c1715f0e4ed8f2b655a66999754256fa42ca6bf
|
[
"MIT"
] | 13
|
2020-05-06T19:02:06.000Z
|
2020-08-24T08:16:43.000Z
|
modules/jip/functions/JIP/script_component.hpp
|
Bear-Cave-ArmA/Olsen-Framework-ArmA-3
|
1c1715f0e4ed8f2b655a66999754256fa42ca6bf
|
[
"MIT"
] | 5
|
2020-05-04T18:04:05.000Z
|
2020-05-14T16:53:13.000Z
|
#define COMPONENT JIP
#include "..\..\script_component.hpp"
| 20.666667
| 38
| 0.709677
|
Bear-Cave-ArmA
|
285b157bd91e1f11fa4f4c0c4a349bb4c69b3637
| 1,988
|
cpp
|
C++
|
prototypes/misc_tests/cv_test4.cpp
|
andrewjouffray/HyperAugment
|
cc7a675a1dac65ce31666e59dfd468c15293024f
|
[
"MIT"
] | null | null | null |
prototypes/misc_tests/cv_test4.cpp
|
andrewjouffray/HyperAugment
|
cc7a675a1dac65ce31666e59dfd468c15293024f
|
[
"MIT"
] | null | null | null |
prototypes/misc_tests/cv_test4.cpp
|
andrewjouffray/HyperAugment
|
cc7a675a1dac65ce31666e59dfd468c15293024f
|
[
"MIT"
] | null | null | null |
#include <opencv2/opencv.hpp>
#include <iostream>
#include <omp.h>
#include <fstream>
#include <string>
#include <filesystem>
#include <chrono>
namespace fs = std::filesystem;
using namespace std;
// goal load a video file and process it with multithearding
vector<string> getFiles(string path){
//cout << "adding " + path << endl;
// this is it for now
vector<string> files;
for(const auto & entry : fs::directory_iterator(path)){
string it = entry.path();
//cout << it << endl;
files.push_back(it);
}
return files;
}
cv::Mat blackWhite(cv::Mat img){
cv::Mat grey;
cv::cvtColor(img, grey, cv::COLOR_BGR2GRAY);
return grey;
}
uint64_t timeSinceEpochMillisec(){
using namespace std::chrono;
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
int main(int argc, const char* argv[]){
string path = "/mnt/0493db9e-eabd-406b-bd32-c5d3c85ebb38/Projects/Video/Weeds2/nenuphare/data1595119927.9510028output.avi";
string save = "/mnt/0493db9e-eabd-406b-bd32-c5d3c85ebb38/Projects/dump/";
int64_t start = timeSinceEpochMillisec();
cout << start << endl;
cv::VideoCapture cap(path);
cv::Mat frame;
while (1){
if (!cap.read(frame)){
cout << "al done" << endl;
break;
}
//cout << "test" << endl;
cv::Mat img = blackWhite(frame);
//cout << "OK" << endl;
//string windowName = "display " + to_string(i);
int64_t current = timeSinceEpochMillisec();
string name = save + to_string(current) + "ok.jpg";
cv::imwrite(name, img);
// this code will be a task that may be executed immediately on a different core or deferred for later execution
} // end of while loop and single region
uint64_t end = timeSinceEpochMillisec();
uint64_t total = end - start;
cout << end << endl;
cout << total << endl;
return 0;
}
| 18.238532
| 131
| 0.622233
|
andrewjouffray
|
285ba9ea9a30d009e31a5906e49bc6cbc8bb45c0
| 2,203
|
cpp
|
C++
|
src/base/ProxyAllocator.cpp
|
bigplayszn/nCine
|
43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454
|
[
"MIT"
] | 675
|
2019-05-28T19:00:55.000Z
|
2022-03-31T16:44:28.000Z
|
src/base/ProxyAllocator.cpp
|
bigplayszn/nCine
|
43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454
|
[
"MIT"
] | 13
|
2020-03-29T06:46:32.000Z
|
2022-01-29T03:19:30.000Z
|
src/base/ProxyAllocator.cpp
|
bigplayszn/nCine
|
43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454
|
[
"MIT"
] | 53
|
2019-06-02T03:04:10.000Z
|
2022-03-11T06:17:50.000Z
|
#include <ncine/common_macros.h>
#include <nctl/ProxyAllocator.h>
namespace nctl {
///////////////////////////////////////////////////////////
// CONSTRUCTORS and DESTRUCTOR
///////////////////////////////////////////////////////////
ProxyAllocator::ProxyAllocator(const char *name, IAllocator &allocator)
: IAllocator(name, allocateImpl, reallocateImpl, deallocateImpl, 0, nullptr),
allocator_(allocator)
{
}
ProxyAllocator::~ProxyAllocator()
{
FATAL_ASSERT(usedMemory_ == 0 && numAllocations_ == 0);
}
///////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS
///////////////////////////////////////////////////////////
void *ProxyAllocator::allocateImpl(IAllocator *allocator, size_t bytes, uint8_t alignment)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *ptr = subject.allocateFunc_(&subject, bytes, alignment);
if (ptr)
{
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
allocatorImpl->numAllocations_++;
}
return ptr;
}
void *ProxyAllocator::reallocateImpl(IAllocator *allocator, void *ptr, size_t bytes, uint8_t alignment, size_t &oldSize)
{
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
void *newPtr = subject.reallocateFunc_(&subject, ptr, bytes, alignment, oldSize);
if (newPtr)
allocatorImpl->usedMemory_ += subject.usedMemory() - memoryUsedBefore;
return newPtr;
}
void ProxyAllocator::deallocateImpl(IAllocator *allocator, void *ptr)
{
if (ptr == nullptr)
return;
FATAL_ASSERT(allocator);
ProxyAllocator *allocatorImpl = static_cast<ProxyAllocator *>(allocator);
IAllocator &subject = allocatorImpl->allocator_;
const size_t memoryUsedBefore = subject.usedMemory();
subject.deallocateFunc_(&subject, ptr);
allocatorImpl->usedMemory_ -= memoryUsedBefore - subject.usedMemory();
FATAL_ASSERT(allocatorImpl->numAllocations_ > 0);
allocatorImpl->numAllocations_--;
}
}
| 29.77027
| 120
| 0.684521
|
bigplayszn
|
286048f8b0629f4e1171e3411031b2ca73a38f01
| 1,784
|
cc
|
C++
|
experiments/efficiency/runtime_test.cc
|
Fytch/lehrfempp
|
c804b3e350aa893180f1a02ce57a93b3d7686e91
|
[
"MIT"
] | 16
|
2018-08-30T19:55:43.000Z
|
2022-02-16T16:38:06.000Z
|
experiments/efficiency/runtime_test.cc
|
Fytch/lehrfempp
|
c804b3e350aa893180f1a02ce57a93b3d7686e91
|
[
"MIT"
] | 151
|
2018-05-27T13:01:50.000Z
|
2021-08-04T14:50:50.000Z
|
experiments/efficiency/runtime_test.cc
|
Fytch/lehrfempp
|
c804b3e350aa893180f1a02ce57a93b3d7686e91
|
[
"MIT"
] | 20
|
2018-11-13T13:46:38.000Z
|
2022-02-18T17:33:52.000Z
|
/** @file runtime_test.cc
* @brief Some tests for runtime behavior of certain C++ constructs
*/
#include <iostream>
#include "lf/base/base.h"
static const int N = 10;
static double stat_tmp[N]; // NOLINT
std::vector<double> getData_VEC(double offset) {
std::vector<double> tmp(10);
for (int j = 0; j < N; j++) {
tmp[j] = 1.0 / (j + offset);
}
return tmp;
}
// NOLINTNEXTLINE
void getData_REF(double offset, std::vector<double> &res) {
for (int j = 0; j < N; j++) {
res[j] = 1.0 / (j + offset);
}
}
nonstd::span<const double> getData_SPAN(double offset) {
for (int j = 0; j < N; j++) {
stat_tmp[j] = 1.0 / (j + offset);
}
return {static_cast<double *>(stat_tmp), (stat_tmp + N)};
}
int main(int /*argc*/, const char * /*unused*/[]) {
std::cout << "Runtime test for range access" << std::endl;
const long int reps = 100000000L;
std::cout << "I. Returning std::vector's" << std::endl;
{
lf::base::AutoTimer t;
for (long int i = 0; i < reps; i++) {
auto res = getData_VEC(static_cast<double>(i));
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
std::cout << "II. Returning result through reference" << std::endl;
{
lf::base::AutoTimer t;
std::vector<double> res(N);
for (long int i = 0; i < reps; i++) {
getData_REF(static_cast<double>(i), res);
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
std::cout << "III. Returning result through span" << std::endl;
{
lf::base::AutoTimer t;
for (long int i = 0; i < reps; i++) {
auto res = getData_SPAN(static_cast<double>(i));
double s = 0.0;
for (int j = 0; j < N; j++) {
s += res[j];
}
}
}
return 0;
}
| 22.582278
| 69
| 0.538677
|
Fytch
|
28617c6019b7bdfdb91bc6e8d63550ad8afaac6a
| 4,390
|
hpp
|
C++
|
include/xwidgets/xvideo.hpp
|
SylvainCorlay/xwidgets
|
f21198f5934c90b034afee9b36c47b0e7b456c6b
|
[
"BSD-3-Clause"
] | 1
|
2020-01-10T04:13:44.000Z
|
2020-01-10T04:13:44.000Z
|
include/xwidgets/xvideo.hpp
|
SylvainCorlay/xwidgets
|
f21198f5934c90b034afee9b36c47b0e7b456c6b
|
[
"BSD-3-Clause"
] | null | null | null |
include/xwidgets/xvideo.hpp
|
SylvainCorlay/xwidgets
|
f21198f5934c90b034afee9b36c47b0e7b456c6b
|
[
"BSD-3-Clause"
] | null | null | null |
/***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XWIDGETS_VIDEO_HPP
#define XWIDGETS_VIDEO_HPP
#include <cstddef>
#include <string>
#include <vector>
#include "xmaterialize.hpp"
#include "xmedia.hpp"
namespace xw
{
/*********************
* video declaration *
*********************/
template <class D>
class xvideo : public xmedia<D>
{
public:
using base_type = xmedia<D>;
using derived_type = D;
void serialize_state(nl::json& state, xeus::buffer_sequence&) const;
void apply_patch(const nl::json&, const xeus::buffer_sequence&);
XPROPERTY(std::string, derived_type, format, "mp4");
XPROPERTY(std::string, derived_type, width, "");
XPROPERTY(std::string, derived_type, height, "");
XPROPERTY(bool, derived_type, autoplay, true);
XPROPERTY(bool, derived_type, loop, true);
XPROPERTY(bool, derived_type, controls, true);
protected:
xvideo();
using base_type::base_type;
private:
void set_defaults();
};
using video = xmaterialize<xvideo>;
/*************************
* xvideo implementation *
*************************/
template <class D>
inline void xvideo<D>::serialize_state(nl::json& state, xeus::buffer_sequence& buffers) const
{
base_type::serialize_state(state, buffers);
xwidgets_serialize(format(), state["format"], buffers);
xwidgets_serialize(width(), state["width"], buffers);
xwidgets_serialize(height(), state["height"], buffers);
xwidgets_serialize(autoplay(), state["autoplay"], buffers);
xwidgets_serialize(loop(), state["loop"], buffers);
xwidgets_serialize(controls(), state["controls"], buffers);
}
template <class D>
inline void xvideo<D>::apply_patch(const nl::json& patch, const xeus::buffer_sequence& buffers)
{
base_type::apply_patch(patch, buffers);
set_property_from_patch(format, patch, buffers);
set_property_from_patch(width, patch, buffers);
set_property_from_patch(height, patch, buffers);
set_property_from_patch(autoplay, patch, buffers);
set_property_from_patch(loop, patch, buffers);
set_property_from_patch(controls, patch, buffers);
}
template <class D>
inline xvideo<D>::xvideo()
: base_type()
{
set_defaults();
}
template <class D>
inline void xvideo<D>::set_defaults()
{
this->_model_name() = "VideoModel";
this->_view_name() = "VideoView";
}
/**********************
* custom serializers *
**********************/
inline void set_property_from_patch(decltype(video::value)& property,
const nl::json& patch,
const xeus::buffer_sequence& buffers)
{
auto it = patch.find(property.name());
if (it != patch.end())
{
using value_type = typename decltype(video::value)::value_type;
std::size_t index = buffer_index(patch[property.name()].template get<std::string>());
const auto& value_buffer = buffers[index];
const char* value_buf = value_buffer.data<const char>();
property = value_type(value_buf, value_buf + value_buffer.size());
}
}
inline auto video_from_file(const std::string& filename)
{
return video::initialize().value(read_file(filename));
}
inline auto video_from_url(const std::string& url)
{
std::vector<char> value(url.cbegin(), url.cend());
return video::initialize().value(value).format("url");
}
/*********************
* precompiled types *
*********************/
extern template class xmaterialize<xvideo>;
extern template class xtransport<xmaterialize<xvideo>>;
}
#endif
| 32.043796
| 99
| 0.550797
|
SylvainCorlay
|
2864b7d13c542879e010c7d2fb375e9f194c14e1
| 4,259
|
hxx
|
C++
|
com/ole32/stg/async/layoutui/layoutui.hxx
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
com/ole32/stg/async/layoutui/layoutui.hxx
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
com/ole32/stg/async/layoutui/layoutui.hxx
|
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, 1992 - 1996.
//
// File: layoutui.hxx
//
// Contents: Common header file Layout Tool UI
//
// Classes: CLayoutApp
// COleClientSite
//
// History: 23-Mar-96 SusiA Created
//
//----------------------------------------------------------------------------
#ifndef __LAYOUTUI_HXX__
#define __LAYOUTUI_HXX__
#include <windows.h>
#include <shellapi.h>
#include <commdlg.h>
#include <cderr.h>
#include <winuser.h>
#include "resource.h"
#ifndef STG_E_NONEOPTIMIZED
#define STG_E_NONEOPTIMIZED _HRESULT_TYPEDEF_(0x80030205L)
#endif
#define gdxWndMin 300;
#define gdyWndMin 300;
#define hwndNil NULL;
#define hNil NULL;
#define bMsgHandled 1
#define bMsgNotHandled 0
class CLayoutApp
{
public:
CLayoutApp(HINSTANCE hInst);
BOOL InitApp(void);
INT DoAppMessageLoop(void);
private:
HINSTANCE m_hInst;
HWND m_hwndMain;
HWND m_hwndBtnAdd;
HWND m_hwndBtnRemove;
HWND m_hwndBtnOptimize;
HWND m_hwndListFiles;
HWND m_hwndStaticFiles;
BOOL m_bOptimizing;
BOOL m_bCancelled;
static INT_PTR CALLBACK LayoutDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
static LONG CALLBACK ListBoxWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static LONG CALLBACK ButtonWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static DWORD OptimizeFiles (void *args);
BOOL InitWindow (void);
VOID ReSizeWindow( LPARAM lParam );
VOID AddFiles( void );
VOID RemoveFiles( void );
VOID EnableButtons( BOOL bShowOptimizeBtn = TRUE );
VOID FormFilterString( TCHAR *patcFilter, INT nMaxLen );
VOID WriteFilesToList( TCHAR *patc );
VOID AddFileToListBox( TCHAR *patcFile );
VOID RemoveFileFromListBox( INT nIndex );
VOID SetListBoxExtent( void );
VOID HandleOptimizeReturnCode( SCODE sc );
VOID SetActionButton( UINT uID );
INT DisplayMessage( HWND hWnd,
UINT uMessageID,
UINT uTitleID,
UINT uFlags );
INT DisplayMessageWithFileName(HWND hWnd,
UINT uMessageIDBefore,
UINT uMessageIDAfter,
UINT uTitleID,
UINT uFlags,
TCHAR *patcFileName);
INT CLayoutApp::DisplayMessageWithTwoFileNames(HWND hWnd,
UINT uMessageID,
UINT uTitleID,
UINT uFlags,
TCHAR *patcFirstFileName,
TCHAR *patcLastFileName);
SCODE OptimizeFilesWorker( void );
SCODE DoOptimizeFile( TCHAR *patcFileName, TCHAR *patcTempFile );
OLECHAR *TCharToOleChar(TCHAR *atcSrc, OLECHAR *awcDst, INT nDstLen);
#if DBG==1
BOOL CLayoutApp::IdenticalFiles( TCHAR *patcFileOne,
TCHAR *patcFileTwo);
#endif
};
class COleClientSite : public IOleClientSite
{
public:
TCHAR *m_patcFile;
inline COleClientSite(void);
// IUnknown
STDMETHOD(QueryInterface)(REFIID riid, void** ppObject);
STDMETHOD_(ULONG, AddRef)(void);
STDMETHOD_(ULONG, Release)(void);
//IOleClientSite
STDMETHOD (SaveObject)( void);
STDMETHOD (GetMoniker)(
/* [in] */ DWORD dwAssign,
/* [in] */ DWORD dwWhichMoniker,
/* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk);
STDMETHOD (GetContainer)(
/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer);
STDMETHOD (ShowObject)( void);
STDMETHOD (OnShowWindow)(
/* [in] */ BOOL fShow);
STDMETHOD (RequestNewObjectLayout)( void);
private:
LONG _cReferences;
};
inline COleClientSite::COleClientSite(void)
{
_cReferences = 1;
}
#endif // __LAYOUTUI_HXX__
| 26.128834
| 95
| 0.565391
|
npocmaka
|
28652391a9f68b49c85f7080f7cf3b649c33dabc
| 6,641
|
cc
|
C++
|
net/base/directory_lister.cc
|
7kbird/chrome
|
f56688375530f1003e34c34f441321977c5af3c3
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
net/base/directory_lister.cc
|
7kbird/chrome
|
f56688375530f1003e34c34f441321977c5af3c3
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
net/base/directory_lister.cc
|
7kbird/chrome
|
f56688375530f1003e34c34f441321977c5af3c3
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2020-11-04T07:23:37.000Z
|
2020-11-04T07:23:37.000Z
|
// Copyright (c) 2012 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 "net/base/directory_lister.h"
#include <algorithm>
#include <vector>
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/i18n/file_util_icu.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "net/base/net_errors.h"
namespace net {
namespace {
bool IsDotDot(const base::FilePath& path) {
return FILE_PATH_LITERAL("..") == path.BaseName().value();
}
// Comparator for sorting lister results. This uses the locale aware filename
// comparison function on the filenames for sorting in the user's locale.
// Static.
bool CompareAlphaDirsFirst(const DirectoryLister::DirectoryListerData& a,
const DirectoryLister::DirectoryListerData& b) {
// Parent directory before all else.
if (IsDotDot(a.info.GetName()))
return true;
if (IsDotDot(b.info.GetName()))
return false;
// Directories before regular files.
bool a_is_directory = a.info.IsDirectory();
bool b_is_directory = b.info.IsDirectory();
if (a_is_directory != b_is_directory)
return a_is_directory;
return base::i18n::LocaleAwareCompareFilenames(a.info.GetName(),
b.info.GetName());
}
bool CompareDate(const DirectoryLister::DirectoryListerData& a,
const DirectoryLister::DirectoryListerData& b) {
// Parent directory before all else.
if (IsDotDot(a.info.GetName()))
return true;
if (IsDotDot(b.info.GetName()))
return false;
// Directories before regular files.
bool a_is_directory = a.info.IsDirectory();
bool b_is_directory = b.info.IsDirectory();
if (a_is_directory != b_is_directory)
return a_is_directory;
return a.info.GetLastModifiedTime() > b.info.GetLastModifiedTime();
}
// Comparator for sorting find result by paths. This uses the locale-aware
// comparison function on the filenames for sorting in the user's locale.
// Static.
bool CompareFullPath(const DirectoryLister::DirectoryListerData& a,
const DirectoryLister::DirectoryListerData& b) {
return base::i18n::LocaleAwareCompareFilenames(a.path, b.path);
}
void SortData(std::vector<DirectoryLister::DirectoryListerData>* data,
DirectoryLister::SortType sort_type) {
// Sort the results. See the TODO below (this sort should be removed and we
// should do it from JS).
if (sort_type == DirectoryLister::DATE)
std::sort(data->begin(), data->end(), CompareDate);
else if (sort_type == DirectoryLister::FULL_PATH)
std::sort(data->begin(), data->end(), CompareFullPath);
else if (sort_type == DirectoryLister::ALPHA_DIRS_FIRST)
std::sort(data->begin(), data->end(), CompareAlphaDirsFirst);
else
DCHECK_EQ(DirectoryLister::NO_SORT, sort_type);
}
} // namespace
DirectoryLister::DirectoryLister(const base::FilePath& dir,
DirectoryListerDelegate* delegate)
: core_(new Core(dir, false, ALPHA_DIRS_FIRST, this)),
delegate_(delegate) {
DCHECK(delegate_);
DCHECK(!dir.value().empty());
}
DirectoryLister::DirectoryLister(const base::FilePath& dir,
bool recursive,
SortType sort,
DirectoryListerDelegate* delegate)
: core_(new Core(dir, recursive, sort, this)),
delegate_(delegate) {
DCHECK(delegate_);
DCHECK(!dir.value().empty());
}
DirectoryLister::~DirectoryLister() {
Cancel();
}
bool DirectoryLister::Start() {
return core_->Start();
}
void DirectoryLister::Cancel() {
return core_->Cancel();
}
DirectoryLister::Core::Core(const base::FilePath& dir,
bool recursive,
SortType sort,
DirectoryLister* lister)
: dir_(dir),
recursive_(recursive),
sort_(sort),
lister_(lister) {
DCHECK(lister_);
}
DirectoryLister::Core::~Core() {}
bool DirectoryLister::Core::Start() {
origin_loop_ = base::MessageLoopProxy::current();
return base::WorkerPool::PostTask(
FROM_HERE, base::Bind(&Core::StartInternal, this), true);
}
void DirectoryLister::Core::Cancel() {
lister_ = NULL;
}
void DirectoryLister::Core::StartInternal() {
if (!base::DirectoryExists(dir_)) {
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::OnDone, this, ERR_FILE_NOT_FOUND));
return;
}
int types = base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES;
if (!recursive_)
types |= base::FileEnumerator::INCLUDE_DOT_DOT;
base::FileEnumerator file_enum(dir_, recursive_, types);
base::FilePath path;
std::vector<DirectoryListerData> file_data;
while (lister_ && !(path = file_enum.Next()).empty()) {
DirectoryListerData data;
data.info = file_enum.GetInfo();
data.path = path;
file_data.push_back(data);
/* TODO(brettw) bug 24107: It would be nice to send incremental updates.
We gather them all so they can be sorted, but eventually the sorting
should be done from JS to give more flexibility in the page. When we do
that, we can uncomment this to send incremental updates to the page.
const int kFilesPerEvent = 8;
if (file_data.size() < kFilesPerEvent)
continue;
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::SendData, file_data));
file_data.clear();
*/
}
SortData(&file_data, sort_);
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::SendData, this, file_data));
origin_loop_->PostTask(
FROM_HERE,
base::Bind(&DirectoryLister::Core::OnDone, this, OK));
}
void DirectoryLister::Core::SendData(
const std::vector<DirectoryLister::DirectoryListerData>& data) {
DCHECK(origin_loop_->BelongsToCurrentThread());
// We need to check for cancellation (indicated by NULL'ing of |lister_|)
// which can happen during each callback.
for (size_t i = 0; lister_ && i < data.size(); ++i)
lister_->OnReceivedData(data[i]);
}
void DirectoryLister::Core::OnDone(int error) {
DCHECK(origin_loop_->BelongsToCurrentThread());
if (lister_)
lister_->OnDone(error);
}
void DirectoryLister::OnReceivedData(const DirectoryListerData& data) {
delegate_->OnListFile(data);
}
void DirectoryLister::OnDone(int error) {
delegate_->OnListDone(error);
}
} // namespace net
| 30.888372
| 78
| 0.680319
|
7kbird
|
286930b7251bfb77d9c4612c785b52db98fecc5d
| 506
|
cpp
|
C++
|
test/test_runner.cpp
|
jmalkin/hll-cpp
|
0522f03473352fe50afb85e823e395253ea80532
|
[
"Apache-2.0"
] | null | null | null |
test/test_runner.cpp
|
jmalkin/hll-cpp
|
0522f03473352fe50afb85e823e395253ea80532
|
[
"Apache-2.0"
] | null | null | null |
test/test_runner.cpp
|
jmalkin/hll-cpp
|
0522f03473352fe50afb85e823e395253ea80532
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2018, Oath Inc. Licensed under the terms of the
* Apache License 2.0. See LICENSE file at the project root for terms.
*/
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
int main(int argc, char **argv) {
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest() );
bool wasSuccessful = runner.run("", false);
return !wasSuccessful;
}
| 31.625
| 87
| 0.741107
|
jmalkin
|
286a928b8661ddedc4fa3d34e5e5227d5e0e4d76
| 7,310
|
cpp
|
C++
|
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_digital_clock.cpp
|
dawmlight/vendor_oh_fun
|
bc9fb50920f06cd4c27399f60076f5793043c77d
|
[
"Apache-2.0"
] | 1
|
2022-02-15T08:51:55.000Z
|
2022-02-15T08:51:55.000Z
|
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_digital_clock.cpp
|
dawmlight/vendor_oh_fun
|
bc9fb50920f06cd4c27399f60076f5793043c77d
|
[
"Apache-2.0"
] | null | null | null |
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_digital_clock.cpp
|
dawmlight/vendor_oh_fun
|
bc9fb50920f06cd4c27399f60076f5793043c77d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020-2021 Huawei Device 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 "components/ui_digital_clock.h"
#include <cstdio>
#include "components/ui_view_group.h"
#include "font/ui_font.h"
#include "gfx_utils/graphic_log.h"
#include "securec.h"
namespace OHOS {
UIDigitalClock::UIDigitalClock()
: timeLabels_{0},
displayMode_(DISPLAY_24_HOUR),
leadingZero_(true),
color_(Color::White()),
prevHour_(0),
prevMinute_(0),
prevSecond_(0),
verticalShow_(false)
{
style_ = &(StyleDefault::GetBackgroundTransparentStyle());
}
void UIDigitalClock::InitTimeLabels()
{
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
if (timeLabels_[i] == nullptr) {
timeLabels_[i] = new UILabel;
if (timeLabels_[i] == nullptr) {
GRAPHIC_LOGE("new UILabel fail");
return;
}
timeLabels_[i]->SetLineBreakMode(UILabel::LINE_BREAK_ADAPT);
timeLabels_[i]->SetStyle(STYLE_BACKGROUND_OPA, OPA_TRANSPARENT);
Add(timeLabels_[i]);
}
}
}
void UIDigitalClock::DisplayLeadingZero(bool displayLeadingZero)
{
leadingZero_ = displayLeadingZero;
UpdateClock(false);
}
void UIDigitalClock::SetOpacity(uint8_t opacity)
{
opaScale_ = opacity;
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetStyle(STYLE_TEXT_OPA, opacity);
}
RefreshTime();
}
uint8_t UIDigitalClock::GetOpacity() const
{
return opaScale_;
}
void UIDigitalClock::SetFontId(uint8_t fontId)
{
SetStyle(STYLE_TEXT_FONT, fontId);
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetFontId(fontId);
}
UpdateClock(false);
}
void UIDigitalClock::SetFont(const char* name, uint8_t size)
{
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetFont(name, size);
}
UpdateClock(false);
}
void UIDigitalClock::SetColor(ColorType color)
{
color_ = color;
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetStyle(STYLE_TEXT_COLOR, color.full);
}
RefreshTime();
}
void UIDigitalClock::TimeElementRefresh()
{
InitTimeLabels();
if (currentHour_ != prevHour_) {
prevHour_ = currentHour_;
timeLabels_[HOUR_ELEMENT]->Invalidate();
}
if (currentMinute_ != prevMinute_) {
prevMinute_ = currentMinute_;
timeLabels_[MINUTE_ELEMENT]->Invalidate();
}
if (currentSecond_ != prevSecond_) {
prevSecond_ = currentSecond_;
timeLabels_[SECOND_ELEMENT]->Invalidate();
}
}
void UIDigitalClock::RefreshTime()
{
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->Invalidate();
}
}
void UIDigitalClock::UpdateClock(bool clockInit)
{
char buf[TIME_ELEMENT_COUNT][BUFFER_SIZE] = {{0}};
const char* formatWithColon = leadingZero_ ? "%02d:" : "%d:";
const char* formatWithoutColon = leadingZero_ ? "%02d" : "%d";
const char* format = verticalShow_ ? formatWithoutColon : formatWithColon;
const char* formatForMinute = verticalShow_ ? "%02d" : "%02d:";
switch (displayMode_) {
case DISPLAY_24_HOUR_NO_SECONDS: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, "%02d", currentMinute_) < 0) {
return;
}
break;
}
case DISPLAY_12_HOUR_NO_SECONDS: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_ % HALF_DAY_IN_HOUR) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, "%02d", currentMinute_) < 0) {
return;
}
break;
}
case DISPLAY_12_HOUR: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_ % HALF_DAY_IN_HOUR) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, formatForMinute, currentMinute_) < 0) {
return;
}
if (sprintf_s(buf[SECOND_ELEMENT], BUFFER_SIZE, "%02d", currentSecond_) < 0) {
return;
}
break;
}
case DISPLAY_24_HOUR: {
if (sprintf_s(buf[HOUR_ELEMENT], BUFFER_SIZE, format, currentHour_) < 0) {
return;
}
if (sprintf_s(buf[MINUTE_ELEMENT], BUFFER_SIZE, formatForMinute, currentMinute_) < 0) {
return;
}
if (sprintf_s(buf[SECOND_ELEMENT], BUFFER_SIZE, "%02d", currentSecond_) < 0) {
return;
}
break;
}
default: {
break;
}
}
SetTimeLabels(buf);
}
void UIDigitalClock::SetTimeLabels(const char buf[TIME_ELEMENT_COUNT][BUFFER_SIZE])
{
InitTimeLabels();
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetText(buf[i]);
}
SetTimeLabelsPosition();
TimeElementRefresh();
}
void UIDigitalClock::SetHorizontal()
{
InitTimeLabels();
uint16_t totalWidth = timeLabels_[HOUR_ELEMENT]->GetWidth() + timeLabels_[MINUTE_ELEMENT]->GetWidth() +
timeLabels_[SECOND_ELEMENT]->GetWidth();
UITextLanguageAlignment align = timeLabels_[HOUR_ELEMENT]->GetHorAlign();
int16_t x = 0;
Rect rect = GetContentRect();
if (align == TEXT_ALIGNMENT_CENTER) {
x = (rect.GetWidth() >> 1) - (totalWidth >> 1);
} else if (align == TEXT_ALIGNMENT_RIGHT) {
x = rect.GetRight() - totalWidth;
}
timeLabels_[HOUR_ELEMENT]->SetPosition(x, 0);
int16_t width = timeLabels_[HOUR_ELEMENT]->GetWidth();
for (uint8_t i = 1; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetPosition(x + width, 0);
width += timeLabels_[i]->GetWidth();
}
}
void UIDigitalClock::SetTimeLabelsPosition()
{
if (verticalShow_) {
SetVertical();
} else {
SetHorizontal();
}
}
void UIDigitalClock::SetVertical()
{
InitTimeLabels();
int16_t fontHeight = timeLabels_[HOUR_ELEMENT]->GetHeight();
timeLabels_[HOUR_ELEMENT]->SetPosition(0, 0);
int16_t y = fontHeight;
for (uint8_t i = 1; i < TIME_ELEMENT_COUNT; i++) {
timeLabels_[i]->SetPosition(0, y);
y += fontHeight;
}
}
UIDigitalClock::~UIDigitalClock()
{
for (uint8_t i = 0; i < TIME_ELEMENT_COUNT; i++) {
if (timeLabels_[i] != nullptr) {
delete timeLabels_[i];
timeLabels_[i] = nullptr;
}
}
}
} // namespace OHOS
| 29.24
| 107
| 0.61368
|
dawmlight
|
286c5ecf38d03a1dd8d219ba69cecda5722795ee
| 1,415
|
cpp
|
C++
|
1.Top Interview Questions/C++/2.Strings/ReverseString.cpp
|
HanumantappaBudihal/LeetCode-Solutions
|
d46ad49f59e14798ff1716f1259a3e04c7aa3d17
|
[
"MIT"
] | null | null | null |
1.Top Interview Questions/C++/2.Strings/ReverseString.cpp
|
HanumantappaBudihal/LeetCode-Solutions
|
d46ad49f59e14798ff1716f1259a3e04c7aa3d17
|
[
"MIT"
] | null | null | null |
1.Top Interview Questions/C++/2.Strings/ReverseString.cpp
|
HanumantappaBudihal/LeetCode-Solutions
|
d46ad49f59e14798ff1716f1259a3e04c7aa3d17
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <iostream>
#include <cstring>
#include <bits/stdc++.h>
using namespace std;
/************************************************************************************************************
* Problem statement : https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/
*
* //Solution :
* //Time complexity :
* //Space complexity :
*
************************************************************************************************************/
//Normal Approach : using the library methods
class Solution1
{
public:
vector<int> reverseString(vector<int> inputString)
{
reverse(inputString.begin(), inputString.end());
}
};
//Without library
class Solution
{
public:
void reverseString(vector<char> inputString)
{
for (int i = 0, j = inputString.size() - 1; i < j; i++, j--)
{
char temp = inputString[i];
inputString[i] = inputString[j];
inputString[j] = temp;
}
}
};
int main()
{
char inputString[5] = {'h', 'e', 'l', 'l', 'o'};
int numberOfElement = sizeof(inputString) / sizeof(inputString[0]);
std::vector<char> string(numberOfElement);
memcpy(&string[0], &inputString[0], numberOfElement * sizeof(int));
Solution solution;
solution.reverseString(string);
}
| 26.203704
| 114
| 0.497527
|
HanumantappaBudihal
|
286cb47acae02dcb7f8fce48320957ed50ad5f44
| 16,597
|
cpp
|
C++
|
wwivconfig/wwivconfig.cpp
|
k5jat/wwiv
|
b390e476c75f68e0f4f28c66d4a2eecd74753b7c
|
[
"Apache-2.0"
] | null | null | null |
wwivconfig/wwivconfig.cpp
|
k5jat/wwiv
|
b390e476c75f68e0f4f28c66d4a2eecd74753b7c
|
[
"Apache-2.0"
] | null | null | null |
wwivconfig/wwivconfig.cpp
|
k5jat/wwiv
|
b390e476c75f68e0f4f28c66d4a2eecd74753b7c
|
[
"Apache-2.0"
] | null | null | null |
/**************************************************************************/
/* */
/* WWIV Initialization Utility Version 5 */
/* Copyright (C)1998-2017, WWIV Software Services */
/* */
/* 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. */
/* */
/**************************************************************************/
#define _DEFINE_GLOBALS_
#include <cctype>
#include <cerrno>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <memory>
#ifdef _WIN32
#include <direct.h>
#include <io.h>
#endif
#include <locale.h>
#include <sys/stat.h>
#include "local_io/wconstants.h"
#include "core/command_line.h"
#include "core/datafile.h"
#include "core/file.h"
#include "core/inifile.h"
#include "core/log.h"
#include "core/os.h"
#include "core/strings.h"
#include "core/version.cpp"
#include "core/wwivport.h"
#include "wwivconfig/archivers.h"
#include "wwivconfig/autoval.h"
#include "wwivconfig/convert.h"
#include "wwivconfig/editors.h"
#include "wwivconfig/languages.h"
#include "wwivconfig/levels.h"
#include "wwivconfig/menus.h"
#include "wwivconfig/networks.h"
#include "wwivconfig/newinit.h"
#include "wwivconfig/paths.h"
#include "wwivconfig/protocols.h"
#include "wwivconfig/regcode.h"
#include "wwivconfig/subsdirs.h"
#include "wwivconfig/sysop_account.h"
#include "wwivconfig/system_info.h"
#include "wwivconfig/user_editor.h"
#include "wwivconfig/utility.h"
#include "wwivconfig/wwivconfig.h"
#include "wwivconfig/wwivd_ui.h"
#include "sdk/vardec.h"
#include "localui/curses_io.h"
#include "localui/curses_win.h"
#include "localui/input.h"
#include "localui/listbox.h"
#include "localui/stdio_win.h"
#include "localui/ui_win.h"
#include "localui/wwiv_curses.h"
#include "sdk/config.h"
#include "sdk/filenames.h"
#include "sdk/usermanager.h"
using std::string;
using std::vector;
using namespace wwiv::core;
using namespace wwiv::sdk;
using namespace wwiv::strings;
static bool CreateConfigOvr(const string& bbsdir) {
IniFile oini(WWIV_INI, {"WWIV"});
int num_instances = oini.value("NUM_INSTANCES", 4);
std::vector<legacy_configovrrec_424_t> config_ovr_data;
for (int i = 1; i <= num_instances; i++) {
string instance_tag = StringPrintf("WWIV-%u", i);
IniFile ini("wwiv.ini", {instance_tag, "WWIV"});
string temp_directory = ini.value<string>("TEMP_DIRECTORY");
if (temp_directory.empty()) {
LOG(ERROR) << "TEMP_DIRECTORY is not set! Unable to create CONFIG.OVR";
return false;
}
// TEMP_DIRECTORY is defined in wwiv.ini, therefore use it over config.ovr, also
// default the batch_directory to TEMP_DIRECTORY if BATCH_DIRECTORY does not exist.
string batch_directory(ini.value<string>("BATCH_DIRECTORY", temp_directory));
// Replace %n with instance number value.
const auto instance_num_string = std::to_string(i);
StringReplace(&temp_directory, "%n", instance_num_string);
StringReplace(&batch_directory, "%n", instance_num_string);
File::absolute(bbsdir, &temp_directory);
File::absolute(bbsdir, &batch_directory);
File::EnsureTrailingSlash(&temp_directory);
File::EnsureTrailingSlash(&batch_directory);
legacy_configovrrec_424_t r = {};
r.primaryport = 1;
to_char_array(r.batchdir, batch_directory);
to_char_array(r.tempdir, temp_directory);
config_ovr_data.emplace_back(r);
}
DataFile<legacy_configovrrec_424_t> file(CONFIG_OVR, File::modeBinary | File::modeReadWrite |
File::modeCreateFile |
File::modeTruncate);
if (!file) {
LOG(ERROR) << "Unable to open CONFIG.OVR for writing.";
return false;
}
if (!file.WriteVector(config_ovr_data)) {
LOG(ERROR) << "Unable to write to CONFIG.OVR.";
return false;
}
return true;
}
WInitApp::WInitApp() {}
WInitApp::~WInitApp() {
// Don't leak the localIO (also fix the color when the app exits)
delete out;
out = nullptr;
}
int main(int argc, char* argv[]) {
try {
wwiv::core::Logger::Init(argc, argv);
std::unique_ptr<WInitApp> app(new WInitApp());
return app->main(argc, argv);
} catch (const std::exception& e) {
LOG(INFO) << "Fatal exception launching wwivconfig: " << e.what();
}
}
static bool IsUserDeleted(const User& user) { return user.data.inact & inact_deleted; }
static bool CreateSysopAccountIfNeeded(const std::string& bbsdir) {
Config config(bbsdir);
{
UserManager usermanager(config);
auto num_users = usermanager.num_user_records();
for (int n = 1; n <= num_users; n++) {
User u{};
usermanager.readuser(&u, n);
if (!IsUserDeleted(u)) {
return true;
}
}
}
out->Cls(ACS_CKBOARD);
if (!dialog_yn(out->window(), "Would you like to create a sysop account now?")) {
messagebox(out->window(), "You will need to log in locally and manually create one");
return true;
}
create_sysop_account(config);
return true;
}
enum class ShouldContinue { CONTINUE, EXIT };
static ShouldContinue
read_configdat_and_upgrade_datafiles_if_needed(UIWindow* window, const wwiv::sdk::Config& config) {
// Convert 4.2X to 4.3 format if needed.
configrec cfg;
File file(config.config_filename());
if (file.length() != sizeof(configrec)) {
// TODO(rushfan): make a subwindow here but until this clear the altcharset background.
if (!dialog_yn(out->window(), "Upgrade config.dat from 4.x format?")) {
return ShouldContinue::EXIT;
}
window->Bkgd(' ');
convert_config_424_to_430(window, config);
}
if (file.Open(File::modeBinary | File::modeReadOnly)) {
file.Read(&cfg, sizeof(configrec));
}
file.Close();
// Check for 5.2 config
{
static const std::string expected_sig = "WWIV";
if (expected_sig != cfg.header.header.signature) {
// We don't have a 5.2 header, let's convert.
if (!dialog_yn(out->window(), "Upgrade config.dat to 5.2 format?")) {
return ShouldContinue::EXIT;
}
convert_config_to_52(window, config);
{
if (file.Open(File::modeBinary | File::modeReadOnly)) {
file.Read(&cfg, sizeof(configrec));
}
file.Close();
}
}
ensure_latest_5x_config(window, config, cfg);
}
ensure_offsets_are_updated(window, config);
return ShouldContinue::CONTINUE;
}
static void ShowHelp(CommandLine& cmdline) {
std::cout << cmdline.GetHelp() << std::endl;
exit(1);
}
static bool config_offsets_matches_actual(const Config& config) {
File file(config.config_filename());
if (!file.Open(File::modeBinary | File::modeReadWrite)) {
return false;
}
configrec x{};
file.Read(&x, sizeof(configrec));
// update user info data
int16_t userreclen = static_cast<int16_t>(sizeof(userrec));
int16_t waitingoffset = offsetof(userrec, waiting);
int16_t inactoffset = offsetof(userrec, inact);
int16_t sysstatusoffset = offsetof(userrec, sysstatus);
int16_t fuoffset = offsetof(userrec, forwardusr);
int16_t fsoffset = offsetof(userrec, forwardsys);
int16_t fnoffset = offsetof(userrec, net_num);
if (userreclen != x.userreclen || waitingoffset != x.waitingoffset ||
inactoffset != x.inactoffset || sysstatusoffset != x.sysstatusoffset ||
fuoffset != x.fuoffset || fsoffset != x.fsoffset || fnoffset != x.fnoffset) {
return false;
}
return true;
}
bool legacy_4xx_menu(const Config& config, UIWindow* window) {
bool done = false;
int selected = -1;
do {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
vector<ListBoxItem> items = {{"N. Network Configuration", 'N'},
{"U. User Editor", 'U'},
{"W. wwivd Configuration", 'W'},
{"Q. Quit", 'Q'}};
int selected_hotkey = -1;
{
ListBox list(window, "Main Menu", items);
list.selection_returns_hotkey(true);
list.set_additional_hotkeys("$");
list.set_selected(selected);
ListBoxResult result = list.Run();
selected = list.selected();
if (result.type == ListBoxResultType::HOTKEY) {
selected_hotkey = result.hotkey;
} else if (result.type == ListBoxResultType::NO_SELECTION) {
done = true;
}
}
out->footer()->SetDefaultFooter();
// It's easier to use the hotkey for this case statement so it's simple to know
// which case statement matches which item.
switch (selected_hotkey) {
case 'Q':
done = true;
break;
case 'N':
networks(config);
break;
case 'U':
user_editor(config);
break;
case 'W':
wwivd_ui(config);
break;
case '$': {
vector<string> lines;
std::ostringstream ss;
ss << "WWIV " << wwiv_version << beta_version << " wwivconfig compiled " << wwiv_date;
lines.push_back(ss.str());
lines.push_back(StrCat("QSCan Lenth: ", config.qscn_len()));
messagebox(window, lines);
} break;
}
out->SetIndicatorMode(IndicatorMode::NONE);
} while (!done);
return true;
}
int WInitApp::main(int argc, char** argv) {
setlocale(LC_ALL, "");
CommandLine cmdline(argc, argv, "net");
cmdline.AddStandardArgs();
cmdline.set_no_args_allowed(true);
cmdline.add_argument(BooleanCommandLineArgument(
"initialize", "Initialize the datafiles for the 1st time and exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("user_editor", 'U', "Run the user editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("menu_editor", 'M', "Run the menu editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("network_editor", 'N', "Run the network editor and then exit.", false));
cmdline.add_argument(
BooleanCommandLineArgument("4xx", '4', "Only run editors that work on WWIV 4.xx.", false));
cmdline.add_argument({"menu_dir", "Override the menu directory when using --menu_editor.", ""});
if (!cmdline.Parse() || cmdline.help_requested()) {
ShowHelp(cmdline);
return 0;
}
auto bbsdir = File::EnsureTrailingSlash(cmdline.bbsdir());
const bool forced_initialize = cmdline.barg("initialize");
UIWindow* window;
if (forced_initialize) {
window = new StdioWindow(nullptr, new ColorScheme());
} else {
CursesIO::Init(StringPrintf("WWIV %s%s Configuration Program.", wwiv_version, beta_version));
window = out->window();
out->Cls(ACS_CKBOARD);
window->SetColor(SchemeId::NORMAL);
}
if (forced_initialize && File::Exists(CONFIG_DAT)) {
messagebox(window, "Unable to use --initialize when CONFIG.DAT exists.");
return 1;
}
bool need_to_initialize = !File::Exists(CONFIG_DAT) || forced_initialize;
if (need_to_initialize) {
window->Bkgd(' ');
if (!new_init(window, bbsdir, need_to_initialize)) {
return 2;
}
}
Config config(bbsdir);
bool legacy_4xx_mode = false;
if (cmdline.barg("menu_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
auto menu_dir = config.menudir();
auto menu_dir_arg = cmdline.sarg("menu_dir");
if (!menu_dir_arg.empty()) {
menu_dir = menu_dir_arg;
}
menus(menu_dir);
return 0;
} else if (cmdline.barg("user_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
user_editor(config);
return 0;
} else if (cmdline.barg("network_editor")) {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
if (!config_offsets_matches_actual(config)) {
return 1;
}
networks(config);
return 0;
} else if (cmdline.barg("4xx")) {
if (!config_offsets_matches_actual(config)) {
return 1;
}
legacy_4xx_mode = true;
}
if (!legacy_4xx_mode &&
read_configdat_and_upgrade_datafiles_if_needed(window, config) ==
ShouldContinue::EXIT) {
legacy_4xx_mode = true;
}
if (legacy_4xx_mode) {
legacy_4xx_menu(config, window);
return 0;
}
CreateConfigOvr(bbsdir);
{
File archiverfile(FilePath(config.datadir(), ARCHIVER_DAT));
if (!archiverfile.Open(File::modeBinary | File::modeReadOnly)) {
create_arcs(window, config.datadir());
}
}
if (forced_initialize) {
return 0;
}
// GP - We can move this up to after "read_status" if the
// wwivconfig --initialize flow should query the user to make an account.
CreateSysopAccountIfNeeded(bbsdir);
bool done = false;
int selected = -1;
do {
out->Cls(ACS_CKBOARD);
out->footer()->SetDefaultFooter();
vector<ListBoxItem> items = {{"G. General System Configuration", 'G'},
{"P. System Paths", 'P'},
{"T. External Transfer Protocol Configuration", 'T'},
{"E. External Editor Configuration", 'E'},
{"S. Security Level Configuration", 'S'},
{"V. Auto-Validation Level Configuration", 'V'},
{"A. Archiver Configuration", 'A'},
{"L. Language Configuration", 'L'},
{"M. Menu Editor", 'M'},
{"N. Network Configuration", 'N'},
{"R. Registration Information", 'R'},
{"U. User Editor", 'U'},
{"X. Update Sub/Directory Maximums", 'X'},
{"W. wwivd Configuration", 'W'},
{"Q. Quit", 'Q'}};
int selected_hotkey = -1;
{
ListBox list(window, "Main Menu", items);
list.selection_returns_hotkey(true);
list.set_additional_hotkeys("$");
list.set_selected(selected);
ListBoxResult result = list.Run();
selected = list.selected();
if (result.type == ListBoxResultType::HOTKEY) {
selected_hotkey = result.hotkey;
} else if (result.type == ListBoxResultType::NO_SELECTION) {
done = true;
}
}
out->footer()->SetDefaultFooter();
// It's easier to use the hotkey for this case statement so it's simple to know
// which case statement matches which item.
switch (selected_hotkey) {
case 'Q':
done = true;
break;
case 'G':
sysinfo1(config);
break;
case 'P':
setpaths(config);
break;
case 'T':
extrn_prots(config.datadir());
break;
case 'E':
extrn_editors(config);
break;
case 'S':
sec_levs(config);
break;
case 'V':
autoval_levs(config);
break;
case 'A':
edit_archivers(config);
break;
case 'L':
edit_languages(config);
break;
case 'N':
networks(config);
break;
case 'M':
menus(config.menudir());
break;
case 'R':
edit_registration_code(config);
break;
case 'U':
user_editor(config);
break;
case 'W':
wwivd_ui(config);
break;
case 'X':
up_subs_dirs(config);
break;
case '$': {
vector<string> lines;
std::ostringstream ss;
ss << "WWIV " << wwiv_version << beta_version << " wwivconfig compiled " << wwiv_date;
lines.push_back(ss.str());
lines.push_back(StrCat("QSCan Lenth: ", config.qscn_len()));
messagebox(window, lines);
} break;
}
out->SetIndicatorMode(IndicatorMode::NONE);
} while (!done);
config.Save();
return 0;
}
| 31.433712
| 105
| 0.607519
|
k5jat
|
286ef9f4e191c1ea6fcfc7ba46470f3ba04df768
| 499
|
hpp
|
C++
|
tools/converter/include/cli.hpp
|
xhuan28/MNN
|
81df3a48d79cbc0b75251d12934345948866f7be
|
[
"Apache-2.0"
] | 3
|
2019-12-27T01:10:32.000Z
|
2021-05-14T08:10:40.000Z
|
tools/converter/include/cli.hpp
|
xhuan28/MNN
|
81df3a48d79cbc0b75251d12934345948866f7be
|
[
"Apache-2.0"
] | 10
|
2019-07-04T01:40:13.000Z
|
2019-10-30T02:38:42.000Z
|
tools/converter/include/cli.hpp
|
xhuan28/MNN
|
81df3a48d79cbc0b75251d12934345948866f7be
|
[
"Apache-2.0"
] | 1
|
2021-01-15T06:28:11.000Z
|
2021-01-15T06:28:11.000Z
|
//
// cli.hpp
// MNNConverter
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef CLI_HPP
#define CLI_HPP
#include <iostream>
#include "config.hpp"
#include "cxxopts.hpp"
class Cli {
public:
static void printProjectBanner();
static cxxopts::Options initializeMNNConvertArgs(modelConfig &modelPath, int argc, char **argv);
};
using namespace std;
class CommonKit {
public:
static bool FileIsExist(string path);
};
#endif // CLI_HPP
| 16.633333
| 100
| 0.709419
|
xhuan28
|
2870ca201c9d033ac2921ff82a4d3509719167a1
| 2,492
|
hpp
|
C++
|
api/CPP/fully_connected_grad_input.hpp
|
liyuming1978/clDNN
|
05e19dd2229dc977c2902ec360f3165ecb925b50
|
[
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null |
api/CPP/fully_connected_grad_input.hpp
|
liyuming1978/clDNN
|
05e19dd2229dc977c2902ec360f3165ecb925b50
|
[
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null |
api/CPP/fully_connected_grad_input.hpp
|
liyuming1978/clDNN
|
05e19dd2229dc977c2902ec360f3165ecb925b50
|
[
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null |
/*
// Copyright (c) 2016 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "../C/fully_connected_grad_input.h"
#include "primitive.hpp"
namespace cldnn
{
/// @addtogroup cpp_api C++ API
/// @{
/// @addtogroup cpp_topology Network Topology
/// @{
/// @addtogroup cpp_primitives Primitives
/// @{
/// @brief Performs backward fully connected layer (inner product) for input.
struct fully_connected_grad_input : public primitive_base<fully_connected_grad_input, CLDNN_PRIMITIVE_DESC(fully_connected_grad_input)>
{
CLDNN_DECLARE_PRIMITIVE(fully_connected_grad_input)
/// @brief Constructs fully connected layer grad for input.
/// @param id This primitive id.
/// @param input Input gradient primitive id.
/// @param input Input primitive id.
/// @param weights Primitive id containing weights data.
/// @param bias Primitive id containing bias data. Provide empty string if using Relu without bias.
fully_connected_grad_input(
const primitive_id& id,
const primitive_id& input_grad,
const primitive_id& input,
const primitive_id& weights,
const padding& output_padding = padding()
)
: primitive_base(id, { input_grad, input }, output_padding)
, weights(weights)
{
}
/// @brief Constructs a copy from basic C API @CLDNN_PRIMITIVE_DESC{fully_connected_grad_input}
fully_connected_grad_input(const dto* dto)
:primitive_base(dto)
, weights(dto->weights)
{
}
/// @brief Primitive id containing weights data.
primitive_id weights;
protected:
std::vector<std::reference_wrapper<const primitive_id>> get_dependencies() const override
{
return{ weights };
}
void update_dto(dto& dto) const override
{
dto.weights = weights.c_str();
}
};
/// @}
/// @}
/// @}
}
| 31.544304
| 135
| 0.668941
|
liyuming1978
|
287383cba67d98a84142fed9f734d6bae19a47fa
| 2,432
|
hpp
|
C++
|
android-28/android/os/storage/StorageManager.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-28/android/os/storage/StorageManager.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-28/android/os/storage/StorageManager.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#pragma once
#include "../../../JObject.hpp"
namespace android::os
{
class Handler;
}
namespace android::os
{
class ParcelFileDescriptor;
}
namespace android::os
{
class ProxyFileDescriptorCallback;
}
namespace android::os::storage
{
class OnObbStateChangeListener;
}
namespace android::os::storage
{
class StorageVolume;
}
namespace java::io
{
class File;
}
namespace java::io
{
class FileDescriptor;
}
class JString;
namespace java::util
{
class UUID;
}
namespace android::os::storage
{
class StorageManager : public JObject
{
public:
// Fields
static JString ACTION_MANAGE_STORAGE();
static JString EXTRA_REQUESTED_BYTES();
static JString EXTRA_UUID();
static java::util::UUID UUID_DEFAULT();
// QJniObject forward
template<typename ...Ts> explicit StorageManager(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
StorageManager(QJniObject obj);
// Constructors
// Methods
void allocateBytes(java::io::FileDescriptor arg0, jlong arg1) const;
void allocateBytes(java::util::UUID arg0, jlong arg1) const;
jlong getAllocatableBytes(java::util::UUID arg0) const;
jlong getCacheQuotaBytes(java::util::UUID arg0) const;
jlong getCacheSizeBytes(java::util::UUID arg0) const;
JString getMountedObbPath(JString arg0) const;
android::os::storage::StorageVolume getPrimaryStorageVolume() const;
android::os::storage::StorageVolume getStorageVolume(java::io::File arg0) const;
JObject getStorageVolumes() const;
java::util::UUID getUuidForPath(java::io::File arg0) const;
jboolean isAllocationSupported(java::io::FileDescriptor arg0) const;
jboolean isCacheBehaviorGroup(java::io::File arg0) const;
jboolean isCacheBehaviorTombstone(java::io::File arg0) const;
jboolean isEncrypted(java::io::File arg0) const;
jboolean isObbMounted(JString arg0) const;
jboolean mountObb(JString arg0, JString arg1, android::os::storage::OnObbStateChangeListener arg2) const;
android::os::ParcelFileDescriptor openProxyFileDescriptor(jint arg0, android::os::ProxyFileDescriptorCallback arg1, android::os::Handler arg2) const;
void setCacheBehaviorGroup(java::io::File arg0, jboolean arg1) const;
void setCacheBehaviorTombstone(java::io::File arg0, jboolean arg1) const;
jboolean unmountObb(JString arg0, jboolean arg1, android::os::storage::OnObbStateChangeListener arg2) const;
};
} // namespace android::os::storage
| 30.4
| 155
| 0.759457
|
YJBeetle
|
2874ba54b9cc00fb38738fe05b1f3ff4d4663b63
| 2,458
|
hpp
|
C++
|
include/hipSYCL/compiler/cbs/LoopsParallelMarker.hpp
|
mfkiwl/hipSYCL
|
baf07483f5f5061b4c5ae73c8ddb0c83786dca3c
|
[
"BSD-2-Clause"
] | null | null | null |
include/hipSYCL/compiler/cbs/LoopsParallelMarker.hpp
|
mfkiwl/hipSYCL
|
baf07483f5f5061b4c5ae73c8ddb0c83786dca3c
|
[
"BSD-2-Clause"
] | null | null | null |
include/hipSYCL/compiler/cbs/LoopsParallelMarker.hpp
|
mfkiwl/hipSYCL
|
baf07483f5f5061b4c5ae73c8ddb0c83786dca3c
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* This file is part of hipSYCL, a SYCL implementation based on CUDA/HIP
*
* Copyright (c) 2021 Aksel Alpay and contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HIPSYCL_LOOPSPARALLELMARKER_HPP
#define HIPSYCL_LOOPSPARALLELMARKER_HPP
#include "llvm/IR/PassManager.h"
#include "llvm/Pass.h"
namespace hipsycl {
namespace compiler {
// marks the wi-loops as parallel (vectorizable) and enables vectorization.
class LoopsParallelMarkerPassLegacy : public llvm::FunctionPass {
public:
static char ID;
explicit LoopsParallelMarkerPassLegacy() : llvm::FunctionPass(ID) {}
llvm::StringRef getPassName() const override { return "hipSYCL loop parallel marking pass"; }
void getAnalysisUsage(llvm::AnalysisUsage &AU) const override;
bool runOnFunction(llvm::Function &L) override;
};
class LoopsParallelMarkerPass : public llvm::PassInfoMixin<LoopsParallelMarkerPass> {
public:
explicit LoopsParallelMarkerPass() {}
llvm::PreservedAnalyses run(llvm::Function &F, llvm::FunctionAnalysisManager &AM);
static bool isRequired() { return false; }
};
} // namespace compiler
} // namespace hipsycl
#endif // HIPSYCL_LOOPSPARALLELMARKER_HPP
| 37.815385
| 95
| 0.772986
|
mfkiwl
|
2875d539af4ea6d77cd798d56a8caaa28fc4a3f2
| 878
|
cpp
|
C++
|
routing/junction_visitor.cpp
|
swaitw/organicmaps
|
ab34d4d405ed22a5af94afa932b841b9ee6f6fd1
|
[
"Apache-2.0"
] | null | null | null |
routing/junction_visitor.cpp
|
swaitw/organicmaps
|
ab34d4d405ed22a5af94afa932b841b9ee6f6fd1
|
[
"Apache-2.0"
] | null | null | null |
routing/junction_visitor.cpp
|
swaitw/organicmaps
|
ab34d4d405ed22a5af94afa932b841b9ee6f6fd1
|
[
"Apache-2.0"
] | null | null | null |
#include "junction_visitor.hpp"
#include "routing/joint_segment.hpp"
#include "routing/route_weight.hpp"
#include "base/logging.hpp"
namespace routing
{
#ifdef DEBUG
void DebugRoutingState(JointSegment const & vertex, std::optional<JointSegment> const & parent,
RouteWeight const & heuristic, RouteWeight const & distance)
{
// 1. Dump current processing vertex.
// std::cout << DebugPrint(vertex);
// std::cout << std::setprecision(8) << "; H = " << heuristic << "; D = " << distance;
// 2. Dump parent vertex.
// std::cout << "; P = " << (parent ? DebugPrint(*parent) : std::string("NO"));
// std::cout << std::endl;
// 3. Set breakpoint on a specific vertex.
// if (vertex.GetMwmId() == 706 && vertex.GetFeatureId() == 147648 &&
// vertex.GetEndSegmentId() == 75)
// {
// int noop = 0;
// }
}
#endif
} // namespace routing
| 25.823529
| 95
| 0.626424
|
swaitw
|
287a82b966168a85726b83082e51688a7df03935
| 6,669
|
cpp
|
C++
|
EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp
|
MacgyverLin/MagnumEngine
|
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
|
[
"MIT"
] | 1
|
2021-03-30T06:28:32.000Z
|
2021-03-30T06:28:32.000Z
|
EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp
|
MacgyverLin/MagnumEngine
|
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
|
[
"MIT"
] | null | null | null |
EpicForceEngine/MagnumEngineLib/MagnumCore/AudioSourceBase.cpp
|
MacgyverLin/MagnumEngine
|
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////////
// Copyright(c) 2016, Lin Koon Wing Macgyver, macgyvercct@yahoo.com.hk //
// //
// Author : Mac Lin //
// Module : Magnum Engine v1.0.0 //
// Date : 14/Jun/2016 //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "Audio.h"
#include "AudioSourceBase.h"
#include "fmod.hpp"
#include "fmod_errors.h"
using namespace Magnum;
AudioSourceBase::AudioSourceBase(Component::Owner &owner_)
: AudioComponent(owner_)
, channelHandle(0)
, paused(false)
, muteEnabled(false)
, bypassEffectsEnabled(false)
, loopEnabled(false)
, priority(128)
, volume(1)
, pitch(1)
, dopplerLevel(1)
, volumeDecayMode(LogorithmRollOff)
, minDistance(1)
, panLevel(1)
, spread(0)
, maxDistance(500)
{
Audio::Manager::instance().audioSources.push() = this;
}
AudioSourceBase::~AudioSourceBase()
{
int idx = Audio::Manager::instance().audioSources.search(this);
if(idx>=0)
{
Audio::Manager::instance().audioSources.remove(idx);
}
}
void AudioSourceBase::stop()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
if(channel)
{
FMOD_RESULT result;
result = channel->stop();
channel = 0;
}
}
void AudioSourceBase::pause()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
paused = true;
if(channel)
channel->setPaused(true);
}
void AudioSourceBase::resume()
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
paused = false;
if(channel)
channel->setPaused(false);
}
void AudioSourceBase::setMuteEnable(bool muteEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
muteEnabled = muteEnable_;
if(channel)
{
channel->setMute(muteEnabled);
}
}
void AudioSourceBase::setBypassEffectsEnable(bool bypassEffectsEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
bypassEffectsEnabled = bypassEffectsEnable_;
if(channel)
{
assert(0);
}
}
void AudioSourceBase::setLoopEnable(bool loopEnable_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
loopEnabled = loopEnable_;
if(channel)
{
if(loopEnable_)
{
//result = channel->setMode(FMOD_LOOP_NORMAL);
result = channel->setLoopCount(-1);
}
else
{
//result = channel->setMode(FMOD_LOOP_OFF);
result = channel->setLoopCount(0);
}
}
}
void AudioSourceBase::setPriority(int priority_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
priority = priority_;
if(channel)
{
channel->setPriority(priority);
}
}
void AudioSourceBase::setVolume(float volume_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
volume = volume_;
if(channel)
{
channel->setVolume(volume);
}
}
void AudioSourceBase::setPitch(float pitch_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
pitch = pitch_;
if(channel)
{
FMOD::Sound *sound;
result = channel->getCurrentSound(&sound);
if(sound)
{
float frequency;
sound->getDefaults(&frequency, 0, 0, 0);
channel->setFrequency(frequency * pitch);
}
}
}
void AudioSourceBase::set3DDopplerLevel(float dopplerLevel_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
dopplerLevel = dopplerLevel_;
if(channel)
{
channel->set3DDopplerLevel(dopplerLevel_);
}
}
void AudioSourceBase::set3DVolumeDecayMode(AudioSourceBase::DecayMode volumeDecayMode_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
volumeDecayMode = volumeDecayMode_;
if(channel)
{
assert(0);
}
}
void AudioSourceBase::set3DMinDistance(float minDistance_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
minDistance = minDistance_;
if(channel)
{
channel->set3DMinMaxDistance(minDistance, maxDistance);
}
}
void AudioSourceBase::set3DPanLevel(float panLevel_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
panLevel = panLevel_;
if(channel)
{
channel->set3DPanLevel(panLevel);
}
}
void AudioSourceBase::set3DSpread(float spread_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
spread = spread_;
if(channel)
{
channel->set3DSpread(spread);
}
}
void AudioSourceBase::set3DMaxDistance(float maxDistance_)
{
FMOD_RESULT result;
FMOD::System *system = (FMOD::System *)(getSystemHandle());
FMOD::Channel *channel = (FMOD::Channel *)channelHandle;
maxDistance = maxDistance_;
if(channel)
{
channel->set3DMinMaxDistance(minDistance, maxDistance);
}
}
bool AudioSourceBase::isPaused() const
{
return paused;
}
bool AudioSourceBase::isMuteEnabled() const
{
return muteEnabled;
}
bool AudioSourceBase::isBypassEffectsEnabled() const
{
return bypassEffectsEnabled;
}
bool AudioSourceBase::isLoopEnabled() const
{
return loopEnabled;
}
int AudioSourceBase::getPriority() const
{
return priority;
}
float AudioSourceBase::getVolume() const
{
return volume;
}
float AudioSourceBase::getPitch() const
{
return pitch;
}
float AudioSourceBase::get3DDopplerLevel() const
{
return dopplerLevel;
}
AudioSourceBase::DecayMode AudioSourceBase::get3DVolumeDecayMode() const
{
return volumeDecayMode;
}
float AudioSourceBase::get3DMinDistance() const
{
return minDistance;
}
float AudioSourceBase::get3DPanLevel() const
{
return panLevel;
}
float AudioSourceBase::get3DSpread() const
{
return spread;
}
float AudioSourceBase::get3DMaxDistance() const
{
return maxDistance;
}
void *AudioSourceBase::getChannelHandle()
{
return channelHandle;
}
| 20.027027
| 87
| 0.690508
|
MacgyverLin
|
287b22e519dd780eb231663c37e9b63ca68a8796
| 753
|
cpp
|
C++
|
src/scene/light.cpp
|
nolmoonen/pbr
|
c5ed37795c8e67de1716762206fe7c58e9079ac0
|
[
"MIT"
] | null | null | null |
src/scene/light.cpp
|
nolmoonen/pbr
|
c5ed37795c8e67de1716762206fe7c58e9079ac0
|
[
"MIT"
] | null | null | null |
src/scene/light.cpp
|
nolmoonen/pbr
|
c5ed37795c8e67de1716762206fe7c58e9079ac0
|
[
"MIT"
] | null | null | null |
#include "light.hpp"
#include "../util/nm_math.hpp"
#include "../system/renderer.hpp"
Light::Light(
Scene *scene, Renderer *renderer, glm::vec3 position, glm::vec3 color
) :
SceneObject(scene, renderer, position), color(color)
{}
void Light::render(bool debug_mode)
{
SceneObject::render(debug_mode);
renderer->render_default(
PRIMITIVE_SPHERE,
color,
glm::scale(
glm::translate(
glm::identity<glm::mat4>(),
position),
glm::vec3(1.f / SCALE)));
}
bool Light::hit(float *t, glm::vec3 origin, glm::vec3 direction)
{
return nm_math::ray_sphere(t, origin, direction, position, 1.f / SCALE);
}
| 25.965517
| 77
| 0.564409
|
nolmoonen
|
287d5513210df00735b4bdf41df40e8f8c8b77b1
| 1,399
|
cpp
|
C++
|
algorithm/SSSP-on-unweight-graph.cpp
|
AREA44/competitive-programming
|
00cede478685bf337193bce4804f13c4ff170903
|
[
"MIT"
] | null | null | null |
algorithm/SSSP-on-unweight-graph.cpp
|
AREA44/competitive-programming
|
00cede478685bf337193bce4804f13c4ff170903
|
[
"MIT"
] | null | null | null |
algorithm/SSSP-on-unweight-graph.cpp
|
AREA44/competitive-programming
|
00cede478685bf337193bce4804f13c4ff170903
|
[
"MIT"
] | null | null | null |
#include "iostream"
#include "stdio.h"
#include "string"
#include "string.h"
#include "algorithm"
#include "math.h"
#include "vector"
#include "map"
#include "queue"
#include "stack"
#include "deque"
#include "set"
using namespace std;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int inf = 1e9;
#define DFS_WHITE -1 // UNVISITED
#define DFS_BLACK 1 // EXPLORED
#define DFS_GRAY 2 // VISTED BUT NOT EXPLORED
vector<vii> AdjList;
int V, E, u, v, s;
void graphUndirected(){
scanf("%d %d", &V, &E);
AdjList.assign(V + 4, vii());
for (int i = 0; i < E; i++) {
scanf("%d %d", &u, &v);
AdjList[u].push_back(ii(v, 0));
AdjList[v].push_back(ii(u, 0));
}
}
vi p;
void printPath(int u) {
if (u == s) { printf("%d", u); return; }
printPath(p[u]);
printf(" %d", u);
}
void bfs(int s){
vi d(V + 4, inf); d[s] = 0;
queue<int> q; q.push(s);
p.assign(V + 4, -1);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int j = 0; j < (int)AdjList[u].size(); j++) {
ii v = AdjList[u][j];
if (d[v.first] == inf) {
d[v.first] = d[u] + 1;
p[v.first] = u;
q.push(v.first);
}
}
}
}
int main(){
graphUndirected();
s = 5, bfs(s);
printPath(7);
printf("\n");
return 0;
}
| 20.573529
| 58
| 0.50965
|
AREA44
|
287f40965278d62cc02152fb361085318976bba3
| 26,955
|
hpp
|
C++
|
include/barry/barray-meat.hpp
|
USCbiostats/barry
|
79c363b9f31d9ee03b3ae199e98c688ffc2abdd0
|
[
"MIT"
] | 8
|
2020-07-21T01:30:35.000Z
|
2022-03-09T15:51:14.000Z
|
include/barry/barray-meat.hpp
|
USCbiostats/barry
|
79c363b9f31d9ee03b3ae199e98c688ffc2abdd0
|
[
"MIT"
] | 2
|
2022-01-24T20:51:46.000Z
|
2022-03-16T23:08:40.000Z
|
include/barry/barray-meat.hpp
|
USCbiostats/barry
|
79c363b9f31d9ee03b3ae199e98c688ffc2abdd0
|
[
"MIT"
] | null | null | null |
// #include <stdexcept>
#include "barray-bones.hpp"
#ifndef BARRY_BARRAY_MEAT_HPP
#define BARRY_BARRAY_MEAT_HPP
#define BARRAY_TYPE() BArray<Cell_Type, Data_Type>
#define BARRAY_TEMPLATE_ARGS() <typename Cell_Type, typename Data_Type>
#define BARRAY_TEMPLATE(a,b) \
template BARRAY_TEMPLATE_ARGS() inline a BARRAY_TYPE()::b
#define ROW(a) this->el_ij[a]
#define COL(a) this->el_ji[a]
template<typename Cell_Type, typename Data_Type>
Cell<Cell_Type> BArray<Cell_Type,Data_Type>::Cell_default = Cell<Cell_Type>();
// Edgelist with data
BARRAY_TEMPLATE(,BArray) (
uint N_, uint M_,
const std::vector< uint > & source,
const std::vector< uint > & target,
const std::vector< Cell_Type > & value,
bool add
) {
if (source.size() != target.size())
throw std::length_error("-source- and -target- don't match on length.");
if (source.size() != value.size())
throw std::length_error("-sorce- and -value- don't match on length.");
// Initializing
N = N_;
M = M_;
el_ij.resize(N);
el_ji.resize(M);
// Writing the data
for (uint i = 0u; i < source.size(); ++i) {
// Checking range
bool empty = this->is_empty(source[i], target[i], true);
if (add && !empty) {
ROW(source[i])[target[i]].add(value[i]);
continue;
}
if (!empty)
throw std::logic_error("The value already exists. Use 'add = true'.");
this->insert_cell(source[i], target[i], value[i], false, false);
}
return;
}
// Edgelist with data
BARRAY_TEMPLATE(,BArray) (
uint N_, uint M_,
const std::vector< uint > & source,
const std::vector< uint > & target,
bool add
) {
std::vector< Cell_Type > value(source.size(), (Cell_Type) 1.0);
if (source.size() != target.size())
throw std::length_error("-source- and -target- don't match on length.");
if (source.size() != value.size())
throw std::length_error("-sorce- and -value- don't match on length.");
// Initializing
N = N_;
M = M_;
el_ij.resize(N);
el_ji.resize(M);
// Writing the data
for (uint i = 0u; i < source.size(); ++i) {
// Checking range
if ((source[i] >= N_) | (target[i] >= M_))
throw std::range_error("Either source or target point to an element outside of the range by (N,M).");
// Checking if it exists
auto search = ROW(source[i]).find(target[i]);
if (search != ROW(source[i]).end()) {
if (!add)
throw std::logic_error("The value already exists. Use 'add = true'.");
// Increasing the value (this will automatically update the
// other value)
ROW(source[i])[target[i]].add(value[i]);
continue;
}
// Adding the value and creating a pointer to it
ROW(source[i]).emplace(
std::pair<uint, Cell< Cell_Type> >(
target[i],
Cell< Cell_Type >(value[i], visited)
)
);
COL(target[i]).emplace(
source[i],
&ROW(source[i])[target[i]]
);
NCells++;
}
return;
}
BARRAY_TEMPLATE(,BArray) (
const BArray<Cell_Type,Data_Type> & Array_,
bool copy_data
) : N(Array_.N), M(Array_.M)
{
// Dimensions
// el_ij.resize(N);
// el_ji.resize(M);
std::copy(Array_.el_ij.begin(), Array_.el_ij.end(), std::back_inserter(el_ij));
std::copy(Array_.el_ji.begin(), Array_.el_ji.end(), std::back_inserter(el_ji));
// Taking care of the pointers
for (uint i = 0u; i < N; ++i)
{
for (auto& r: row(i, false))
COL(r.first)[i] = &ROW(i)[r.first];
}
this->NCells = Array_.NCells;
this->visited = Array_.visited;
// Data
if (Array_.data != nullptr)
{
if (copy_data)
{
data = new Data_Type(* Array_.data );
delete_data = true;
} else {
data = Array_.data;
delete_data = false;
}
}
return;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator=) (
const BArray<Cell_Type,Data_Type> & Array_
) {
// Clearing
if (this != &Array_)
{
this->clear(true);
this->resize(Array_.N, Array_.M);
// Entries
for (uint i = 0u; i < N; ++i)
{
if (Array_.nnozero() == nnozero())
break;
for (auto& r : Array_.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Data
if (data != nullptr)
{
if (delete_data)
delete data;
data = nullptr;
delete_data = false;
}
if (Array_.data != nullptr)
{
data = new Data_Type(*Array_.data);
delete_data = true;
}
}
return *this;
}
BARRAY_TEMPLATE(,BArray) (
BARRAY_TYPE() && x
) noexcept :
N(0u), M(0u), NCells(0u),
data(nullptr),
delete_data(x.delete_data)
{
this->clear(true);
this->resize(x.N, x.M);
// Entries
for (uint i = 0u; i < N; ++i) {
if (x.nnozero() == nnozero())
break;
for (auto& r : x.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Managing data
if (x.data != nullptr)
{
if (x.delete_data)
{
data = new Data_Type(*x.data);
delete_data = true;
} else {
data = x.data;
delete_data = false;
}
}
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator=) (
BARRAY_TYPE() && x
) noexcept {
// Clearing
if (this != &x) {
this->clear(true);
this->resize(x.N, x.M);
// Entries
for (uint i = 0u; i < N; ++i) {
if (x.nnozero() == nnozero())
break;
for (auto& r : x.row(i, false))
this->insert_cell(i, r.first, r.second.value, false, false);
}
// Data
if (data != nullptr)
{
if (delete_data)
delete data;
data = nullptr;
delete_data = false;
}
if (x.data != nullptr)
{
data = new Data_Type( *x.data );
delete_data = true;
}
// x.data = nullptr;
// x.delete_data = false;
}
return *this;
}
BARRAY_TEMPLATE(bool, operator==) (
const BARRAY_TYPE() & Array_
) {
// Dimension and number of cells used
if ((N != Array_.nrow()) | (M != Array_.ncol()) | (NCells != Array_.nnozero()))
return false;
// One holds, and the other doesn't.
if ((!data & Array_.data) | (data & !Array_.data))
return false;
if (this->el_ij != Array_.el_ij)
return false;
return true;
}
BARRAY_TEMPLATE(,~BArray) () {
if (delete_data && (data != nullptr))
delete data;
return;
}
BARRAY_TEMPLATE(void, set_data) (
Data_Type * data_, bool delete_data_
) {
if ((data != nullptr) && delete_data)
delete data;
data = data_;
delete_data = delete_data_;
return;
}
BARRAY_TEMPLATE(Data_Type *, D) ()
{
return this->data;
}
template<typename Cell_Type, typename Data_Type>
inline const Data_Type * BArray<Cell_Type,Data_Type>::D() const
{
return this->data;
}
template<typename Cell_Type, typename Data_Type>
inline void BArray<Cell_Type,Data_Type>::flush_data()
{
if (delete_data)
{
delete data;
delete_data = false;
}
data = nullptr;
return;
}
BARRAY_TEMPLATE(void, out_of_range) (
uint i,
uint j
) const {
if (i >= N)
throw std::range_error("The row is out of range.");
else if (j >= M)
throw std::range_error("The column is out of range.");
return;
}
BARRAY_TEMPLATE(Cell_Type, get_cell) (
uint i,
uint j,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i,j);
if (ROW(i).size() == 0u)
return (Cell_Type) 0.0;
// If it is not empty, then find and return
auto search = ROW(i).find(j);
if (search != ROW(i).end())
return search->second.value;
// This is if it is empty
return (Cell_Type) 0.0;
}
BARRAY_TEMPLATE(std::vector< Cell_Type >, get_row_vec) (
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i, 0u);
std::vector< Cell_Type > ans(ncol(), (Cell_Type) false);
for (const auto & iter : row(i, false))
ans[iter.first] = iter.second.value; //this->get_cell(i, iter->first, false);
return ans;
}
BARRAY_TEMPLATE(void, get_row_vec) (
std::vector< Cell_Type > * x,
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(i, 0u);
for (const auto & iter : row(i, false))
x->at(iter.first) = iter.second.value; // this->get_cell(i, iter->first, false);
}
BARRAY_TEMPLATE(std::vector< Cell_Type >, get_col_vec) (
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(0u, i);
std::vector< Cell_Type > ans(nrow(), (Cell_Type) false);
for (const auto iter : col(i, false))
ans[iter.first] = iter.second->value;//this->get_cell(iter->first, i, false);
return ans;
}
BARRAY_TEMPLATE(void, get_col_vec) (
std::vector<Cell_Type> * x,
uint i,
bool check_bounds
) const {
// Checking boundaries
if (check_bounds)
out_of_range(0u, i);
for (const auto & iter : col(i, false))
x->at(iter.first) = iter.second->value;//this->get_cell(iter->first, i, false);
}
BARRAY_TEMPLATE(const Row_type< Cell_Type > &, row) (
uint i,
bool check_bounds
) const {
if (check_bounds)
out_of_range(i, 0u);
return this->el_ij[i];
}
BARRAY_TEMPLATE(const Col_type< Cell_Type > &, col) (
uint i,
bool check_bounds
) const {
if (check_bounds)
out_of_range(0u, i);
return this->el_ji[i];
}
BARRAY_TEMPLATE(Entries< Cell_Type >, get_entries) () const {
Entries<Cell_Type> res(NCells);
for (uint i = 0u; i < N; ++i) {
if (ROW(i).size() == 0u)
continue;
for (auto col = ROW(i).begin(); col != ROW(i).end(); ++col) {
res.source.push_back(i),
res.target.push_back(col->first),
res.val.push_back(col->second.value);
}
}
return res;
}
BARRAY_TEMPLATE(bool, is_empty) (
uint i,
uint j,
bool check_bounds
) const {
if (check_bounds)
out_of_range(i, j);
if (ROW(i).size() == 0u)
return true;
else if (COL(j).size() == 0u)
return true;
if (ROW(i).find(j) == ROW(i).end())
return true;
return false;
}
BARRAY_TEMPLATE(unsigned int, nrow) () const noexcept {
return N;
}
BARRAY_TEMPLATE(unsigned int, ncol) () const noexcept {
return M;
}
BARRAY_TEMPLATE(unsigned int, nnozero) () const noexcept {
return NCells;
}
BARRAY_TEMPLATE(Cell< Cell_Type >, default_val) () const {
return this->Cell_default;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator+=) (
const std::pair<uint,uint> & coords
) {
this->insert_cell(
coords.first,
coords.second,
this->Cell_default,
true, true
);
return *this;
}
BARRAY_TEMPLATE(BARRAY_TYPE() &, operator-=) (
const std::pair<uint,uint> & coords
) {
this->rm_cell(
coords.first,
coords.second,
true, true
);
return *this;
}
template BARRAY_TEMPLATE_ARGS()
inline BArrayCell<Cell_Type,Data_Type> BARRAY_TYPE()::operator()(
uint i,
uint j,
bool check_bounds
) {
return BArrayCell<Cell_Type,Data_Type>(this, i, j, check_bounds);
}
template BARRAY_TEMPLATE_ARGS()
inline const BArrayCell_const<Cell_Type,Data_Type> BARRAY_TYPE()::operator() (
uint i,
uint j,
bool check_bounds
) const {
return BArrayCell_const<Cell_Type,Data_Type>(this, i, j, check_bounds);
}
BARRAY_TEMPLATE(void, rm_cell) (
uint i,
uint j,
bool check_bounds,
bool check_exists
) {
// Checking the boundaries
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Nothing to do
if (ROW(i).size() == 0u)
return;
// Checking the counter part
if (COL(j).size() == 0u)
return;
// Hard work, need to remove it from both, if it exist
if (ROW(i).find(j) == ROW(i).end())
return;
}
// Remove the pointer first (so it wont point to empty)
COL(j).erase(i);
ROW(i).erase(j);
NCells--;
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
const Cell< Cell_Type> & v,
bool check_bounds,
bool check_exists
) {
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Checking if nothing here, then we move along
if (ROW(i).size() == 0u) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
return;
}
// In this case, the row exists, but we are checking that the value is empty
if (ROW(i).find(j) == ROW(i).end()) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
} else {
throw std::logic_error("The cell already exists.");
}
} else {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
}
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
Cell< Cell_Type> && v,
bool check_bounds,
bool check_exists
) {
if (check_bounds)
out_of_range(i,j);
if (check_exists) {
// Checking if nothing here, then we move along
if (ROW(i).size() == 0u) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
return;
}
// In this case, the row exists, but we are checking that the value is empty
if (ROW(i).find(j) == ROW(i).end()) {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
} else {
throw std::logic_error("The cell already exists.");
}
} else {
ROW(i).insert(std::pair< uint, Cell<Cell_Type>>(j, v));
COL(j).emplace(i, &ROW(i)[j]);
NCells++;
}
return;
}
BARRAY_TEMPLATE(void, insert_cell) (
uint i,
uint j,
Cell_Type v,
bool check_bounds,
bool check_exists
) {
return insert_cell(i, j, Cell<Cell_Type>(v, visited), check_bounds, check_exists);
}
BARRAY_TEMPLATE(void, swap_cells) (
uint i0, uint j0,
uint i1, uint j1,
bool check_bounds,
int check_exists,
int * report
) {
if (check_bounds) {
out_of_range(i0,j0);
out_of_range(i1,j1);
}
// Simplest case, we know both exists, so we don't need to check anything
if (check_exists == CHECK::NONE)
{
// Just in case, if this was passed
if (report != nullptr)
(*report) = EXISTS::BOTH;
// If source and target coincide, we do nothing
if ((i0 == i1) && (j0 == j1))
return;
// Using the initializing by move, after this, the cell becomes
// invalid. We use pointers instead as this way we access the Heap memory,
// which should be faster to access.
Cell<Cell_Type> c0(std::move(ROW(i0)[j0]));
rm_cell(i0, j0, false, false);
Cell<Cell_Type> c1(std::move(ROW(i1)[j1]));
rm_cell(i1, j1, false, false);
// Inserting the cells by reference, these will be deleted afterwards
insert_cell(i0, j0, c1, false, false);
insert_cell(i1, j1, c0, false, false);
return;
}
bool check0, check1;
if (check_exists == CHECK::BOTH)
{
check0 = !is_empty(i0, j0, false);
check1 = !is_empty(i1, j1, false);
} else if (check_exists == CHECK::ONE) {
check0 = !is_empty(i0, j0, false);
check1 = true;
} else if (check_exists == CHECK::TWO) {
check0 = true;
check1 = !is_empty(i1, j1, false);
}
if (report != nullptr)
(*report) = EXISTS::NONE;
// If both cells exists
if (check0 & check1)
{
if (report != nullptr)
(*report) = EXISTS::BOTH;
// If source and target coincide, we do nothing
if ((i0 == i1) && (j0 == j1))
return;
Cell<Cell_Type> c0(std::move(ROW(i0)[j0]));
rm_cell(i0, j0, false, false);
Cell<Cell_Type> c1(std::move(ROW(i1)[j1]));
rm_cell(i1, j1, false, false);
insert_cell(i0, j0, c1, false, false);
insert_cell(i1, j1, c0, false, false);
} else if (!check0 & check1) { // If only the second exists
if (report != nullptr)
(*report) = EXISTS::TWO;
insert_cell(i0, j0, ROW(i1)[j1], false, false);
rm_cell(i1, j1, false, false);
} else if (check0 & !check1) {
if (report != nullptr)
(*report) = EXISTS::ONE;
insert_cell(i1, j1, ROW(i0)[j0], false, false);
rm_cell(i0, j0, false, false);
}
return;
}
BARRAY_TEMPLATE(void, toggle_cell) (
uint i,
uint j,
bool check_bounds,
int check_exists
) {
if (check_bounds)
out_of_range(i, j);
if (check_exists == EXISTS::UKNOWN) {
if (is_empty(i, j, false)) {
insert_cell(i, j, BArray<Cell_Type, Data_Type>::Cell_default, false, false);
ROW(i)[j].visited = visited;
} else
rm_cell(i, j, false, false);
} else if (check_exists == EXISTS::AS_ONE) {
rm_cell(i, j, false, false);
} else if (check_exists == EXISTS::AS_ZERO) {
insert_cell(i, j, BArray<Cell_Type,Data_Type>::Cell_default, false, false);
ROW(i)[j].visited = visited;
}
return;
}
BARRAY_TEMPLATE(void, swap_rows) (
uint i0,
uint i1,
bool check_bounds
) {
if (check_bounds) {
out_of_range(i0,0u);
out_of_range(i1,0u);
}
bool move0=true, move1=true;
if (ROW(i0).size() == 0u) move0 = false;
if (ROW(i1).size() == 0u) move1 = false;
if (!move0 && !move1)
return;
// Swapping happens naturally, need to take care of the pointers
// though
ROW(i0).swap(ROW(i1));
// Delete the thing
if (move0)
for (auto& i: row(i1, false))
COL(i.first).erase(i0);
if (move1)
for (auto& i: row(i0, false))
COL(i.first).erase(i1);
// Now, point to the thing, if it has something to point at. Recall that
// the indices swapped.
if (move1)
for (auto& i: row(i0, false))
COL(i.first)[i0] = &ROW(i0)[i.first];
if (move0)
for (auto& i: row(i1, false))
COL(i.first)[i1] = &ROW(i1)[i.first];
return;
}
// This swapping is more expensive overall
BARRAY_TEMPLATE(void, swap_cols) (
uint j0,
uint j1,
bool check_bounds
) {
if (check_bounds) {
out_of_range(0u, j0);
out_of_range(0u, j1);
}
// Which ones need to be checked
bool check0 = true, check1 = true;
if (COL(j0).size() == 0u) check0 = false;
if (COL(j1).size() == 0u) check1 = false;
if (check0 && check1) {
// Just swapping one at a time
int status;
Col_type<Cell_Type> col_tmp = COL(j1);
Col_type<Cell_Type> col1 = COL(j0);
for (auto iter = col1.begin(); iter != col1.end(); ++iter) {
// Swapping values (col-wise)
swap_cells(iter->first, j0, iter->first, j1, false, CHECK::TWO, &status);
// Need to remove it, so we don't swap that as well
if (status == EXISTS::BOTH)
col_tmp.erase(iter->first);
}
// If there's anything left to move, we start moving it, otherwise, we just
// skip it
if (col_tmp.size() != 0u) {
for (auto iter = col_tmp.begin(); iter != col_tmp.end(); ++iter) {
insert_cell(iter->first, j0, *iter->second, false, false);
rm_cell(iter->first, j1);
}
}
} else if (check0 && !check1) {
// 1 is empty, so we just add new cells and remove the other ones
for (auto iter = COL(j0).begin(); iter != COL(j0).begin(); ++iter)
insert_cell(iter->first, j1, *iter->second, false, false);
// Setting the column to be zero
COL(j0).empty();
} else if (!check0 && check1) {
// 1 is empty, so we just add new cells and remove the other ones
for (auto iter = COL(j1).begin(); iter != COL(j1).begin(); ++iter) {
// Swapping values (col-wise)
insert_cell(iter->first, j0, *iter->second, false, false);
}
// Setting the column to be zero
COL(j1).empty();
}
return;
}
BARRAY_TEMPLATE(void, zero_row) (
uint i,
bool check_bounds
) {
if (check_bounds)
out_of_range(i, 0u);
// Nothing to do
if (ROW(i).size() == 0u)
return;
// Else, remove all elements
auto row0 = ROW(i);
for (auto row = row0.begin(); row != row0.end(); ++row)
rm_cell(i, row->first, false, false);
return;
}
BARRAY_TEMPLATE(void, zero_col) (
uint j,
bool check_bounds
) {
if (check_bounds)
out_of_range(0u, j);
// Nothing to do
if (COL(j).size() == 0u)
return;
// Else, remove all elements
auto col0 = COL(j);
for (auto col = col0.begin(); col != col0.end(); ++col)
rm_cell(col->first, j, false, false);
return;
}
BARRAY_TEMPLATE(void, transpose) () {
// Start by flipping the switch
visited = !visited;
// Do we need to resize (increase) either?
if (N > M) el_ji.resize(N);
else if (N < M) el_ij.resize(M);
// uint N0 = N, M0 = M;
int status;
for (uint i = 0u; i < N; ++i)
{
// Do we need to move anything?
if (ROW(i).size() == 0u)
continue;
// We now iterate changing rows
Row_type<Cell_Type> row = ROW(i);
for (auto col = row.begin(); col != row.end(); ++col)
{
// Skip if in the diagoal
if (i == col->first)
{
ROW(i)[i].visited = visited;
continue;
}
// We have not visited this yet, we need to change that
if (ROW(i)[col->first].visited != visited)
{
// First, swap the contents
swap_cells(i, col->first, col->first, i, false, CHECK::TWO, &status);
// Changing the switch
if (status == EXISTS::BOTH)
ROW(i)[col->first].visited = visited;
ROW(col->first)[i].visited = visited;
}
}
}
// Shreding. Note that no information should have been lost since, hence, no
// change in NCells.
if (N > M) el_ij.resize(M);
else if (N < M) el_ji.resize(N);
// Swapping the values
std::swap(N, M);
return;
}
BARRAY_TEMPLATE(void, clear) (
bool hard
) {
if (hard)
{
el_ji.clear();
el_ij.clear();
el_ij.resize(N);
el_ji.resize(M);
NCells = 0u;
} else {
for (unsigned int i = 0u; i < N; ++i)
zero_row(i, false);
}
return;
}
BARRAY_TEMPLATE(void, resize) (
uint N_,
uint M_
) {
// Removing rows
if (N_ < N)
for (uint i = N_; i < N; ++i)
zero_row(i, false);
// Removing cols
if (M_ < M)
for (uint j = M_; j < M; ++j)
zero_col(j, false);
// Resizing will invalidate pointers and values out of range
if (M_ != M) {
el_ji.resize(M_);
M = M_;
}
if (N_ != N) {
el_ij.resize(N_);
N = N_;
}
return;
}
BARRAY_TEMPLATE(void, reserve) () {
#ifdef BARRAY_USE_UNORDERED_MAP
for (uint i = 0u; i < N; i++)
ROW(i).reserve(M);
for (uint i = 0u; i < M; i++)
COL(i).reserve(N);
#endif
return;
}
BARRAY_TEMPLATE(void, print) (
const char * fmt,
...
) const {
std::va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
for (uint i = 0u; i < N; ++i)
{
#ifdef BARRY_DEBUG_LEVEL
#if BARRY_DEBUG_LEVEL > 1
printf_barry("%s [%3i,]", BARRY_DEBUG_HEADER, i);
#endif
#else
printf_barry("[%3i,] ", i);
#endif
for (uint j = 0u; j < M; ++j) {
if (this->is_empty(i, j, false))
printf_barry(" . ");
else
printf_barry(" %.2f ", static_cast<double>(this->get_cell(i, j, false)));
}
printf_barry("\n");
}
return;
}
#undef ROW
#undef COL
#undef BARRAY_TYPE
#undef BARRAY_TEMPLATE_ARGS
#undef BARRAY_TEMPLATE
#endif
| 21.968215
| 113
| 0.506733
|
USCbiostats
|
287f82ec982f80d5bf005edffbe89f3e874bde45
| 5,060
|
cxx
|
C++
|
Charts/vtkContextActor.cxx
|
Lin1225/vtk_v5.10.0
|
b54ac74f4716572862365fbff28cd0ecb8d08c3d
|
[
"BSD-3-Clause"
] | 2
|
2020-01-07T20:50:53.000Z
|
2020-01-29T18:22:02.000Z
|
Charts/vtkContextActor.cxx
|
Armand0s/homemade_vtk
|
6bc7b595a4a7f86e8fa969d067360450fa4e0a6a
|
[
"BSD-3-Clause"
] | null | null | null |
Charts/vtkContextActor.cxx
|
Armand0s/homemade_vtk
|
6bc7b595a4a7f86e8fa969d067360450fa4e0a6a
|
[
"BSD-3-Clause"
] | 5
|
2015-03-23T21:13:19.000Z
|
2022-01-03T11:15:39.000Z
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkContextActor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkContextActor.h"
#include "vtkContext2D.h"
#include "vtkOpenGLContextDevice2D.h"
#include "vtkOpenGL2ContextDevice2D.h"
#include "vtkContextScene.h"
#include "vtkTransform2D.h"
#include "vtkViewport.h"
#include "vtkWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkObjectFactory.h"
vtkStandardNewMacro(vtkContextActor);
vtkCxxSetObjectMacro(vtkContextActor, Context, vtkContext2D);
vtkCxxSetObjectMacro(vtkContextActor, Scene, vtkContextScene);
//----------------------------------------------------------------------------
vtkContextActor::vtkContextActor()
{
this->Context = vtkContext2D::New();
this->Scene = vtkContextScene::New();
this->Initialized = false;
}
//----------------------------------------------------------------------------
// Destroy an actor2D.
vtkContextActor::~vtkContextActor()
{
if (this->Context)
{
this->Context->End();
this->Context->Delete();
this->Context = NULL;
}
if (this->Scene)
{
this->Scene->Delete();
this->Scene = NULL;
}
}
//----------------------------------------------------------------------------
void vtkContextActor::ReleaseGraphicsResources(vtkWindow *window)
{
vtkOpenGLContextDevice2D *device =
vtkOpenGLContextDevice2D::SafeDownCast(this->Context->GetDevice());
if (device)
{
device->ReleaseGraphicsResources(window);
}
if(this->Scene)
{
this->Scene->ReleaseGraphicsResources();
}
}
//----------------------------------------------------------------------------
// Renders an actor2D's property and then it's mapper.
int vtkContextActor::RenderOverlay(vtkViewport* viewport)
{
vtkDebugMacro(<< "vtkContextActor::RenderOverlay");
if (!this->Context)
{
vtkErrorMacro(<< "vtkContextActor::Render - No painter set");
return 0;
}
// Need to figure out how big the window is, taking into account tiling...
vtkWindow *window = viewport->GetVTKWindow();
int scale[2];
window->GetTileScale(scale);
int size[2];
size[0] = window->GetSize()[0];
size[1] = window->GetSize()[1];
int viewportInfo[4];
viewport->GetTiledSizeAndOrigin( &viewportInfo[0], &viewportInfo[1],
&viewportInfo[2], &viewportInfo[3] );
// The viewport is in normalized coordinates, and is the visible section of
// the scene.
vtkTransform2D* transform = this->Scene->GetTransform();
transform->Identity();
if (scale[0] > 1 || scale[1] > 1)
{
// Tiled display - work out the transform required
double *b = window->GetTileViewport();
int box[] = { vtkContext2D::FloatToInt(b[0] * size[0]),
vtkContext2D::FloatToInt(b[1] * size[1]),
vtkContext2D::FloatToInt(b[2] * size[0]),
vtkContext2D::FloatToInt(b[3] * size[1]) };
transform->Translate(-box[0], -box[1]);
if (this->Scene->GetScaleTiles())
{
transform->Scale(scale[0], scale[1]);
}
}
else if (viewportInfo[0] != size[0] || viewportInfo[1] != size[1] )
{
size[0]=viewportInfo[0];
size[1]=viewportInfo[1];
}
if (!this->Initialized)
{
this->Initialize(viewport);
}
// This is the entry point for all 2D rendering.
// First initialize the drawing device.
this->Context->GetDevice()->Begin(viewport);
this->Scene->SetGeometry(size);
this->Scene->Paint(this->Context);
this->Context->GetDevice()->End();
return 1;
}
//----------------------------------------------------------------------------
void vtkContextActor::Initialize(vtkViewport* viewport)
{
vtkContextDevice2D *device = NULL;
if (vtkOpenGL2ContextDevice2D::IsSupported(viewport))
{
vtkDebugMacro("Using OpenGL 2 for 2D rendering.")
device = vtkOpenGL2ContextDevice2D::New();
}
else
{
vtkDebugMacro("Using OpenGL 1 for 2D rendering.")
device = vtkOpenGLContextDevice2D::New();
}
if (device)
{
this->Context->Begin(device);
device->Delete();
this->Initialized = true;
}
else
{
// Failed
vtkErrorMacro("Error: failed to initialize the render device.")
}
}
//----------------------------------------------------------------------------
void vtkContextActor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Context: " << this->Context << "\n";
if (this->Context)
{
this->Context->PrintSelf(os, indent.GetNextIndent());
}
}
| 28.268156
| 78
| 0.588735
|
Lin1225
|
287f86cc257f7c6803d7226c36014d060a9e76fb
| 4,800
|
hxx
|
C++
|
src/bp/Config.hxx
|
nn6n/beng-proxy
|
2cf351da656de6fbace3048ee90a8a6a72f6165c
|
[
"BSD-2-Clause"
] | 1
|
2022-03-15T22:54:39.000Z
|
2022-03-15T22:54:39.000Z
|
src/bp/Config.hxx
|
nn6n/beng-proxy
|
2cf351da656de6fbace3048ee90a8a6a72f6165c
|
[
"BSD-2-Clause"
] | null | null | null |
src/bp/Config.hxx
|
nn6n/beng-proxy
|
2cf351da656de6fbace3048ee90a8a6a72f6165c
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "access_log/Config.hxx"
#include "ssl/Config.hxx"
#include "net/SocketConfig.hxx"
#include "spawn/Config.hxx"
#include <forward_list>
#include <chrono>
#include <stddef.h>
struct StringView;
/**
* Configuration.
*/
struct BpConfig {
struct Listener : SocketConfig {
std::string tag;
#ifdef HAVE_AVAHI
std::string zeroconf_service;
std::string zeroconf_interface;
#endif
/**
* If non-empty, then this listener has its own
* translation server(s) and doesn't use the global
* server.
*/
std::forward_list<AllocatedSocketAddress> translation_sockets;
enum class Handler {
TRANSLATION,
PROMETHEUS_EXPORTER,
} handler = Handler::TRANSLATION;
bool auth_alt_host = false;
bool ssl = false;
SslConfig ssl_config;
Listener() {
listen = 64;
tcp_defer_accept = 10;
}
explicit Listener(SocketAddress _address) noexcept
:SocketConfig(_address)
{
listen = 64;
tcp_defer_accept = 10;
}
#ifdef HAVE_AVAHI
/**
* @return the name of the interface where the
* Zeroconf service shall be published
*/
[[gnu::pure]]
const char *GetZeroconfInterface() const noexcept {
if (!zeroconf_interface.empty())
return zeroconf_interface.c_str();
if (!interface.empty())
return interface.c_str();
return nullptr;
}
#endif
};
std::forward_list<Listener> listen;
AccessLogConfig access_log;
AccessLogConfig child_error_log;
std::string session_cookie = "beng_proxy_session";
std::chrono::seconds session_idle_timeout = std::chrono::minutes(30);
std::string session_save_path;
struct ControlListener : SocketConfig {
ControlListener() {
pass_cred = true;
}
explicit ControlListener(SocketAddress _bind_address)
:SocketConfig(_bind_address) {
pass_cred = true;
}
};
std::forward_list<ControlListener> control_listen;
std::forward_list<AllocatedSocketAddress> translation_sockets;
/** maximum number of simultaneous connections */
unsigned max_connections = 32768;
size_t http_cache_size = 512 * 1024 * 1024;
size_t filter_cache_size = 128 * 1024 * 1024;
size_t nfs_cache_size = 256 * 1024 * 1024;
unsigned translate_cache_size = 131072;
unsigned translate_stock_limit = 32;
unsigned tcp_stock_limit = 0;
unsigned lhttp_stock_limit = 0, lhttp_stock_max_idle = 8;
unsigned fcgi_stock_limit = 0, fcgi_stock_max_idle = 8;
unsigned was_stock_limit = 0, was_stock_max_idle = 16;
unsigned multi_was_stock_limit = 0, multi_was_stock_max_idle = 16;
unsigned remote_was_stock_limit = 0, remote_was_stock_max_idle = 16;
unsigned cluster_size = 0, cluster_node = 0;
enum class SessionCookieSameSite : uint8_t {
NONE,
STRICT,
LAX,
} session_cookie_same_site;
bool dynamic_session_cookie = false;
bool verbose_response = false;
bool emulate_mod_auth_easy = false;
bool http_cache_obey_no_cache = true;
SpawnConfig spawn;
SslClientConfig ssl_client;
BpConfig() {
#ifdef HAVE_LIBSYSTEMD
spawn.systemd_scope = "bp-spawn.scope";
spawn.systemd_scope_description = "The cm4all-beng-proxy child process spawner";
spawn.systemd_slice = "system-cm4all.slice";
#endif
}
void HandleSet(StringView name, const char *value);
void Finish(unsigned default_port);
};
/**
* Load and parse the specified configuration file. Throws an
* exception on error.
*/
void
LoadConfigFile(BpConfig &config, const char *path);
| 24.742268
| 82
| 0.74375
|
nn6n
|
2880119cd99ce85a00042ad784d2634da983d136
| 3,381
|
cpp
|
C++
|
MidiBlocksPlugins/ChordBankBlock/chordbankblock.cpp
|
millerthegorilla/midi-blocks
|
b7fc0c49b93b5d9cdd39358bfa6974fd2d0df7ac
|
[
"MIT"
] | null | null | null |
MidiBlocksPlugins/ChordBankBlock/chordbankblock.cpp
|
millerthegorilla/midi-blocks
|
b7fc0c49b93b5d9cdd39358bfa6974fd2d0df7ac
|
[
"MIT"
] | null | null | null |
MidiBlocksPlugins/ChordBankBlock/chordbankblock.cpp
|
millerthegorilla/midi-blocks
|
b7fc0c49b93b5d9cdd39358bfa6974fd2d0df7ac
|
[
"MIT"
] | null | null | null |
/*
Copyright (C) 2013 Adam Nash
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "chordbankblock.h"
#include "ui_chordbankblockeditor.h"
#include "chorditemdelegate.h"
#include <QDebug>
ChordBankBlock::ChordBankBlock(QObject *parent) :
editorUi(new Ui::ChordBankBlockEditor)
{
if (parent)
{
setParent(parent);
}
editor = new QWidget();
editorUi->setupUi(editor);
editorUi->tv_chords->setModel(&m_model);
editorUi->tv_chords->setItemDelegateForColumn(0, new ChordItemDelegate(this));
editorUi->verticalLayout->insertWidget(0, &m_chordEditor);
connect(editorUi->pb_add, SIGNAL(clicked()),
this, SLOT(addChord()));
connect(editorUi->pb_remove, SIGNAL(clicked()),
this, SLOT(removeChord()));
}
ChordBankBlock::~ChordBankBlock()
{
delete editorUi;
delete editor;
}
QString ChordBankBlock::getName()
{
return "Chord Bank Block";
}
QString ChordBankBlock::getGroupName()
{
return "Chord Blocks";
}
QWidget* ChordBankBlock::getEditorWidget()
{
return editor;
}
ControlBlock* ChordBankBlock::createDefaultBlock()
{
return new ChordBankBlock();
}
void ChordBankBlock::receiveBeat(QByteArray message)
{
Q_UNUSED(message)
//take off all previous notes
if (!m_notes.isEmpty())
{
foreach(QByteArray note, m_notes)
{
note[0] = 128;
sendChord(note);
}
m_notes.clear();
}
m_model.incrementBeat();
QList<QVariant> notes = m_model.getChordForBeat();
foreach(QVariant note, notes)
{
QByteArray noteOn;
noteOn.push_back(static_cast<char>(144));
noteOn.push_back(static_cast<char>(note.toInt()));
noteOn.push_back(static_cast<char>(100));
m_notes.push_back(noteOn);
sendChord(noteOn);
}
}
//void ChordBankBlock::receiveToggle_Write_Mode(QByteArray message)
//{
// //TODO: engage chord writing mode
//}
//void ChordBankBlock::receiveWrite_Input(QByteArray message)
//{
// //TODO: write the chord if in chord writing mode
//}
void ChordBankBlock::addChord()
{
if (m_model.insertRows(m_model.rowCount(QModelIndex()), 1, QModelIndex()))
{
m_model.setData(m_model.index(m_model.rowCount(QModelIndex())-1, 0),
m_chordEditor.getValues(),
Qt::EditRole);
}
}
void ChordBankBlock::removeChord()
{
foreach (QModelIndex index, editorUi->tv_chords->selectionModel()->selectedRows())
{
m_model.removeRows(index.row(), 1, QModelIndex());
}
}
Q_EXPORT_PLUGIN2(chordbankblockplugin, ChordBankBlock)
| 25.421053
| 87
| 0.645075
|
millerthegorilla
|
2884713e818f042a181b5f03563ddcc2d3315a69
| 1,652
|
cc
|
C++
|
garnet/lib/ui/gfx/tests/stereo_camera_unittest.cc
|
OpenTrustGroup/fuchsia
|
647e593ea661b8bf98dcad2096e20e8950b24a97
|
[
"BSD-3-Clause"
] | 1
|
2019-04-21T18:02:26.000Z
|
2019-04-21T18:02:26.000Z
|
garnet/lib/ui/gfx/tests/stereo_camera_unittest.cc
|
OpenTrustGroup/fuchsia
|
647e593ea661b8bf98dcad2096e20e8950b24a97
|
[
"BSD-3-Clause"
] | 16
|
2020-09-04T19:01:11.000Z
|
2021-05-28T03:23:09.000Z
|
garnet/lib/ui/gfx/tests/stereo_camera_unittest.cc
|
OpenTrustGroup/fuchsia
|
647e593ea661b8bf98dcad2096e20e8950b24a97
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2018 The Fuchsia 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 "garnet/lib/ui/gfx/resources/stereo_camera.h"
#include <lib/ui/scenic/cpp/commands.h>
#include <gtest/gtest.h>
#include "garnet/lib/ui/gfx/tests/session_test.h"
#include "src/ui/lib/escher/util/epsilon_compare.h"
#include <glm/gtc/type_ptr.hpp>
namespace scenic_impl {
namespace gfx {
namespace test {
using StereoCameraTest = SessionTest;
TEST_F(StereoCameraTest, Basic) {
constexpr ResourceId invalid_id = 0;
constexpr ResourceId scene_id = 1;
constexpr ResourceId camera_id = 2;
ASSERT_TRUE(Apply(scenic::NewCreateSceneCmd(scene_id)));
EXPECT_TRUE(Apply(scenic::NewCreateStereoCameraCmd(camera_id, scene_id)));
EXPECT_FALSE(Apply(scenic::NewCreateStereoCameraCmd(camera_id, invalid_id)));
// Not really projection matrices but we're just testing the setters
glm::mat4 left_projection = glm::mat4(2);
glm::mat4 right_projection = glm::mat4(3);
EXPECT_TRUE(Apply(scenic::NewSetStereoCameraProjectionCmd(
camera_id, glm::value_ptr(left_projection), glm::value_ptr(right_projection))));
auto camera = session()->resources()->FindResource<StereoCamera>(camera_id);
EXPECT_TRUE(camera);
EXPECT_TRUE(escher::CompareMatrix(left_projection,
camera->GetEscherCamera(StereoCamera::Eye::LEFT).projection()));
EXPECT_TRUE(escher::CompareMatrix(
right_projection, camera->GetEscherCamera(StereoCamera::Eye::RIGHT).projection()));
}
} // namespace test
} // namespace gfx
} // namespace scenic_impl
| 33.714286
| 100
| 0.746368
|
OpenTrustGroup
|
288511bf23e83f6efbf7f5bcf6be5bee633d6b90
| 8,823
|
cpp
|
C++
|
sources/Platform/Linux/LinuxWindow.cpp
|
NoFr1ends/LLGL
|
837fa70f151e2caeb1bd4122fcd4eb672080efa5
|
[
"BSD-3-Clause"
] | null | null | null |
sources/Platform/Linux/LinuxWindow.cpp
|
NoFr1ends/LLGL
|
837fa70f151e2caeb1bd4122fcd4eb672080efa5
|
[
"BSD-3-Clause"
] | null | null | null |
sources/Platform/Linux/LinuxWindow.cpp
|
NoFr1ends/LLGL
|
837fa70f151e2caeb1bd4122fcd4eb672080efa5
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* LinuxWindow.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <LLGL/Platform/NativeHandle.h>
#include <LLGL/Display.h>
#include "LinuxWindow.h"
#include "MapKey.h"
#include <exception>
namespace LLGL
{
static Offset2D GetScreenCenteredPosition(const Extent2D& size)
{
if (auto display = Display::InstantiatePrimary())
{
const auto resolution = display->GetDisplayMode().resolution;
return
{
static_cast<int>((resolution.width - size.width )/2),
static_cast<int>((resolution.height - size.height)/2),
};
}
return {};
}
std::unique_ptr<Window> Window::Create(const WindowDescriptor& desc)
{
return std::unique_ptr<Window>(new LinuxWindow(desc));
}
LinuxWindow::LinuxWindow(const WindowDescriptor& desc) :
desc_ { desc }
{
OpenWindow();
}
LinuxWindow::~LinuxWindow()
{
XDestroyWindow(display_, wnd_);
XCloseDisplay(display_);
}
void LinuxWindow::GetNativeHandle(void* nativeHandle) const
{
auto& handle = *reinterpret_cast<NativeHandle*>(nativeHandle);
handle.display = display_;
handle.window = wnd_;
handle.visual = visual_;
}
void LinuxWindow::ResetPixelFormat()
{
// dummy
}
Extent2D LinuxWindow::GetContentSize() const
{
/* Return the size of the client area */
return GetSize(true);
}
void LinuxWindow::SetPosition(const Offset2D& position)
{
/* Move window and store new position */
XMoveWindow(display_, wnd_, position.x, position.y);
desc_.position = position;
}
Offset2D LinuxWindow::GetPosition() const
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
return { attribs.x, attribs.y };
}
void LinuxWindow::SetSize(const Extent2D& size, bool useClientArea)
{
XResizeWindow(display_, wnd_, size.width, size.height);
}
Extent2D LinuxWindow::GetSize(bool useClientArea) const
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
return Extent2D
{
static_cast<std::uint32_t>(attribs.width),
static_cast<std::uint32_t>(attribs.height)
};
}
void LinuxWindow::SetTitle(const std::wstring& title)
{
/* Convert UTF16 to UTF8 string (X11 limitation) and set window title */
std::string s(title.begin(), title.end());
XStoreName(display_, wnd_, s.c_str());
}
std::wstring LinuxWindow::GetTitle() const
{
return std::wstring();
}
void LinuxWindow::Show(bool show)
{
if (show)
{
/* Map window and reset window position */
XMapWindow(display_, wnd_);
XMoveWindow(display_, wnd_, desc_.position.x, desc_.position.y);
}
else
XUnmapWindow(display_, wnd_);
if (desc_.borderless)
XSetInputFocus(display_, (show ? wnd_ : None), RevertToParent, CurrentTime);
}
bool LinuxWindow::IsShown() const
{
return false;
}
void LinuxWindow::SetDesc(const WindowDescriptor& desc)
{
//todo...
}
WindowDescriptor LinuxWindow::GetDesc() const
{
return desc_; //todo...
}
void LinuxWindow::OnProcessEvents()
{
XEvent event;
XPending(display_);
while (XQLength(display_))
{
XNextEvent(display_, &event);
switch (event.type)
{
case KeyPress:
ProcessKeyEvent(event.xkey, true);
break;
case KeyRelease:
ProcessKeyEvent(event.xkey, false);
break;
case ButtonPress:
ProcessMouseKeyEvent(event.xbutton, true);
break;
case ButtonRelease:
ProcessMouseKeyEvent(event.xbutton, false);
break;
case Expose:
ProcessExposeEvent();
break;
case MotionNotify:
ProcessMotionEvent(event.xmotion);
break;
case DestroyNotify:
PostQuit();
break;
case ClientMessage:
ProcessClientMessage(event.xclient);
break;
}
}
XFlush(display_);
}
/*
* ======= Private: =======
*/
void LinuxWindow::OpenWindow()
{
/* Get native context handle */
auto nativeHandle = reinterpret_cast<const NativeContextHandle*>(desc_.windowContext);
if (nativeHandle)
{
/* Get X11 display from context handle */
display_ = nativeHandle->display;
visual_ = nativeHandle->visual;
}
else
{
/* Open X11 display */
display_ = XOpenDisplay(nullptr);
visual_ = nullptr;
}
if (!display_)
throw std::runtime_error("failed to open X11 display");
/* Setup common parameters for window creation */
::Window rootWnd = (nativeHandle != nullptr ? nativeHandle->parentWindow : DefaultRootWindow(display_));
int screen = (nativeHandle != nullptr ? nativeHandle->screen : DefaultScreen(display_));
::Visual* visual = (nativeHandle != nullptr ? nativeHandle->visual->visual : DefaultVisual(display_, screen));
int depth = (nativeHandle != nullptr ? nativeHandle->visual->depth : DefaultDepth(display_, screen));
int borderSize = 0;
/* Setup window attributes */
XSetWindowAttributes attribs;
attribs.background_pixel = WhitePixel(display_, screen);
attribs.border_pixel = 0;
attribs.event_mask = (ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask);
unsigned long valueMask = CWEventMask | CWBorderPixel;//(CWColormap | CWEventMask | CWOverrideRedirect)
if (nativeHandle)
{
valueMask |= CWColormap;
attribs.colormap = nativeHandle->colorMap;
}
else
valueMask |= CWBackPixel;
if (desc_.borderless) //WARNING -> input no longer works
{
valueMask |= CWOverrideRedirect;
attribs.override_redirect = true;
}
/* Get final window position */
if (desc_.centered)
desc_.position = GetScreenCenteredPosition(desc_.size);
/* Create X11 window */
wnd_ = XCreateWindow(
display_,
rootWnd,
desc_.position.x,
desc_.position.y,
desc_.size.width,
desc_.size.height,
borderSize,
depth,
InputOutput,
visual,
valueMask,
(&attribs)
);
/* Set title and show window (if enabled) */
SetTitle(desc_.title);
/* Show window */
if (desc_.visible)
Show();
/* Prepare borderless window */
if (desc_.borderless)
{
XGrabKeyboard(display_, wnd_, True, GrabModeAsync, GrabModeAsync, CurrentTime);
XGrabPointer(display_, wnd_, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, wnd_, None, CurrentTime);
}
/* Enable WM_DELETE_WINDOW protocol */
closeWndAtom_ = XInternAtom(display_, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display_, wnd_, &closeWndAtom_, 1);
}
void LinuxWindow::ProcessKeyEvent(XKeyEvent& event, bool down)
{
auto key = MapKey(event);
if (down)
PostKeyDown(key);
else
PostKeyUp(key);
}
void LinuxWindow::ProcessMouseKeyEvent(XButtonEvent& event, bool down)
{
switch (event.button)
{
case Button1:
PostMouseKeyEvent(Key::LButton, down);
break;
case Button2:
PostMouseKeyEvent(Key::MButton, down);
break;
case Button3:
PostMouseKeyEvent(Key::RButton, down);
break;
case Button4:
PostWheelMotion(1);
break;
case Button5:
PostWheelMotion(-1);
break;
}
}
void LinuxWindow::ProcessExposeEvent()
{
XWindowAttributes attribs;
XGetWindowAttributes(display_, wnd_, &attribs);
const Extent2D size
{
static_cast<std::uint32_t>(attribs.width),
static_cast<std::uint32_t>(attribs.height)
};
PostResize(size);
}
void LinuxWindow::ProcessClientMessage(XClientMessageEvent& event)
{
Atom atom = static_cast<Atom>(event.data.l[0]);
if (atom == closeWndAtom_)
PostQuit();
}
void LinuxWindow::ProcessMotionEvent(XMotionEvent& event)
{
const Offset2D mousePos { event.x, event.y };
PostLocalMotion(mousePos);
PostGlobalMotion({ mousePos.x - prevMousePos_.x, mousePos.y - prevMousePos_.y });
prevMousePos_ = mousePos;
}
void LinuxWindow::PostMouseKeyEvent(Key key, bool down)
{
if (down)
PostKeyDown(key);
else
PostKeyUp(key);
}
} // /namespace LLGL
// ================================================================================
| 24.714286
| 139
| 0.613737
|
NoFr1ends
|
2885e7fa9c064cb4a5913f9b8f8db37177f0bb98
| 323
|
cpp
|
C++
|
src/kits/debugger/source_language/c_family/CppLanguage.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 1,338
|
2015-01-03T20:06:56.000Z
|
2022-03-26T13:49:54.000Z
|
src/kits/debugger/source_language/c_family/CppLanguage.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 15
|
2015-01-17T22:19:32.000Z
|
2021-12-20T12:35:00.000Z
|
src/kits/debugger/source_language/c_family/CppLanguage.cpp
|
Kirishikesan/haiku
|
835565c55830f2dab01e6e332cc7e2d9c015b51e
|
[
"MIT"
] | 350
|
2015-01-08T14:15:27.000Z
|
2022-03-21T18:14:35.000Z
|
/*
* Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
* Copyright 2012-2013, Rene Gollent, rene@gollent.com.
* Distributed under the terms of the MIT License.
*/
#include "CppLanguage.h"
CppLanguage::CppLanguage()
{
}
CppLanguage::~CppLanguage()
{
}
const char*
CppLanguage::Name() const
{
return "C++";
}
| 12.423077
| 55
| 0.690402
|
Kirishikesan
|
28860ae214f32e95d2218a6f6437461182ed6b67
| 872
|
cxx
|
C++
|
painty/core/test/src/KubelkaMunkTest.cxx
|
lindemeier/painty
|
792cac6655b3707805ffc68d902f0e675a7770b8
|
[
"MIT"
] | 15
|
2020-04-22T15:18:28.000Z
|
2022-03-24T07:48:28.000Z
|
painty/core/test/src/KubelkaMunkTest.cxx
|
lindemeier/painty
|
792cac6655b3707805ffc68d902f0e675a7770b8
|
[
"MIT"
] | 25
|
2020-04-18T18:55:50.000Z
|
2021-05-30T21:26:39.000Z
|
painty/core/test/src/KubelkaMunkTest.cxx
|
lindemeier/painty
|
792cac6655b3707805ffc68d902f0e675a7770b8
|
[
"MIT"
] | 2
|
2020-09-16T05:55:54.000Z
|
2021-01-09T12:09:43.000Z
|
/**
* @file KubelkaMunkTest.cxx
* @author thomas lindemeier
*
* @brief
*
* @date 2020-05-14
*
*/
#include "gtest/gtest.h"
#include "painty/core/KubelkaMunk.hxx"
TEST(KubelkaMunk, Reflectance) {
constexpr auto Eps = 0.00001;
const auto d = 0.5;
const painty::vec<double, 3U> k = {0.2, 0.1, 0.22};
const painty::vec<double, 3U> s = {0.124, 0.658, 0.123};
const painty::vec<double, 3U> r0 = {0.65, 0.2, 0.2146};
const auto r1 = painty::ComputeReflectance(k, s, r0, d);
EXPECT_NEAR(r1[0], 0.541596, Eps);
EXPECT_NEAR(r1[1], 0.343822, Eps);
EXPECT_NEAR(r1[2], 0.206651, Eps);
EXPECT_NEAR(painty::ComputeReflectance(k, s, r0, 0.0)[0], r0[0], Eps);
const painty::vec<double, 3U> s2 = {0.0, 0.0, 0.0};
EXPECT_NEAR(painty::ComputeReflectance(k, s2, r0, d)[0], 0.53217499727638173,
Eps);
}
| 27.25
| 79
| 0.598624
|
lindemeier
|
2887edc208ada4e07f89e8459df6bc8b4032330b
| 6,198
|
cpp
|
C++
|
test/json2sql/enum_record_set.cpp
|
slotix/json2sql
|
bed76cad843a11dcee6d96b58ee6b4a84f4f67a3
|
[
"BSD-3-Clause"
] | 8
|
2018-03-05T04:14:44.000Z
|
2021-12-22T03:18:16.000Z
|
test/json2sql/enum_record_set.cpp
|
slotix/json2sql
|
bed76cad843a11dcee6d96b58ee6b4a84f4f67a3
|
[
"BSD-3-Clause"
] | 10
|
2018-02-23T22:09:07.000Z
|
2019-06-06T17:29:26.000Z
|
test/json2sql/enum_record_set.cpp
|
slotix/json2sql
|
bed76cad843a11dcee6d96b58ee6b4a84f4f67a3
|
[
"BSD-3-Clause"
] | 7
|
2018-04-06T00:16:43.000Z
|
2020-06-26T13:32:47.000Z
|
//
// Created by sn0w1eo on 26.02.18.
//
#include <gtest/gtest.h>
#include <hash_table.hpp>
#include <enum_table.hpp>
#include "enum_record_set.hpp"
namespace {
using rapidjson::Value;
using namespace DBConvert::Structures;
class EnumRecordSetTest : public ::testing::Test {
protected:
void SetUp() {
any_value_ptr = new Value;
any_value_ptr->SetString("Any Value");
any_value_ptr2 = new Value;
any_value_ptr2->SetDouble(42.42);
parent_title = new Value;
parent_title->SetString("Parent Table");
child_title = new Value;
child_title->SetString("Child Table");
parent_table = new EnumTable(1, parent_title, 0, nullptr);
child_table = new EnumTable(2, child_title, 0, parent_table);
parent_rs = parent_table->get_record_set();
child_rs = child_table->get_record_set();
}
void TearDown() {
parent_rs = nullptr;
child_rs = nullptr;
delete parent_table;
delete child_table;
delete parent_title;
delete child_title;
delete any_value_ptr;
delete any_value_ptr2;
}
Value * parent_title;
Value * child_title;
Table * parent_table;
Table * child_table;
RecordSet * parent_rs;
RecordSet * child_rs;
Value * any_value_ptr;
Value * any_value_ptr2;
};
TEST_F(EnumRecordSetTest, CtorOwnerTableNullException) {
try {
EnumRecordSet ers(nullptr);
FAIL();
} catch (const ERROR_CODES & err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_Ctor_OwnerTableUndefined);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackIdFieldInCtorAsFirstElement) {
EnumRecordSet ers(parent_table);
EXPECT_TRUE( strcmp(ers.get_fields()->at(0)->get_title(), COLUMN_TITLES::PRIMARY_KEY_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackRefIdFieldAsSecondElementIfParentExists) { ;
EnumRecordSet ers(child_table);
EXPECT_TRUE( strcmp(ers.get_fields()->at(1)->get_title(), COLUMN_TITLES::REFERENCE_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackEnumFieldAsThirdElementIfParentExists) {
EnumRecordSet child_rs(child_table);
EXPECT_TRUE( strcmp(child_rs.get_fields()->at(2)->get_title(), COLUMN_TITLES::ENUM_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, CtorCreatesAndPushesBackEnumFieldAsSecondElementIfNoParent) {
EnumRecordSet parent_rs(parent_table);
EXPECT_TRUE( strcmp(parent_rs.get_fields()->at(1)->get_title(), COLUMN_TITLES::ENUM_FIELD) == 0 );
}
TEST_F(EnumRecordSetTest, AddRecordNullValuePtrException) {
try {
parent_rs->add_record(nullptr);
FAIL();
} catch (const ERROR_CODES err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_AddRecord_ValueUndefined);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, AddRecordIncreaseCurrentIdEachTime) {
parent_rs->add_record(any_value_ptr);
EXPECT_EQ(parent_rs->get_current_id(), 1);
parent_rs->add_record(any_value_ptr2);
EXPECT_EQ(parent_rs->get_current_id(), 2);
EXPECT_EQ(parent_rs->get_records()->size(), 2);
}
TEST_F(EnumRecordSetTest, AddRecordAddsNewRecordWithIdAndValueInEnumField) {
Field * id_field = parent_rs->get_fields()->at(0);
Field * enum_field = parent_rs->get_fields()->at(1); // if ParentTable exists enum_field will be ->at(2) otherwise ->at(1)
parent_rs->add_record(any_value_ptr);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(id_field)->GetInt64(), 1);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(enum_field), any_value_ptr);
parent_rs->add_record(any_value_ptr2);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(id_field)->GetInt64(), 2);
EXPECT_EQ(parent_rs->get_records()->back()->get_value(enum_field), any_value_ptr2);
}
TEST_F(EnumRecordSetTest, AddRecordAddsNewRecordWithIdRefIfParentTableExists) {
parent_rs->add_record(any_value_ptr);
child_rs->add_record(any_value_ptr2);
Field * child_ref_id_field = child_rs->get_fields()->at(1);
uint64_t parent_current_id = parent_rs->get_current_id();
uint64_t child_ref_id = child_rs->get_records()->back()->get_value(child_ref_id_field)->GetUint64();
EXPECT_EQ(child_ref_id, parent_current_id);
}
TEST_F(EnumRecordSetTest, AddRecordExceptionIfParentExistsButParentCurrentIdRecordIsZero) {
try{
child_rs->add_record(any_value_ptr);
FAIL();
} catch(const ERROR_CODES & err) {
EXPECT_EQ(err, ERROR_CODES::EnumRecordSet_AddRecord_ParentTableCurrentIdRecordIsZero);
} catch(...) {
FAIL();
}
}
TEST_F(EnumRecordSetTest, AddRecordUpdatesEnumField) {
Field * enum_field = parent_rs->get_fields()->at(1); // 1 if parent table, 2 child if child table
EXPECT_EQ(enum_field->get_length(), 0);
Value v1; v1.SetInt(12); // length is sizeof(uint32_t)
parent_rs->add_record(&v1);
EXPECT_EQ(enum_field->get_length(), sizeof(uint32_t));
Value v2; v2.SetString("123456789"); // length is 9
parent_rs->add_record(&v2);
EXPECT_EQ(enum_field->get_length(), strlen(v2.GetString()));
}
TEST_F(EnumRecordSetTest, AddNullRecordAddsValueSetNullToRecords) {
Field * enum_field = parent_rs->get_fields()->at(1); // 1 if parent table, 2 child if child table
parent_rs->add_null_record();
Record * added_record = parent_rs->get_records()->back();
EXPECT_TRUE( added_record->get_value(enum_field)->IsNull() );
parent_rs->add_null_record();
added_record = parent_rs->get_records()->back();
EXPECT_TRUE( added_record->get_value(enum_field)->IsNull() );
EXPECT_EQ( parent_rs->get_records()->size(), 2);
}
}
| 38.496894
| 132
| 0.647306
|
slotix
|
288bc24fb2022d139bf8d20be6b86508c0df0c25
| 12,073
|
cc
|
C++
|
src/rm/RequestManagerVirtualRouter.cc
|
vidister/one
|
3baad262f81694eb182f9accb5dd576f5596f3b0
|
[
"Apache-2.0"
] | 1
|
2019-11-21T09:33:40.000Z
|
2019-11-21T09:33:40.000Z
|
src/rm/RequestManagerVirtualRouter.cc
|
vidister/one
|
3baad262f81694eb182f9accb5dd576f5596f3b0
|
[
"Apache-2.0"
] | null | null | null |
src/rm/RequestManagerVirtualRouter.cc
|
vidister/one
|
3baad262f81694eb182f9accb5dd576f5596f3b0
|
[
"Apache-2.0"
] | 2
|
2020-03-09T09:11:41.000Z
|
2020-04-01T13:38:20.000Z
|
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "RequestManagerVirtualRouter.h"
#include "RequestManagerVMTemplate.h"
#include "RequestManagerVirtualMachine.h"
#include "PoolObjectAuth.h"
#include "Nebula.h"
#include "DispatchManager.h"
#include "VirtualRouterPool.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
RequestManagerVirtualRouter::RequestManagerVirtualRouter(const string& method_name,
const string& help,
const string& params)
: Request(method_name, params, help)
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
auth_op = AuthRequest::MANAGE;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterInstantiate::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
int n_vms = xmlrpc_c::value_int(paramList.getInt(2));
int tmpl_id = xmlrpc_c::value_int(paramList.getInt(3));
string name = xmlrpc_c::value_string(paramList.getString(4));
bool on_hold = xmlrpc_c::value_boolean(paramList.getBoolean(5));
string str_uattrs = xmlrpc_c::value_string(paramList.getString(6));
Nebula& nd = Nebula::instance();
VirtualRouterPool* vrpool = nd.get_vrouterpool();
VirtualRouter * vr;
DispatchManager* dm = nd.get_dm();
VMTemplatePool* tpool = nd.get_tpool();
PoolObjectAuth vr_perms;
Template* extra_attrs;
string error;
string vr_name, tmp_name;
ostringstream oss;
vector<int> vms;
vector<int>::iterator vmid;
int vid;
/* ---------------------------------------------------------------------- */
/* Get the Virtual Router NICs */
/* ---------------------------------------------------------------------- */
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
extra_attrs = vr->get_vm_template();
vr_name = vr->get_name();
if (tmpl_id == -1)
{
tmpl_id = vr->get_template_id();
}
vr->unlock();
if (tmpl_id == -1)
{
att.resp_msg = "A template ID was not provided, and the virtual router "
"does not have a default one";
failure_response(ACTION, att);
return;
}
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
VMTemplate * tmpl = tpool->get_ro(tmpl_id);
if ( tmpl == 0 )
{
att.resp_id = tmpl_id;
att.resp_obj = PoolObjectSQL::TEMPLATE;
failure_response(NO_EXISTS, att);
return;
}
bool is_vrouter = tmpl->is_vrouter();
tmpl->unlock();
if (!is_vrouter)
{
att.resp_msg = "Only virtual router templates are allowed";
failure_response(ACTION, att);
return;
}
if (name.empty())
{
name = "vr-" + vr_name + "-%i";
}
VMTemplateInstantiate tmpl_instantiate;
for (int i=0; i<n_vms; oss.str(""), i++)
{
oss << i;
tmp_name = one_util::gsub(name, "%i", oss.str());
ErrorCode ec = tmpl_instantiate.request_execute(tmpl_id, tmp_name,
true, str_uattrs, extra_attrs, vid, att);
if (ec != SUCCESS)
{
failure_response(ec, att);
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
dm->delete_vm(*vmid, att, att.resp_msg);
}
return;
}
vms.push_back(vid);
}
vr = vrpool->get(vrid);
if (vr != 0)
{
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
vr->add_vmid(*vmid);
}
vr->set_template_id(tmpl_id);
vrpool->update(vr);
vr->unlock();
}
// VMs are created on hold to wait for all of them to be created
// successfully, to avoid the rollback dm->finalize call on prolog
if (!on_hold)
{
for (vmid = vms.begin(); vmid != vms.end(); vmid++)
{
dm->release(*vmid, att, att.resp_msg);
}
}
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterAttachNic::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
VirtualRouterPool* vrpool = static_cast<VirtualRouterPool*>(pool);
VirtualRouter * vr;
VectorAttribute* nic;
VectorAttribute* nic_bck;
VirtualMachineTemplate tmpl;
PoolObjectAuth vr_perms;
int rc;
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
string str_tmpl = xmlrpc_c::value_string(paramList.getString(2));
// -------------------------------------------------------------------------
// Parse NIC template
// -------------------------------------------------------------------------
rc = tmpl.parse_str_or_xml(str_tmpl, att.resp_msg);
if ( rc != 0 )
{
failure_response(INTERNAL, att);
return;
}
// -------------------------------------------------------------------------
// Authorize the operation & check quotas
// -------------------------------------------------------------------------
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
vr->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
VirtualRouter::set_auth_request(att.uid, ar, &tmpl, true); // USE VNET
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
RequestAttributes att_quota(vr_perms.uid, vr_perms.gid, att);
if ( quota_authorization(&tmpl, Quotas::VIRTUALROUTER, att_quota) == false )
{
return;
}
// -------------------------------------------------------------------------
// Attach NIC to the Virtual Router
// -------------------------------------------------------------------------
vr = vrpool->get(vrid);
if (vr == 0)
{
quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
nic = vr->attach_nic(&tmpl, att.resp_msg);
if ( nic != 0 )
{
nic_bck = nic->clone();
}
set<int> vms = vr->get_vms();
vrpool->update(vr);
vr->unlock();
if (nic == 0)
{
quota_rollback(&tmpl, Quotas::VIRTUALROUTER, att_quota);
failure_response(ACTION, att);
return;
}
// -------------------------------------------------------------------------
// Attach NIC to each VM
// -------------------------------------------------------------------------
VirtualMachineAttachNic vm_attach_nic;
for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
{
VirtualMachineTemplate tmpl;
tmpl.set(nic_bck->clone());
ErrorCode ec = vm_attach_nic.request_execute(*vmid, tmpl, att);
if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
{
delete nic_bck;
failure_response(ACTION, att);
return;
}
}
delete nic_bck;
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VirtualRouterDetachNic::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
VirtualRouterPool* vrpool = static_cast<VirtualRouterPool*>(pool);
VirtualRouter * vr;
PoolObjectAuth vr_perms;
int rc;
int vrid = xmlrpc_c::value_int(paramList.getInt(1));
int nic_id = xmlrpc_c::value_int(paramList.getInt(2));
// -------------------------------------------------------------------------
// Authorize the operation
// -------------------------------------------------------------------------
vr = vrpool->get_ro(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
vr->get_permissions(vr_perms);
vr->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(AuthRequest::MANAGE, vr_perms); // MANAGE VROUTER
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
failure_response(AUTHORIZATION, att);
return;
}
// -------------------------------------------------------------------------
// Detach the NIC from the Virtual Router
// -------------------------------------------------------------------------
vr = vrpool->get(vrid);
if (vr == 0)
{
att.resp_id = vrid;
failure_response(NO_EXISTS, att);
return;
}
rc = vr->detach_nic(nic_id);
set<int> vms = vr->get_vms();
vrpool->update(vr);
vr->unlock();
if (rc != 0)
{
ostringstream oss;
oss << "NIC with NIC_ID " << nic_id << " does not exist.";
att.resp_msg = oss.str();
failure_response(Request::ACTION, att);
return;
}
// -------------------------------------------------------------------------
// Detach NIC from each VM
// -------------------------------------------------------------------------
VirtualMachineDetachNic vm_detach_nic;
for (set<int>::iterator vmid = vms.begin(); vmid != vms.end(); vmid++)
{
ErrorCode ec = vm_detach_nic.request_execute(*vmid, nic_id, att);
if (ec != SUCCESS) //TODO: manage individual attach error, do rollback?
{
failure_response(Request::ACTION, att);
return;
}
}
success_response(vrid, att);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
| 28.745238
| 83
| 0.455562
|
vidister
|
288cfffdcaf3e3d50d5fe581c917ddd589663956
| 2,955
|
cpp
|
C++
|
Engine/databaseadmincsvformat.cpp
|
vadkasevas/BAS
|
657f62794451c564c77d6f92b2afa9f5daf2f517
|
[
"MIT"
] | 302
|
2016-05-20T12:55:23.000Z
|
2022-03-29T02:26:14.000Z
|
Engine/databaseadmincsvformat.cpp
|
chulakshana/BAS
|
955f5a41bd004bcdd7d19725df6ab229b911c09f
|
[
"MIT"
] | 9
|
2016-07-21T09:04:50.000Z
|
2021-05-16T07:34:42.000Z
|
Engine/databaseadmincsvformat.cpp
|
chulakshana/BAS
|
955f5a41bd004bcdd7d19725df6ab229b911c09f
|
[
"MIT"
] | 113
|
2016-05-18T07:48:37.000Z
|
2022-02-26T12:59:39.000Z
|
#include "databaseadmincsvformat.h"
#include "ui_databaseadmincsvformat.h"
#include <QDir>
#include <QFileDialog>
#include <QDebug>
DatabaseAdminCsvFormat::DatabaseAdminCsvFormat(QWidget *parent) :
QDialog(parent),
ui(new Ui::DatabaseAdminCsvFormat)
{
ui->setupUi(this);
connect(ui->DragSectionCombo,SIGNAL(ChangedDragSection()),this,SLOT(ChangedDragSection()));
IsExport = true;
ui->LabelValidation->setVisible(false);
IsCsv = true;
}
QString DatabaseAdminCsvFormat::GetExtension()
{
return (IsCsv)?".csv":".xls";
}
void DatabaseAdminCsvFormat::SetXls()
{
IsCsv = false;
setWindowTitle("Xls");
}
QString DatabaseAdminCsvFormat::GetFileName()
{
return ui->FileName->text();
}
void DatabaseAdminCsvFormat::SetIsExport(bool IsExport)
{
this->IsExport = IsExport;
if(IsExport)
{
QString randomString;
{
QString possibleCharacters("abcdefghijklmnopqrstuvwxyz");
int randomStringLength = 10;
for(int i=0; i<randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
}
ui->FileName->setText(QDir::cleanPath(QDir::currentPath() + QDir::separator() + randomString + GetExtension()));
}
}
void DatabaseAdminCsvFormat::ChangedDragSection()
{
QStringList res;
foreach(int i, ui->DragSectionCombo->SelectedItems())
{
res.append(Columns[i].Name);
}
ui->FormatResult->setText(res.join(":"));
}
void DatabaseAdminCsvFormat::SetDatabaseColumns(QList<DatabaseColumn> Columns)
{
this->Columns = Columns;
QStringList List;
QList<int> Items;
int index = 0;
foreach(DatabaseColumn Column, Columns)
{
List.append(Column.Description);
Items.append(index);
index++;
}
ui->DragSectionCombo->SetData(List,Items);
ChangedDragSection();
}
QList<int> DatabaseAdminCsvFormat::GetColumnIds()
{
QList<int> res;
foreach(int i, ui->DragSectionCombo->SelectedItems())
{
res.append(Columns[i].Id);
}
return res;
}
DatabaseAdminCsvFormat::~DatabaseAdminCsvFormat()
{
delete ui;
}
void DatabaseAdminCsvFormat::on_OpenFileButton_clicked()
{
QString fileName;
if(IsExport)
fileName = QFileDialog::getSaveFileName(this, tr("Save"), "", tr("Csv Files (*.csv);;All Files (*.*)"));
else
fileName = QFileDialog::getOpenFileName(this, tr("Save"), "", tr("All Files (*.*);;Csv Files (*.csv)"));
if(fileName.length()>0)
{
ui->FileName->setText(fileName);
}
}
void DatabaseAdminCsvFormat::on_Ok_clicked()
{
if (IsExport || QFile::exists(GetFileName()))
{
accept();
} else
{
ui->LabelValidation->setVisible(true);
}
}
void DatabaseAdminCsvFormat::on_Cancel_clicked()
{
reject();
}
| 21.727941
| 120
| 0.643316
|
vadkasevas
|
288dbd960d6e8f1e0ae0e8e9da6520c15f44affb
| 11,530
|
cpp
|
C++
|
src/VS/vlib/Hand.cpp
|
valet-bridge/valet
|
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
|
[
"Apache-2.0"
] | null | null | null |
src/VS/vlib/Hand.cpp
|
valet-bridge/valet
|
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
|
[
"Apache-2.0"
] | 1
|
2015-11-15T08:20:33.000Z
|
2018-03-04T09:48:23.000Z
|
src/VS/vlib/Hand.cpp
|
valet-bridge/valet
|
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
|
[
"Apache-2.0"
] | null | null | null |
/*
Valet, a generalized Butler scorer for bridge.
Copyright (C) 2015 by Soren Hein.
See LICENSE and README.
*/
#include "stdafx.h"
#include <assert.h>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "valet.h"
#include "Pairs.h"
#include "Hand.h"
#include "scoring.h"
extern OptionsType options;
extern Pairs pairs;
typedef int (*fptrType)(int rawScore);
fptrType fptr;
//////////////////////////////////////////////////
// //
// General functions for all types of scoring //
// //
//////////////////////////////////////////////////
Hand::Hand()
{
Hand::Reset();
}
Hand::~Hand()
{
}
void Hand::Reset()
{
boardNo = 0;
numEntries = 0;
results.resize(HAND_CHUNK_SIZE);
length = HAND_CHUNK_SIZE;
}
int Hand::SetBoardNumber(
const unsigned n)
{
if (boardNo > 0 && n != boardNo)
return RETURN_BOARD_NUMBER_CHANGE;
boardNo = n;
GetVul(boardNo, vulNS, vulEW);
return RETURN_NO_FAULT;
}
unsigned Hand::GetBoardNumber()
{
return boardNo;
}
unsigned Hand::GetNumEntries()
{
return numEntries;
}
void Hand::AddResult(
const ResultType& res)
{
assert(boardNo > 0);
if (numEntries == length)
{
length += 8;
results.resize(length);
}
results[numEntries++] = res;
}
void Hand::ResetValetEntry(
ValetEntryType& entry)
{
entry.pairNo = 0;
entry.oppNo = 0;
entry.declFlag[0] = false;
entry.declFlag[1] = false;
entry.defFlag = false;
entry.leadFlag[0] = false;
entry.leadFlag[1] = false;
entry.overall = 0.;
entry.bidScore = 0.;
entry.playScore[0] = 0.;
entry.playScore[1] = 0.;
entry.leadScore[0] = 0.;
entry.leadScore[1] = 0.;
entry.defScore = 0.;
}
const unsigned Hswap[2][2] = { {0, 1}, {1, 0} };
void Hand::SetPairSwaps(
const ResultType& res,
ValetEntryType& entry,
unsigned& decl,
unsigned& leader)
{
// This function takes care of assigning the scores to the right
// players within a pair. pairNo is negative if the players are
// internally stored in the opposite order to the one that happens
// to be at the table.
unsigned swapNS, swapEW;
int pairNoNS = pairs.GetPairNumber(res.north, res.south);
assert(pairNoNS != 0);
if (pairNoNS < 0)
{
entry.pairNo = static_cast<unsigned>(-pairNoNS);
swapNS = 1;
}
else
{
entry.pairNo = static_cast<unsigned>(pairNoNS);
swapNS = 0;
}
int pairNoEW = pairs.GetPairNumber(res.east, res.west);
assert(pairNoEW != 0);
if (pairNoEW < 0)
{
entry.oppNo = static_cast<unsigned>(-pairNoEW);
swapEW = 1;
}
else
{
entry.oppNo = static_cast<unsigned>(pairNoEW);
swapEW = 0;
}
if (res.declarer == VALET_NORTH || res.declarer == VALET_SOUTH)
{
decl = Hswap[swapNS][res.declarer == VALET_SOUTH];
leader = Hswap[swapEW][res.declarer == VALET_SOUTH];
}
else if (res.declarer == VALET_EAST || res.declarer == VALET_WEST)
{
decl = Hswap[swapEW][res.declarer == VALET_WEST];
leader = Hswap[swapNS][res.declarer == VALET_EAST];
}
else
{
decl = 0;
leader = 0;
assert(false);
}
}
void Hand::SetPassout(
const ResultType& res,
const float totalIMPs,
ValetEntryType& entry)
{
// Pass-out.
int pairNoNS = pairs.GetPairNumber(res.north, res.south);
assert(pairNoNS != 0);
if (pairNoNS < 0)
pairNoNS = -pairNoNS; // Doesn't matter for pass-out
int pairNoEW = pairs.GetPairNumber(res.east, res.west);
assert(pairNoEW != 0);
if (pairNoEW < 0)
pairNoEW = -pairNoEW; // Doesn't matter for pass-out
entry.pairNo = static_cast<unsigned>(pairNoNS);
entry.oppNo = static_cast<unsigned>(pairNoEW);
entry.overall = totalIMPs;
entry.bidScore = totalIMPs;
}
void Hand::SetPlayResult(
const ResultType& res,
const float totalIMPs,
const float bidIMPs,
const float leadIMPs,
ValetEntryType& entry)
{
unsigned decl, leader;
Hand::SetPairSwaps(res, entry, decl, leader);
// All IMPs are seen from NS's side up to here.
float sign = 1.f;
if (res.declarer == VALET_EAST || res.declarer == VALET_WEST)
{
sign = -1.f;
unsigned tmp = entry.pairNo;
entry.pairNo = entry.oppNo;
entry.oppNo = tmp;
}
entry.declFlag[decl] = true;
entry.defFlag = true;
entry.leadFlag[leader] = true;
entry.overall = sign * totalIMPs;
entry.bidScore = sign * bidIMPs;
entry.playScore[decl] = sign * (totalIMPs - bidIMPs);
if (options.leadFlag && res.leadRank > 0)
{
entry.leadScore[leader] = - sign * leadIMPs;
entry.defScore = sign * (bidIMPs - totalIMPs + leadIMPs);
}
else
entry.defScore = sign * (bidIMPs - totalIMPs);
}
//////////////////////////////////////////////////
// //
// Functions only for datum scoring (Butler) //
// //
//////////////////////////////////////////////////
int Hand::GetDatum(
const vector<int>& rawScore)
{
// Datum score (average), rounded to nearest 10.
// This is used for Butler scoring.
int datum = 0;
int dmin = 9999, dmax = -9999;
for (unsigned i = 0; i < numEntries; i++)
{
if (rawScore[i] < dmin)
dmin = rawScore[i];
if (rawScore[i] > dmax)
dmax = rawScore[i];
datum += rawScore[i];
}
if (options.datumFilter && numEntries > 2)
datum = (datum-dmin-dmax) / static_cast<int>(numEntries-2);
else
datum = datum / static_cast<int>(numEntries);
return datum;
}
float Hand::GetDatumBidding(
const ResultType& res,
const unsigned vul,
const unsigned resMatrix[5][14],
const int datum)
{
// This is used for Butler scoring.
// We calculate the IMPs (across-the-field style) for our own
// contract if we get an average declarer of our denomination
// (playing from our side), and we compare this to the datum.
// This gives us the bidding performance, in a way.
float bidIMPs = 0.;
unsigned count = 0;
unsigned d = res.denom;
for (unsigned t = 0; t <= 13; t++)
{
if (resMatrix[d][t] == 0)
continue;
int artifScore = CalculateRawScore(res, vul, t);
bidIMPs += resMatrix[d][t] *
static_cast<float>(CalculateIMPs(artifScore - datum));
count += resMatrix[d][t];
}
assert(count > 0);
return (bidIMPs / count);
}
//////////////////////////////////////////////////
// //
// Functions only for IAF scoring and MPs //
// //
//////////////////////////////////////////////////
float Hand::GetOverallScore(
const vector<int> rawScore,
const int score)
{
// For a given score, we calculate the average number of IMPs/MPs
// against all the other pairs. If we've seen the score before,
// we use a cached value.
map<int, float>::iterator it = scoreLookup.find(score);
if (it != scoreLookup.end())
return it->second;
float result = 0;
unsigned count = 0;
bool seenSelfFlag = false;
for (unsigned i = 0; i < numEntries; i++)
{
// Skip own score.
if (! seenSelfFlag && rawScore[i] == score)
{
seenSelfFlag = true;
continue;
}
result += static_cast<float>((*fptr)(score - rawScore[i]));
count++;
}
assert(count > 0);
return (scoreLookup[score] = result / count);
}
float Hand::GetBiddingScore(
const vector<int> rawScore,
const unsigned no,
const unsigned vul,
const unsigned resMatrix[5][14],
const float overallResult)
{
// This is analogous to GetDatumBidding for Butler scoring.
// We compare to all other scores, not to the datum.
float bidResult = 0.;
unsigned count = 0;
ResultType resArtif = results[no];
unsigned d = resArtif.denom;
for (unsigned t = 0; t <= 13; t++)
{
if (resMatrix[d][t] == 0)
continue;
// Make a synthetic result of our contract with different
// declarers (including ourselves, but that scores 0).
resArtif.tricks = t;
int artifScore = CalculateRawScore(resArtif, vul, t);
bidResult +=
resMatrix[d][t] * Hand::GetOverallScore(rawScore, artifScore);
count += resMatrix[d][t];
}
// Special case: If we're the only ones to play in a denomination,
// we somewhat arbitrarily assign the full score to the bidding.
if (count == 0)
return overallResult;
else
return bidResult / count;
}
//////////////////////////////////////////////////
// //
// General scoring function, uses above //
// //
//////////////////////////////////////////////////
vector<ValetEntryType> Hand::CalculateScores()
{
vector<int> rawScore(numEntries);
vector<unsigned> vulList(numEntries);
unsigned resDeclMatrix[4][5][14] = {0};
unsigned resDeclLeadMatrix[4][4][5][14] = {0};
for (unsigned i = 0; i < numEntries; i++)
{
unsigned decl = results[i].declarer;
unsigned denom = results[i].denom;
unsigned tricks = results[i].tricks;
vulList[i] = (decl == VALET_NORTH ||
decl == VALET_SOUTH ? vulNS : vulEW);
rawScore[i] = CalculateRawScore(results[i], vulList[i]);
resDeclMatrix[decl][denom][tricks]++;
if (options.leadFlag && results[i].leadRank > 0)
{
unsigned lead = results[i].leadDenom;
resDeclLeadMatrix[decl][lead][denom][tricks]++;
}
}
vector<ValetEntryType> entries(numEntries);
if (numEntries == 0)
return entries;
if (options.valet == VALET_IMPS)
{
int datum = Hand::GetDatum(rawScore);
float bidIMPs, bidLeadIMPs, leadIMPs = 0.f;
for (unsigned i = 0; i < numEntries; i++)
{
ValetEntryType& entry = entries[i];
Hand::ResetValetEntry(entry);
const ResultType& res = results[i];
float butlerIMPs = static_cast<float>(
CalculateIMPs(rawScore[i] - datum));
if (res.level == 0)
Hand::SetPassout(res, butlerIMPs, entry);
else
{
bidIMPs = GetDatumBidding(res, vulList[i],
resDeclMatrix[res.declarer], datum);
if (options.leadFlag && res.leadRank > 0)
{
bidLeadIMPs = GetDatumBidding(res, vulList[i],
resDeclLeadMatrix[res.declarer][res.leadDenom], datum);
leadIMPs = bidLeadIMPs - bidIMPs;
}
else
leadIMPs = 0.f;
Hand::SetPlayResult(res, butlerIMPs, bidIMPs, leadIMPs, entry);
}
}
}
else
{
if (options.valet == VALET_IMPS_ACROSS_FIELD)
fptr = &CalculateIMPs;
else if (options.valet == VALET_MATCHPOINTS)
fptr = &CalculateMPs;
else
assert(false);
scoreLookup.clear();
float bidIAF, bidLeadIAF, leadIAF = 0.f;
for (unsigned i = 0; i < numEntries; i++)
{
ValetEntryType& entry = entries[i];
Hand::ResetValetEntry(entry);
const ResultType& res = results[i];
float IAFs = Hand::GetOverallScore(rawScore, rawScore[i]);
if (res.level == 0)
Hand::SetPassout(res, IAFs, entry);
else
{
bidIAF = GetBiddingScore(rawScore, i, vulList[i],
resDeclMatrix[res.declarer], IAFs);
if (options.leadFlag && res.leadRank > 0)
{
bidLeadIAF = GetBiddingScore(rawScore, i, vulList[i],
resDeclLeadMatrix[res.declarer][res.leadDenom], IAFs);
leadIAF = bidLeadIAF - bidIAF;
}
else
leadIAF = 0.f;
Hand::SetPlayResult(res, IAFs, bidIAF, leadIAF, entry);
}
}
}
return entries;
}
| 23.06
| 71
| 0.590286
|
valet-bridge
|
288f0fa771c4bfca6b7fab038801fc88bed55bd2
| 2,603
|
hpp
|
C++
|
include/eve/module/math/diff/impl/hypot.hpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
include/eve/module/math/diff/impl/hypot.hpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
include/eve/module/math/diff/impl/hypot.hpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/module/core.hpp>
#include <eve/module/core.hpp>
#include <eve/module/math/regular/hypot.hpp>
#include <eve/module/math/pedantic/hypot.hpp>
namespace eve::detail
{
template<int N, typename T0, typename T1, typename... Ts>
auto hypot_(EVE_SUPPORTS(cpu_), diff_type<N>
, T0 arg0, T1 arg1, Ts... args) noexcept
{
using r_t = common_compatible_t<T0,T1, Ts...>;
if constexpr(N > sizeof...(Ts)+2)
{
return zero(as<r_t >());
}
else
{
auto h = hypot(arg0, arg1, args...);
if constexpr(N==1) return arg0/h;
else if constexpr(N==2) return arg1/h;
else
{
auto getNth = []<std::size_t... I>(std::index_sequence<I...>, auto& that, auto... vs)
{
auto iff = [&that]<std::size_t J>(auto val, std::integral_constant<std::size_t,J>)
{
if constexpr(J==N) that = val;
};
((iff(vs, std::integral_constant<std::size_t,I+3>{})),...);
};
r_t that(0);
getNth(std::make_index_sequence<sizeof...(args)>{},that,args...);
return that/h;
}
}
}
template<int N, typename T0, typename T1, typename... Ts>
auto hypot_(EVE_SUPPORTS(cpu_), decorated<diff_<N>(pedantic_)> const &
, T0 arg0, T1 arg1, Ts... args) noexcept
{
using r_t = common_compatible_t<T0,T1, Ts...>;
if constexpr(N > sizeof...(Ts)+2)
{
return zero(as<r_t >());
}
else
{
if constexpr(N > sizeof...(Ts)+2) return zero(as<r_t>());
else
{
auto h = pedantic(hypot)(arg0, arg1, args...);
if constexpr(N==1) return arg0/h;
else if constexpr(N==2) return arg1/h;
else
{
auto getNth = []<std::size_t... I>(std::index_sequence<I...>, auto& that, auto... vs)
{
auto iff = [&that]<std::size_t J>(auto val, std::integral_constant<std::size_t,J>)
{
if constexpr(J==N) that = val;
};
((iff(vs, std::integral_constant<std::size_t,I+3>{})),...);
};
r_t that(0);
getNth(std::make_index_sequence<sizeof...(args)>{},that,args...);
return that/h;
}
}
}
}
}
| 29.91954
| 100
| 0.48713
|
clayne
|
2890a085007d30e34ab174ff9d044ef698241adf
| 2,340
|
hpp
|
C++
|
include/range/v3/algorithm/copy.hpp
|
morinmorin/range-v3
|
d911614f40dcbc05062cd3a398007270c86b2d65
|
[
"MIT"
] | null | null | null |
include/range/v3/algorithm/copy.hpp
|
morinmorin/range-v3
|
d911614f40dcbc05062cd3a398007270c86b2d65
|
[
"MIT"
] | null | null | null |
include/range/v3/algorithm/copy.hpp
|
morinmorin/range-v3
|
d911614f40dcbc05062cd3a398007270c86b2d65
|
[
"MIT"
] | null | null | null |
/// \file
// Range v3 library
//
// Copyright Eric Niebler 2013-present
//
// Use, modification and distribution is subject to 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)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_ALGORITHM_COPY_HPP
#define RANGES_V3_ALGORITHM_COPY_HPP
#include <functional>
#include <utility>
#include <range/v3/range_fwd.hpp>
#include <range/v3/algorithm/result_types.hpp>
#include <range/v3/iterator/concepts.hpp>
#include <range/v3/iterator/traits.hpp>
#include <range/v3/range/access.hpp>
#include <range/v3/range/concepts.hpp>
#include <range/v3/range/dangling.hpp>
#include <range/v3/range/traits.hpp>
#include <range/v3/utility/copy.hpp>
#include <range/v3/utility/static_const.hpp>
namespace ranges
{
/// \addtogroup group-algorithms
/// @{
template<typename I, typename O>
using copy_result = detail::in_out_result<I, O>;
struct cpp20_copy_fn
{
template<typename I, typename S, typename O>
constexpr auto operator()(I begin, S end, O out) const
-> CPP_ret(copy_result<I, O>)( //
requires input_iterator<I> && sentinel_for<S, I> && weakly_incrementable<O> &&
indirectly_copyable<I, O>)
{
for(; begin != end; ++begin, ++out)
*out = *begin;
return {begin, out};
}
template<typename Rng, typename O>
constexpr auto operator()(Rng && rng, O out) const
-> CPP_ret(copy_result<safe_iterator_t<Rng>, O>)( //
requires input_range<Rng> && weakly_incrementable<O> &&
indirectly_copyable<iterator_t<Rng>, O>)
{
return (*this)(begin(rng), end(rng), std::move(out));
}
};
struct RANGES_EMPTY_BASES copy_fn
: aux::copy_fn
, cpp20_copy_fn
{
using aux::copy_fn::operator();
using cpp20_copy_fn::operator();
};
/// \sa `copy_fn`
/// \ingroup group-algorithms
RANGES_INLINE_VARIABLE(copy_fn, copy)
namespace cpp20
{
using ranges::copy_result;
RANGES_INLINE_VARIABLE(cpp20_copy_fn, copy)
} // namespace cpp20
/// @}
} // namespace ranges
#endif // include guard
| 28.536585
| 94
| 0.631624
|
morinmorin
|
2891692a139096ff3c00c7d928507f9dadc410ae
| 1,338
|
cpp
|
C++
|
obs-studio/plugins/win-dshow/dshow-plugin.cpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
obs-studio/plugins/win-dshow/dshow-plugin.cpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
obs-studio/plugins/win-dshow/dshow-plugin.cpp
|
noelemahcz/libobspp
|
029472b973e5a1985f883242f249848385df83a3
|
[
"MIT"
] | null | null | null |
#include <obs-module.h>
#include <strsafe.h>
#include <strmif.h>
#include "virtualcam-guid.h"
OBS_DECLARE_MODULE()
OBS_MODULE_USE_DEFAULT_LOCALE("win-dshow", "en-US")
MODULE_EXPORT const char *obs_module_description(void)
{
return "Windows DirectShow source/encoder";
}
extern void RegisterDShowSource();
extern void RegisterDShowEncoders();
#ifdef VIRTUALCAM_ENABLED
extern "C" struct obs_output_info virtualcam_info;
static bool vcam_installed(bool b64)
{
wchar_t cls_str[CHARS_IN_GUID];
wchar_t temp[MAX_PATH];
HKEY key = nullptr;
StringFromGUID2(CLSID_OBS_VirtualVideo, cls_str, CHARS_IN_GUID);
StringCbPrintf(temp, sizeof(temp), L"CLSID\\%s", cls_str);
DWORD flags = KEY_READ;
flags |= b64 ? KEY_WOW64_64KEY : KEY_WOW64_32KEY;
LSTATUS status = RegOpenKeyExW(HKEY_CLASSES_ROOT, temp, 0, flags, &key);
if (status != ERROR_SUCCESS) {
return false;
}
RegCloseKey(key);
return true;
}
#endif
bool obs_module_load(void)
{
RegisterDShowSource();
RegisterDShowEncoders();
#ifdef VIRTUALCAM_ENABLED
obs_register_output(&virtualcam_info);
bool installed = vcam_installed(false);
#else
bool installed = false;
#endif
obs_data_t *obs_settings = obs_data_create();
obs_data_set_bool(obs_settings, "vcamEnabled", installed);
obs_apply_private_data(obs_settings);
obs_data_release(obs_settings);
return true;
}
| 22.3
| 73
| 0.775037
|
noelemahcz
|
28937011bddc59ba74593117e770a2f406a5a089
| 13,827
|
cpp
|
C++
|
src/MIP_deamon.cpp
|
SaivNator/MIPTP_cpp
|
c830b875c47cad742f0e0ed07649e9322865b02e
|
[
"MIT"
] | 1
|
2018-07-29T17:53:50.000Z
|
2018-07-29T17:53:50.000Z
|
src/MIP_deamon.cpp
|
SaivNator/MIPTP_cpp
|
c830b875c47cad742f0e0ed07649e9322865b02e
|
[
"MIT"
] | null | null | null |
src/MIP_deamon.cpp
|
SaivNator/MIPTP_cpp
|
c830b875c47cad742f0e0ed07649e9322865b02e
|
[
"MIT"
] | null | null | null |
//MIP_deamon.cpp
//Author: Sivert Andresen Cubedo
//C++
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include <queue>
//LINUX
#include <signal.h>
//Local
#include "../include/LinuxException.hpp"
#include "../include/EventPoll.hpp"
#include "../include/RawSock.hpp"
#include "../include/AddressTypes.hpp"
#include "../include/MIPFrame.hpp"
#include "../include/CrossIPC.hpp"
#include "../include/CrossForkExec.hpp"
#include "../include/TimerWrapper.hpp"
enum update_sock_option
{
LOCAL_MIP = 1,
ARP_DISCOVERY = 2,
ARP_LOSTCONNECTION = 3,
ADVERTISEMENT = 4
};
struct ARPPair
{
bool reply; //if true then pair is not lost
MIPAddress mip; //dest mip
MACAddress mac; //dest mac
RawSock::MIPRawSock* sock; //socket to reach dest
};
/*
Globals
*/
std::vector<RawSock::MIPRawSock> raw_sock_vec; //(must keep order intact so not to invalidate ARPPairs)
std::vector<ARPPair> arp_pair_vec; //(can't have duplicates)
ChildProcess routing_deamon;
EventPoll epoll;
AnonymousSocketPacket transport_sock;
AnonymousSocket update_sock;
AnonymousSocket lookup_sock;
std::queue<std::pair<bool, MIPFrame>> lookup_queue; //pair <true if source mip is set, frame>
const int ARP_TIMEOUT = 2000; //in ms
/*
Send local mip discovery to update_sock.
Parameters:
mip local mip discovered
Return:
void
Global:
update_sock
*/
void sendLocalMip(MIPAddress mip)
{
std::uint8_t option = update_sock_option::LOCAL_MIP;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Send arp discovery with update_sock.
Parameters:
mip discovered address
Return:
void
Glboal:
update_sock
*/
void sendArpDiscovery(MIPAddress mip)
{
std::uint8_t option = update_sock_option::ARP_DISCOVERY;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Send arp lost connection with update_sock.
Parameters:
mip lost address
Return:
void
Global:
update_sock
*/
void sendArpLostConnection(MIPAddress mip)
{
std::uint8_t option = update_sock_option::ARP_LOSTCONNECTION;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(option));
update_sock.write(reinterpret_cast<char*>(&mip), sizeof(mip));
}
/*
Print arp_pair_vec.
Parameters:
Return:
void
Global:
arp_pair_vec
*/
void printARPTable()
{
std::printf("%s: %4s:\n", "MIP", "MAC");
for (auto & p : arp_pair_vec) {
std::printf("%d: %4x:%x:%x:%x:%x:%x\n", (int)p.mip, p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5]);
}
}
/*
Add pair to arp_pair_vec.
Parameters:
sock ref to sock that Node was discovered on
mip mip
mac mac
Return:
void
Global:
arp_pair_vec
*/
void addARPPair(RawSock::MIPRawSock & sock, MIPAddress mip, MACAddress mac)
{
ARPPair pair;
pair.reply = true;
pair.mip = mip;
pair.mac = mac;
pair.sock = &sock;
arp_pair_vec.push_back(pair);
printARPTable(); //debug
}
/*
Send response frame to pair.
Parameters:
pair ref to pair
Return:
void
*/
void sendResponseFrame(ARPPair & pair)
{
static MIPFrame mip_frame;
mip_frame.setMipTRA(MIPFrame::ZERO);
mip_frame.setMipDest(pair.mip);
mip_frame.setMipSource(pair.sock->getMip());
mip_frame.setMsgSize(0);
mip_frame.setMipTTL(0xff);
MACAddress dest = pair.mac;
MACAddress source = pair.sock->getMac();
mip_frame.setEthDest(dest);
mip_frame.setEthSource(source);
mip_frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
mip_frame.setMsg(mip_frame.getData(), mip_frame.getSize());
pair.sock->sendMipFrame(mip_frame);
}
/*
Send broadcast frame on sock.
Parameters:
sock ref to sock
Return:
void
*/
void sendBroadcastFrame(RawSock::MIPRawSock & sock)
{
static MIPFrame mip_frame;
mip_frame.setMipTRA(MIPFrame::A);
mip_frame.setMipDest(0xff);
mip_frame.setMipSource(sock.getMip());
mip_frame.setMsgSize(0);
mip_frame.setMipTTL(0xff);
static MACAddress dest{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
MACAddress source = sock.getMac();
mip_frame.setEthDest(dest);
mip_frame.setEthSource(source);
mip_frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
mip_frame.setMsg(mip_frame.getData(), mip_frame.getSize());
sock.sendMipFrame(mip_frame);
}
/*
Receive on transport_sock.
Parameters:
Return:
void
Global:
transport_sock
lookup_queue
raw_sock_vec
*/
void receiveTransportSock()
{
static MIPFrame frame;
if (frame.getMsgSize() != MIPFrame::MSG_MAX_SIZE) {
frame.setMsgSize(MIPFrame::MSG_MAX_SIZE);
}
MIPAddress dest;
std::size_t msg_size;
AnonymousSocketPacket::IovecWrapper<3> iov;
iov.setIndex(0, dest);
iov.setIndex(1, msg_size);
iov.setIndex(2, frame.getMsg(), frame.getMsgSize());
transport_sock.recviovec(iov);
if (frame.getMsgSize() != msg_size) {
frame.setMsgSize(msg_size);
}
//check if dest address is local, if so then send back to transport_deamon
if (std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s) { return s.getMip() == dest; }) != raw_sock_vec.end()) {
transport_sock.sendiovec(iov);
}
else {
frame.setMipTRA(MIPFrame::T);
frame.setMipDest(dest);
frame.setMipTTL(0xff);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
lookup_queue.emplace(false, frame);
lookup_sock.write(reinterpret_cast<char*>(&dest), sizeof(dest));
}
}
/*
Receive on lookup_sock.
Parameters:
Return:
void
Global:
lookup_sock
*/
void receiveLookupSock()
{
bool success;
lookup_sock.read(reinterpret_cast<char*>(&success), sizeof(success));
if (success) {
MIPAddress via;
lookup_sock.read(reinterpret_cast<char*>(&via), sizeof(via));
//check outgoing sockets
auto pair_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == via; });
if (pair_it != arp_pair_vec.end()) {
ARPPair pair = (*pair_it);
MIPFrame & frame = lookup_queue.front().second;
if (!lookup_queue.front().first) {
frame.setMipSource(pair.sock->getMip());
}
MACAddress eth_dest = pair.mac;
MACAddress eth_source = pair.sock->getMac();
frame.setEthDest(eth_dest);
frame.setEthSource(eth_source);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
pair.sock->sendMipFrame(frame);
}
//check if via is target is local
lookup_queue.pop();
}
else {
lookup_queue.pop();
}
}
/*
Receive on update_sock.
Parameters:
Return:
void
Global:
update_sock
arp_pair_vec
*/
void receiveUpdateSock()
{
//receive:
// to
// ad size
// ad
static MIPFrame frame;
MIPAddress dest_mip;
std::size_t ad_size;
update_sock.read(reinterpret_cast<char*>(&dest_mip), sizeof(dest_mip));
update_sock.read(reinterpret_cast<char*>(&ad_size), sizeof(ad_size));
frame.setMsgSize(ad_size);
update_sock.read(frame.getMsg(), ad_size);
auto pair_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == dest_mip; });
if (pair_it != arp_pair_vec.end()) {
ARPPair & pair = (*pair_it);
frame.setMipTRA(MIPFrame::R);
frame.setMipDest(pair.mip);
frame.setMipSource(pair.sock->getMip());
frame.setMipTTL(0xff);
MACAddress eth_dest = pair.mac;
MACAddress eth_source = pair.sock->getMac();
frame.setEthDest(eth_dest);
frame.setEthSource(eth_source);
frame.setEthProtocol(htons(RawSock::MIPRawSock::ETH_P_MIP));
pair.sock->sendMipFrame(frame);
}
}
/*
Receive on raw sock.
Parameters:
sock ref to sock
Return:
void
Global:
update_sock
*/
void receiveRawSock(RawSock::MIPRawSock & sock)
{
static MIPFrame mip_frame;
sock.recvMipFrame(mip_frame);
int tra = mip_frame.getMipTRA();
MIPAddress source_mip = mip_frame.getMipSource();
MIPAddress dest_mip = mip_frame.getMipDest();
std::uint8_t option;
std::size_t msg_size = mip_frame.getMsgSize();
std::vector<ARPPair>::iterator arp_it;
switch (tra)
{
case MIPFrame::A:
arp_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == source_mip; });
if (arp_it == arp_pair_vec.end()) {
addARPPair(sock, mip_frame.getMipSource(), mip_frame.getEthSource());
sendArpDiscovery(source_mip);
sendResponseFrame(arp_pair_vec.back());
}
else {
arp_it->reply = true;
sendResponseFrame((*arp_it));
}
break;
case MIPFrame::ZERO:
arp_it = std::find_if(arp_pair_vec.begin(), arp_pair_vec.end(), [&](ARPPair & p) { return p.mip == source_mip; });
if (arp_it == arp_pair_vec.end()) {
addARPPair(sock, mip_frame.getMipSource(), mip_frame.getEthSource());
sendArpDiscovery(source_mip);
}
else {
arp_it->reply = true;
}
break;
case MIPFrame::R:
//send ad to routing_deamon
//send:
// from
// ad size
// ad
option = update_sock_option::ADVERTISEMENT;
update_sock.write(reinterpret_cast<char*>(&option), sizeof(std::uint8_t));
update_sock.write(reinterpret_cast<char*>(&source_mip), sizeof(source_mip));
update_sock.write(reinterpret_cast<char*>(&msg_size), sizeof(msg_size));
update_sock.write(mip_frame.getMsg(), msg_size);
break;
case MIPFrame::T:
//cache frame in lookup_queue
//send:
// mip
if (std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s) { return s.getMip() == dest_mip; }) == raw_sock_vec.end()) {
int ttl = mip_frame.getMipTTL();
if (ttl <= 0) {
//drop frame
std::cout << "ttl 0, dropping frame\n";
}
else {
mip_frame.setMipTTL(ttl - 1);
lookup_queue.emplace(true, mip_frame);
lookup_sock.write(reinterpret_cast<char*>(&dest_mip), sizeof(dest_mip));
}
}
else {
//send to transport deamon
AnonymousSocketPacket::IovecWrapper<3> iov;
iov.setIndex(0, source_mip);
iov.setIndex(1, msg_size);
iov.setIndex(2, mip_frame.getMsg(), msg_size);
transport_sock.sendiovec(iov);
}
break;
default:
throw std::runtime_error("Invalid TRA");
break;
}
}
/*
Init raw_sock_vec.
Parameters:
mip_vec ref to vec containing mip
Return:
void
*/
void initRawSock(const std::vector<MIPAddress> & mip_vec)
{
auto inter_names = RawSock::getInterfaceNames(std::vector<int>{ AF_PACKET });
for (auto & mip : mip_vec) {
if (inter_names.empty()) {
//debug
std::cout << raw_sock_vec.size() << " interfaces detected.\n";
return;
}
std::string & name = inter_names.back();
if (name == "lo") {
continue;
}
raw_sock_vec.push_back(RawSock::MIPRawSock(name, mip));
//debug
std::cout << raw_sock_vec.back().toString() << "\n";
inter_names.pop_back();
}
//debug
std::cout << raw_sock_vec.size() << " interfaces detected.\n";
}
/*
Signal function.
*/
void sigintHandler(int signum)
{
epoll.closeResources();
}
/*
args: ./MIP_deamon <transport connection> [mip addresses ...]
*/
int main(int argc, char** argv)
{
//parse args
if (argc < 3) {
std::cerr << "Too few args\n";
return EXIT_FAILURE;
}
//signal
struct sigaction sa;
sa.sa_handler = &sigintHandler;
if (sigaction(SIGINT, &sa, NULL) == -1) {
throw LinuxException::Error("sigaction()");
}
//Connect transport_deamon
transport_sock = AnonymousSocketPacket(argv[1]);
//Connect routing_deamon
{
auto pair1 = AnonymousSocket::createPair();
auto pair2 = AnonymousSocket::createPair();
std::vector<std::string> args(2);
args[0] = pair1.second.toString();
args[1] = pair2.second.toString();
routing_deamon = ChildProcess::forkExec("./routing_deamon", args);
update_sock = pair1.first;
lookup_sock = pair2.first;
pair1.second.closeResources();
pair2.second.closeResources();
}
//Make MIPRawSock
{
std::vector<MIPAddress> mip_vec;
for (int i = 2; i < argc; ++i) {
mip_vec.push_back(std::atoi(argv[i]));
}
initRawSock(mip_vec);
}
//epoll
epoll = EventPoll(100);
for (auto & sock : raw_sock_vec) {
epoll.addFriend<RawSock::MIPRawSock>(sock);
}
epoll.addFriend<AnonymousSocketPacket>(transport_sock);
epoll.addFriend<AnonymousSocket>(update_sock);
epoll.addFriend<AnonymousSocket>(lookup_sock);
//send local mip addresses to routing_deamon
for (auto & s : raw_sock_vec) {
sendLocalMip(s.getMip());
}
//Send first broadcast frames
for (auto & s : raw_sock_vec) {
sendBroadcastFrame(s);
}
//timer
TimerWrapper timeout_timer;
timeout_timer.setExpirationFromNow(ARP_TIMEOUT);
epoll.addFriend(timeout_timer);
while (!epoll.isClosed()) {
try {
auto & event_vec = epoll.wait(20); //<- epoll exceptions will happen here
for (auto & ev : event_vec) {
int in_fd = ev.data.fd;
//check
if (in_fd == timeout_timer.getFd()) {
//std::cout << "Expired: " << timeout_timer.readExpiredTime() << "\n";
for (auto it = arp_pair_vec.begin(); it != arp_pair_vec.end(); ) {
if (!it->reply) {
sendArpLostConnection(it->mip);
arp_pair_vec.erase(it);
}
else {
it->reply = false;
++it;
}
}
for (RawSock::MIPRawSock & sock : raw_sock_vec) {
sendBroadcastFrame(sock);
}
timeout_timer.setExpirationFromNow(ARP_TIMEOUT);
}
else if (in_fd == transport_sock.getFd()) {
receiveTransportSock();
}
else if (in_fd == update_sock.getFd()) {
receiveUpdateSock();
}
else if (in_fd == lookup_sock.getFd()) {
receiveLookupSock();
}
else {
//check raw
auto raw_it = std::find_if(raw_sock_vec.begin(), raw_sock_vec.end(), [&](RawSock::MIPRawSock & s){ return s.getFd() == in_fd; });
if (raw_it != raw_sock_vec.end()) {
receiveRawSock((*raw_it));
}
}
}
}
catch (LinuxException::InterruptedException & e) {
//if this then interrupted
std::cout << "MIP_deamon: epoll interrupted\n";
}
}
update_sock.closeResources();
lookup_sock.closeResources();
std::cout << "MIP_deamon: joining routing_deamon\n";
routing_deamon.join();
std::cout << "MIP_deamon: terminating\n";
return EXIT_SUCCESS;
}
| 24.300527
| 150
| 0.697621
|
SaivNator
|
28937fbfa133d011eabee2e20eb392f70358a729
| 1,533
|
cc
|
C++
|
third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
third_party/blink/renderer/core/xml/document_xml_tree_viewer.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2016 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 "third_party/blink/renderer/core/xml/document_xml_tree_viewer.h"
#include "third_party/blink/public/resources/grit/blink_resources.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/script/classic_script.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/data_resource_helper.h"
namespace blink {
void TransformDocumentToXMLTreeView(Document& document) {
String script_string =
UncompressResourceAsASCIIString(IDR_DOCUMENTXMLTREEVIEWER_JS);
String css_string =
UncompressResourceAsASCIIString(IDR_DOCUMENTXMLTREEVIEWER_CSS);
v8::HandleScope handle_scope(V8PerIsolateData::MainThreadIsolate());
ClassicScript::CreateUnspecifiedScript(script_string,
ScriptSourceLocationType::kInternal)
->RunScriptInIsolatedWorldAndReturnValue(
document.domWindow(), IsolatedWorldId::kDocumentXMLTreeViewerWorldId);
Element* element = document.getElementById("xml-viewer-style");
if (element) {
element->setTextContent(css_string);
}
}
} // namespace blink
| 40.342105
| 80
| 0.782779
|
chromium
|
28944b8ff24d177b9155a38b7480e3264003a45e
| 1,571
|
hpp
|
C++
|
src/libs/server_common/include/keto/server_common/EventUtils.hpp
|
burntjam/keto
|
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
|
[
"MIT"
] | 1
|
2020-03-04T10:38:00.000Z
|
2020-03-04T10:38:00.000Z
|
src/libs/server_common/include/keto/server_common/EventUtils.hpp
|
burntjam/keto
|
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
|
[
"MIT"
] | null | null | null |
src/libs/server_common/include/keto/server_common/EventUtils.hpp
|
burntjam/keto
|
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
|
[
"MIT"
] | 1
|
2020-03-04T10:38:01.000Z
|
2020-03-04T10:38:01.000Z
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: EventUtils.hpp
* Author: ubuntu
*
* Created on February 17, 2018, 10:33 AM
*/
#ifndef EVENTUTILS_HPP
#define EVENTUTILS_HPP
#include <string>
#include <vector>
#include "keto/event/Event.hpp"
#include "keto/server_common/VectorUtils.hpp"
#include "keto/server_common/Exception.hpp"
namespace keto {
namespace server_common {
template<class PbType>
keto::event::Event toEvent(PbType& type) {
std::string pbValue;
if (!type.SerializeToString(&pbValue)) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffSerializationException());
}
return keto::event::Event(VectorUtils().copyStringToVector(pbValue));
}
template<class PbType>
keto::event::Event toEvent(const std::string& event, PbType& type) {
std::string pbValue;
if (!type.SerializeToString(&pbValue)) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffSerializationException());
}
return keto::event::Event(event,VectorUtils().copyStringToVector(pbValue));
}
template<class PbType>
PbType fromEvent(const keto::event::Event& event) {
PbType pbValue;
keto::event::Event copyEvent = event;
if (!pbValue.ParseFromString(VectorUtils().copyVectorToString(copyEvent.getMessage()))) {
BOOST_THROW_EXCEPTION(keto::server_common::ProtobuffDeserializationException());
}
return pbValue;
}
}
}
#endif /* EVENTUTILS_HPP */
| 25.754098
| 93
| 0.721833
|
burntjam
|
28965e844bd40bf2ec2d3b1d670fa2188ec31509
| 16,473
|
cc
|
C++
|
third_party/blink/renderer/modules/webtransport/outgoing_stream_test.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
third_party/blink/renderer/modules/webtransport/outgoing_stream_test.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86
|
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
third_party/blink/renderer/modules/webtransport/outgoing_stream_test.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webtransport/outgoing_stream.h"
#include <utility>
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_tester.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_traits.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_exception.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_typed_array.h"
#include "third_party/blink/renderer/modules/webtransport/web_transport_error.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "v8/include/v8.h"
namespace blink {
namespace {
using ::testing::ElementsAre;
using ::testing::StrictMock;
class MockClient : public GarbageCollected<MockClient>,
public OutgoingStream::Client {
public:
MOCK_METHOD0(SendFin, void());
MOCK_METHOD0(ForgetStream, void());
MOCK_METHOD1(Reset, void(uint8_t));
};
// The purpose of this class is to ensure that the data pipe is reset before the
// V8TestingScope is destroyed, so that the OutgoingStream object doesn't try to
// create a DOMException after the ScriptState has gone away.
class StreamCreator {
STACK_ALLOCATED();
public:
StreamCreator() = default;
~StreamCreator() {
Reset();
// Let the OutgoingStream object respond to the closure if it needs to.
test::RunPendingTasks();
}
// The default value of |capacity| means some sensible value selected by mojo.
OutgoingStream* Create(const V8TestingScope& scope, uint32_t capacity = 0) {
MojoCreateDataPipeOptions options;
options.struct_size = sizeof(MojoCreateDataPipeOptions);
options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE;
options.element_num_bytes = 1;
options.capacity_num_bytes = capacity;
mojo::ScopedDataPipeProducerHandle data_pipe_producer;
MojoResult result =
mojo::CreateDataPipe(&options, data_pipe_producer, data_pipe_consumer_);
if (result != MOJO_RESULT_OK) {
ADD_FAILURE() << "CreateDataPipe() returned " << result;
}
auto* script_state = scope.GetScriptState();
mock_client_ = MakeGarbageCollected<StrictMock<MockClient>>();
auto* outgoing_stream = MakeGarbageCollected<OutgoingStream>(
script_state, mock_client_, std::move(data_pipe_producer));
ExceptionState exception_state(scope.GetIsolate(),
ExceptionState::kConstructionContext,
"OutgoingStream");
outgoing_stream->Init(exception_state);
CHECK(!exception_state.HadException());
return outgoing_stream;
}
// Closes the pipe.
void Reset() { data_pipe_consumer_.reset(); }
// This is for use in EXPECT_CALL(), which is why it returns a reference.
MockClient& GetMockClient() { return *mock_client_; }
// Reads everything from |data_pipe_consumer_| and returns it in a vector.
Vector<uint8_t> ReadAllPendingData() {
Vector<uint8_t> data;
const void* buffer = nullptr;
uint32_t buffer_num_bytes = 0;
MojoResult result = data_pipe_consumer_->BeginReadData(
&buffer, &buffer_num_bytes, MOJO_BEGIN_READ_DATA_FLAG_NONE);
switch (result) {
case MOJO_RESULT_OK:
break;
case MOJO_RESULT_SHOULD_WAIT: // No more data yet.
return data;
default:
ADD_FAILURE() << "BeginReadData() failed: " << result;
return data;
}
data.Append(static_cast<const uint8_t*>(buffer), buffer_num_bytes);
data_pipe_consumer_->EndReadData(buffer_num_bytes);
return data;
}
Persistent<StrictMock<MockClient>> mock_client_;
mojo::ScopedDataPipeConsumerHandle data_pipe_consumer_;
};
TEST(OutgoingStreamTest, Create) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
EXPECT_TRUE(outgoing_stream->Writable());
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
TEST(OutgoingStreamTest, WriteArrayBuffer) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
auto* chunk = DOMArrayBuffer::Create("A", 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester tester(scope.GetScriptState(), result);
tester.WaitUntilSettled();
EXPECT_TRUE(tester.IsFulfilled());
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre('A'));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
TEST(OutgoingStreamTest, WriteArrayBufferView) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
auto* buffer = DOMArrayBuffer::Create("*B", 2);
// Create a view into the buffer with offset 1, ie. "B".
auto* chunk = DOMUint8Array::Create(buffer, 1, 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester tester(scope.GetScriptState(), result);
tester.WaitUntilSettled();
EXPECT_TRUE(tester.IsFulfilled());
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre('B'));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
bool IsAllNulls(base::span<const uint8_t> data) {
return std::all_of(data.begin(), data.end(), [](uint8_t c) { return !c; });
}
TEST(OutgoingStreamTest, AsyncWrite) {
V8TestingScope scope;
StreamCreator stream_creator;
// Set a large pipe capacity, so any platform-specific excess is dwarfed in
// size.
constexpr uint32_t kPipeCapacity = 512u * 1024u;
auto* outgoing_stream = stream_creator.Create(scope, kPipeCapacity);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
// Write a chunk that definitely will not fit in the pipe.
const size_t kChunkSize = kPipeCapacity * 3;
auto* chunk = DOMArrayBuffer::Create(kChunkSize, 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester tester(scope.GetScriptState(), result);
// Let the first pipe write complete.
test::RunPendingTasks();
// Let microtasks run just in case write() returns prematurely.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
EXPECT_FALSE(tester.IsFulfilled());
// Read the first part of the data.
auto data1 = stream_creator.ReadAllPendingData();
EXPECT_LT(data1.size(), kChunkSize);
// Verify the data wasn't corrupted.
EXPECT_TRUE(IsAllNulls(data1));
// Allow the asynchronous pipe write to happen.
test::RunPendingTasks();
// Read the second part of the data.
auto data2 = stream_creator.ReadAllPendingData();
EXPECT_TRUE(IsAllNulls(data2));
test::RunPendingTasks();
// Read the final part of the data.
auto data3 = stream_creator.ReadAllPendingData();
EXPECT_TRUE(IsAllNulls(data3));
EXPECT_EQ(data1.size() + data2.size() + data3.size(), kChunkSize);
// Now the write() should settle.
tester.WaitUntilSettled();
EXPECT_TRUE(tester.IsFulfilled());
// Nothing should be left to read.
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre());
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
}
// Writing immediately followed by closing should not lose data.
TEST(OutgoingStreamTest, WriteThenClose) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
auto* chunk = DOMArrayBuffer::Create("D", 1);
ScriptPromise write_promise =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
EXPECT_CALL(stream_creator.GetMockClient(), SendFin()).WillOnce([&]() {
// This needs to happen asynchronously.
scope.GetExecutionContext()
->GetTaskRunner(TaskType::kNetworking)
->PostTask(FROM_HERE, WTF::Bind(&OutgoingStream::OnOutgoingStreamClosed,
WrapWeakPersistent(outgoing_stream)));
});
ScriptPromise close_promise =
writer->close(script_state, ASSERT_NO_EXCEPTION);
ScriptPromiseTester write_tester(scope.GetScriptState(), write_promise);
ScriptPromiseTester close_tester(scope.GetScriptState(), close_promise);
// Make sure that write() and close() both run before the event loop is
// serviced.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
write_tester.WaitUntilSettled();
EXPECT_TRUE(write_tester.IsFulfilled());
close_tester.WaitUntilSettled();
EXPECT_TRUE(close_tester.IsFulfilled());
EXPECT_THAT(stream_creator.ReadAllPendingData(), ElementsAre('D'));
}
TEST(OutgoingStreamTest, DataPipeClosed) {
V8TestingScope scope;
StreamCreator stream_creator;
auto* outgoing_stream = stream_creator.Create(scope);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
ScriptPromise closed = writer->closed(script_state);
ScriptPromiseTester closed_tester(script_state, closed);
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
// Close the other end of the pipe.
stream_creator.Reset();
closed_tester.WaitUntilSettled();
EXPECT_TRUE(closed_tester.IsRejected());
DOMException* closed_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), closed_tester.Value().V8Value());
ASSERT_TRUE(closed_exception);
EXPECT_EQ(closed_exception->name(), "NetworkError");
EXPECT_EQ(closed_exception->message(),
"The stream was aborted by the remote server");
auto* chunk = DOMArrayBuffer::Create('C', 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester write_tester(script_state, result);
write_tester.WaitUntilSettled();
EXPECT_TRUE(write_tester.IsRejected());
DOMException* write_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), write_tester.Value().V8Value());
ASSERT_TRUE(write_exception);
EXPECT_EQ(write_exception->name(), "NetworkError");
EXPECT_EQ(write_exception->message(),
"The stream was aborted by the remote server");
}
TEST(OutgoingStreamTest, DataPipeClosedDuringAsyncWrite) {
V8TestingScope scope;
StreamCreator stream_creator;
constexpr uint32_t kPipeCapacity = 512 * 1024;
auto* outgoing_stream = stream_creator.Create(scope, kPipeCapacity);
auto* script_state = scope.GetScriptState();
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
const size_t kChunkSize = kPipeCapacity * 2;
auto* chunk = DOMArrayBuffer::Create(kChunkSize, 1);
ScriptPromise result =
writer->write(script_state, ScriptValue::From(script_state, chunk),
ASSERT_NO_EXCEPTION);
ScriptPromiseTester write_tester(script_state, result);
ScriptPromise closed = writer->closed(script_state);
ScriptPromiseTester closed_tester(script_state, closed);
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
// Close the other end of the pipe.
stream_creator.Reset();
write_tester.WaitUntilSettled();
EXPECT_TRUE(write_tester.IsRejected());
DOMException* write_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), write_tester.Value().V8Value());
ASSERT_TRUE(write_exception);
EXPECT_EQ(write_exception->name(), "NetworkError");
EXPECT_EQ(write_exception->message(),
"The stream was aborted by the remote server");
closed_tester.WaitUntilSettled();
EXPECT_TRUE(closed_tester.IsRejected());
DOMException* closed_exception = V8DOMException::ToImplWithTypeCheck(
scope.GetIsolate(), write_tester.Value().V8Value());
ASSERT_TRUE(closed_exception);
EXPECT_EQ(closed_exception->name(), "NetworkError");
EXPECT_EQ(closed_exception->message(),
"The stream was aborted by the remote server");
}
TEST(OutgoingStreamTest, Abort) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), Reset(0u));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
writer->abort(script_state, ScriptValue(isolate, v8::Undefined(isolate)),
ASSERT_NO_EXCEPTION);
}
TEST(OutgoingStreamTest, AbortWithWebTransportError) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), Reset(0));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
v8::Local<v8::Value> error =
WebTransportError::Create(isolate,
/*stream_error_code=*/absl::nullopt, "foobar",
WebTransportError::Source::kStream);
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
writer->abort(script_state, ScriptValue(isolate, error), ASSERT_NO_EXCEPTION);
}
TEST(OutgoingStreamTest, AbortWithWebTransportErrorWithCode) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), Reset(8));
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
v8::Local<v8::Value> error = WebTransportError::Create(
isolate,
/*stream_error_code=*/8, "foobar", WebTransportError::Source::kStream);
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
writer->abort(script_state, ScriptValue(isolate, error), ASSERT_NO_EXCEPTION);
}
TEST(OutgoingStreamTest, CloseAndConnectionError) {
V8TestingScope scope;
StreamCreator stream_creator;
ScriptState* script_state = scope.GetScriptState();
v8::Isolate* isolate = scope.GetIsolate();
auto* outgoing_stream = stream_creator.Create(scope);
testing::InSequence s;
EXPECT_CALL(stream_creator.GetMockClient(), SendFin());
EXPECT_CALL(stream_creator.GetMockClient(), ForgetStream());
auto* writer =
outgoing_stream->Writable()->getWriter(script_state, ASSERT_NO_EXCEPTION);
// Run microtasks to ensure that the underlying sink's close function is
// called immediately.
v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
writer->close(script_state, ASSERT_NO_EXCEPTION);
outgoing_stream->Error(ScriptValue(isolate, v8::Undefined(isolate)));
}
} // namespace
} // namespace blink
| 36.44469
| 83
| 0.742002
|
zealoussnow
|
28978548b1829e7a11224ceb2e8f5153185fe842
| 1,972
|
cpp
|
C++
|
Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp
|
obivan43/pawnengine
|
ec092fa855d41705f3fb55fcf1aa5e515d093405
|
[
"MIT"
] | null | null | null |
Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp
|
obivan43/pawnengine
|
ec092fa855d41705f3fb55fcf1aa5e515d093405
|
[
"MIT"
] | null | null | null |
Editor/gui/InspectorWidget/widget/impl/Texture2DComponentWidget.cpp
|
obivan43/pawnengine
|
ec092fa855d41705f3fb55fcf1aa5e515d093405
|
[
"MIT"
] | null | null | null |
#include "Texture2DComponentWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
namespace editor::impl {
Texture2DComponentWidget::Texture2DComponentWidget(QWidget* parent)
: QWidget(parent)
, m_Entity(nullptr)
, m_Texture2D(nullptr)
, m_Color(nullptr)
, m_Texture2DLineEdit(nullptr)
, m_Texture2DLabel(nullptr) {
QVBoxLayout* layout = new QVBoxLayout(this);
QHBoxLayout* textureLayout = new QHBoxLayout();
m_Color = new Double3Widget("Color", glm::vec3(0.0f), this);
m_Color->SetMinMax(0.0, 1.0);
m_Texture2DLineEdit = new QLineEdit(this);
m_Texture2DLabel = new QLabel("Texture2D", this);
m_Texture2DLabel->setMinimumWidth(80);
textureLayout->addWidget(m_Texture2DLabel);
textureLayout->addWidget(m_Texture2DLineEdit);
layout->addWidget(m_Color);
layout->addLayout(textureLayout);
setLayout(layout);
InitConnections();
}
void Texture2DComponentWidget::OnColorChanged(glm::vec3 value) {
if (m_Texture2D) {
m_Texture2D->Color = value;
}
}
void Texture2DComponentWidget::SetEntity(pawn::engine::GameEntity* entity) {
m_Entity = entity;
}
void Texture2DComponentWidget::SetTexture2D(pawn::engine::Texture2DComponent* texture2D) {
m_Texture2D = texture2D;
m_Texture2DLineEdit->setText(texture2D->TextureName.c_str());
m_Color->SetValue(texture2D->Color);
}
void Texture2DComponentWidget::OnLineEditPress() {
QString& text{ m_Texture2DLineEdit->text() };
std::string& textureName{ m_Texture2D->TextureName };
textureName = text.toLocal8Bit().constData();
emit Texture2DModified(*m_Entity);
m_Texture2DLineEdit->clearFocus();
}
void Texture2DComponentWidget::InitConnections() {
connect(
m_Color,
SIGNAL(ValueChanged(glm::vec3)),
this,
SLOT(OnColorChanged(glm::vec3))
);
connect(
m_Texture2DLineEdit,
SIGNAL(returnPressed()),
this,
SLOT(OnLineEditPress())
);
}
}
| 24.04878
| 92
| 0.704868
|
obivan43
|
2899c2100506c2105260479f6240a9baee92e541
| 652
|
cpp
|
C++
|
Src/SimRobotCore2/Simulation/Axis.cpp
|
bhuman/SimRobot
|
f7b2039e7b8c801cdbd74ea25346cf86b298ab06
|
[
"MIT"
] | 3
|
2021-11-05T21:09:09.000Z
|
2021-11-15T22:48:10.000Z
|
Src/SimRobotCore2/Simulation/Axis.cpp
|
bhuman/SimRobot
|
f7b2039e7b8c801cdbd74ea25346cf86b298ab06
|
[
"MIT"
] | null | null | null |
Src/SimRobotCore2/Simulation/Axis.cpp
|
bhuman/SimRobot
|
f7b2039e7b8c801cdbd74ea25346cf86b298ab06
|
[
"MIT"
] | null | null | null |
/**
* @file Simulation/Axis.cpp
* Implementation of class Axis
* @author Colin Graf
*/
#include "Axis.h"
#include "Platform/Assert.h"
#include "Simulation/Actuators/Joint.h"
#include "Simulation/Motors/Motor.h"
#include <cmath>
Axis::~Axis()
{
delete deflection;
delete motor;
}
void Axis::create()
{
// normalize axis
const float len = std::sqrt(x * x + y * y + z * z);
if(len == 0.f)
x = 1.f;
else
{
const float invLen = 1.f / len;
x *= invLen;
y *= invLen;
z *= invLen;
}
}
void Axis::addParent(Element& element)
{
joint = dynamic_cast<Joint*>(&element);
ASSERT(!joint->axis);
joint->axis = this;
}
| 16.3
| 53
| 0.613497
|
bhuman
|
289e451ffa00b08f3d822915b75dff6d0df64895
| 7,873
|
cpp
|
C++
|
ext/botan/src/lib/hash/sha3/sha3.cpp
|
usdot-fhwa-OPS/V2X-Hub
|
c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c
|
[
"Apache-2.0"
] | 56
|
2019-04-25T19:06:11.000Z
|
2022-03-25T20:26:25.000Z
|
ext/botan/src/lib/hash/sha3/sha3.cpp
|
usdot-fhwa-OPS/V2X-Hub
|
c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c
|
[
"Apache-2.0"
] | 184
|
2019-04-24T18:20:08.000Z
|
2022-03-22T18:56:45.000Z
|
ext/botan/src/lib/hash/sha3/sha3.cpp
|
usdot-fhwa-OPS/V2X-Hub
|
c38f9ea0b5b4c7be60539c92c8ac3fd218edcd0c
|
[
"Apache-2.0"
] | 34
|
2019-04-03T15:21:16.000Z
|
2022-03-20T04:26:53.000Z
|
/*
* SHA-3
* (C) 2010,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/sha3.h>
#include <botan/loadstor.h>
#include <botan/rotate.h>
#include <botan/exceptn.h>
#include <botan/cpuid.h>
#include <tuple>
namespace Botan {
namespace {
// This is a workaround for a suspected bug in clang 12 (and XCode 13)
// that caused a miscompile of the SHA3 implementation for optimization
// level -O2 and higher.
//
// For details, see: https://github.com/randombit/botan/issues/2802
#if defined(__clang__) && \
(( defined(__apple_build_version__) && __clang_major__ == 13) || \
(!defined(__apple_build_version__) && __clang_major__ == 12))
#define BOTAN_WORKAROUND_MAYBE_INLINE __attribute__((noinline))
#else
#define BOTAN_WORKAROUND_MAYBE_INLINE inline
#endif
BOTAN_WORKAROUND_MAYBE_INLINE std::tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t>
xor_CNs(const uint64_t A[25])
{
return {
A[0] ^ A[5] ^ A[10] ^ A[15] ^ A[20],
A[1] ^ A[6] ^ A[11] ^ A[16] ^ A[21],
A[2] ^ A[7] ^ A[12] ^ A[17] ^ A[22],
A[3] ^ A[8] ^ A[13] ^ A[18] ^ A[23],
A[4] ^ A[9] ^ A[14] ^ A[19] ^ A[24]};
}
#undef BOTAN_WORKAROUND_MAYBE_INLINE
inline void SHA3_round(uint64_t T[25], const uint64_t A[25], uint64_t RC)
{
const auto Cs = xor_CNs(A);
const uint64_t D0 = rotl<1>(std::get<0>(Cs)) ^ std::get<3>(Cs);
const uint64_t D1 = rotl<1>(std::get<1>(Cs)) ^ std::get<4>(Cs);
const uint64_t D2 = rotl<1>(std::get<2>(Cs)) ^ std::get<0>(Cs);
const uint64_t D3 = rotl<1>(std::get<3>(Cs)) ^ std::get<1>(Cs);
const uint64_t D4 = rotl<1>(std::get<4>(Cs)) ^ std::get<2>(Cs);
const uint64_t B00 = A[ 0] ^ D1;
const uint64_t B01 = rotl<44>(A[ 6] ^ D2);
const uint64_t B02 = rotl<43>(A[12] ^ D3);
const uint64_t B03 = rotl<21>(A[18] ^ D4);
const uint64_t B04 = rotl<14>(A[24] ^ D0);
T[ 0] = B00 ^ (~B01 & B02) ^ RC;
T[ 1] = B01 ^ (~B02 & B03);
T[ 2] = B02 ^ (~B03 & B04);
T[ 3] = B03 ^ (~B04 & B00);
T[ 4] = B04 ^ (~B00 & B01);
const uint64_t B05 = rotl<28>(A[ 3] ^ D4);
const uint64_t B06 = rotl<20>(A[ 9] ^ D0);
const uint64_t B07 = rotl< 3>(A[10] ^ D1);
const uint64_t B08 = rotl<45>(A[16] ^ D2);
const uint64_t B09 = rotl<61>(A[22] ^ D3);
T[ 5] = B05 ^ (~B06 & B07);
T[ 6] = B06 ^ (~B07 & B08);
T[ 7] = B07 ^ (~B08 & B09);
T[ 8] = B08 ^ (~B09 & B05);
T[ 9] = B09 ^ (~B05 & B06);
const uint64_t B10 = rotl< 1>(A[ 1] ^ D2);
const uint64_t B11 = rotl< 6>(A[ 7] ^ D3);
const uint64_t B12 = rotl<25>(A[13] ^ D4);
const uint64_t B13 = rotl< 8>(A[19] ^ D0);
const uint64_t B14 = rotl<18>(A[20] ^ D1);
T[10] = B10 ^ (~B11 & B12);
T[11] = B11 ^ (~B12 & B13);
T[12] = B12 ^ (~B13 & B14);
T[13] = B13 ^ (~B14 & B10);
T[14] = B14 ^ (~B10 & B11);
const uint64_t B15 = rotl<27>(A[ 4] ^ D0);
const uint64_t B16 = rotl<36>(A[ 5] ^ D1);
const uint64_t B17 = rotl<10>(A[11] ^ D2);
const uint64_t B18 = rotl<15>(A[17] ^ D3);
const uint64_t B19 = rotl<56>(A[23] ^ D4);
T[15] = B15 ^ (~B16 & B17);
T[16] = B16 ^ (~B17 & B18);
T[17] = B17 ^ (~B18 & B19);
T[18] = B18 ^ (~B19 & B15);
T[19] = B19 ^ (~B15 & B16);
const uint64_t B20 = rotl<62>(A[ 2] ^ D3);
const uint64_t B21 = rotl<55>(A[ 8] ^ D4);
const uint64_t B22 = rotl<39>(A[14] ^ D0);
const uint64_t B23 = rotl<41>(A[15] ^ D1);
const uint64_t B24 = rotl< 2>(A[21] ^ D2);
T[20] = B20 ^ (~B21 & B22);
T[21] = B21 ^ (~B22 & B23);
T[22] = B22 ^ (~B23 & B24);
T[23] = B23 ^ (~B24 & B20);
T[24] = B24 ^ (~B20 & B21);
}
}
//static
void SHA_3::permute(uint64_t A[25])
{
#if defined(BOTAN_HAS_SHA3_BMI2)
if(CPUID::has_bmi2())
{
return permute_bmi2(A);
}
#endif
static const uint64_t RC[24] = {
0x0000000000000001, 0x0000000000008082, 0x800000000000808A,
0x8000000080008000, 0x000000000000808B, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008A,
0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
0x000000008000808B, 0x800000000000008B, 0x8000000000008089,
0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800A, 0x800000008000000A, 0x8000000080008081,
0x8000000000008080, 0x0000000080000001, 0x8000000080008008
};
uint64_t T[25];
for(size_t i = 0; i != 24; i += 2)
{
SHA3_round(T, A, RC[i+0]);
SHA3_round(A, T, RC[i+1]);
}
}
//static
size_t SHA_3::absorb(size_t bitrate,
secure_vector<uint64_t>& S, size_t S_pos,
const uint8_t input[], size_t length)
{
while(length > 0)
{
size_t to_take = std::min(length, bitrate / 8 - S_pos);
length -= to_take;
while(to_take && S_pos % 8)
{
S[S_pos / 8] ^= static_cast<uint64_t>(input[0]) << (8 * (S_pos % 8));
++S_pos;
++input;
--to_take;
}
while(to_take && to_take % 8 == 0)
{
S[S_pos / 8] ^= load_le<uint64_t>(input, 0);
S_pos += 8;
input += 8;
to_take -= 8;
}
while(to_take)
{
S[S_pos / 8] ^= static_cast<uint64_t>(input[0]) << (8 * (S_pos % 8));
++S_pos;
++input;
--to_take;
}
if(S_pos == bitrate / 8)
{
SHA_3::permute(S.data());
S_pos = 0;
}
}
return S_pos;
}
//static
void SHA_3::finish(size_t bitrate,
secure_vector<uint64_t>& S, size_t S_pos,
uint8_t init_pad, uint8_t fini_pad)
{
BOTAN_ARG_CHECK(bitrate % 64 == 0, "SHA-3 bitrate must be multiple of 64");
S[S_pos / 8] ^= static_cast<uint64_t>(init_pad) << (8 * (S_pos % 8));
S[(bitrate / 64) - 1] ^= static_cast<uint64_t>(fini_pad) << 56;
SHA_3::permute(S.data());
}
//static
void SHA_3::expand(size_t bitrate,
secure_vector<uint64_t>& S,
uint8_t output[], size_t output_length)
{
BOTAN_ARG_CHECK(bitrate % 64 == 0, "SHA-3 bitrate must be multiple of 64");
const size_t byterate = bitrate / 8;
while(output_length > 0)
{
const size_t copying = std::min(byterate, output_length);
copy_out_vec_le(output, copying, S);
output += copying;
output_length -= copying;
if(output_length > 0)
{
SHA_3::permute(S.data());
}
}
}
SHA_3::SHA_3(size_t output_bits) :
m_output_bits(output_bits),
m_bitrate(1600 - 2*output_bits),
m_S(25),
m_S_pos(0)
{
// We only support the parameters for SHA-3 in this constructor
if(output_bits != 224 && output_bits != 256 &&
output_bits != 384 && output_bits != 512)
throw Invalid_Argument("SHA_3: Invalid output length " +
std::to_string(output_bits));
}
std::string SHA_3::name() const
{
return "SHA-3(" + std::to_string(m_output_bits) + ")";
}
std::string SHA_3::provider() const
{
#if defined(BOTAN_HAS_SHA3_BMI2)
if(CPUID::has_bmi2())
{
return "bmi2";
}
#endif
return "base";
}
std::unique_ptr<HashFunction> SHA_3::copy_state() const
{
return std::unique_ptr<HashFunction>(new SHA_3(*this));
}
HashFunction* SHA_3::clone() const
{
return new SHA_3(m_output_bits);
}
void SHA_3::clear()
{
zeroise(m_S);
m_S_pos = 0;
}
void SHA_3::add_data(const uint8_t input[], size_t length)
{
m_S_pos = SHA_3::absorb(m_bitrate, m_S, m_S_pos, input, length);
}
void SHA_3::final_result(uint8_t output[])
{
SHA_3::finish(m_bitrate, m_S, m_S_pos, 0x06, 0x80);
/*
* We never have to run the permutation again because we only support
* limited output lengths
*/
copy_out_vec_le(output, m_output_bits/8, m_S);
clear();
}
}
| 26.778912
| 90
| 0.572717
|
usdot-fhwa-OPS
|
289ef8c8180d743574707a78d0201eb1a99f0e90
| 16,630
|
cpp
|
C++
|
editor/osm_auth.cpp
|
smartyw/organicmaps
|
9b10eb9d3ed6833861cef294c2416cc98b15e10d
|
[
"Apache-2.0"
] | 1
|
2021-06-27T05:41:23.000Z
|
2021-06-27T05:41:23.000Z
|
editor/osm_auth.cpp
|
smartyw/organicmaps
|
9b10eb9d3ed6833861cef294c2416cc98b15e10d
|
[
"Apache-2.0"
] | null | null | null |
editor/osm_auth.cpp
|
smartyw/organicmaps
|
9b10eb9d3ed6833861cef294c2416cc98b15e10d
|
[
"Apache-2.0"
] | null | null | null |
#include "editor/osm_auth.hpp"
#include "platform/http_client.hpp"
#include "coding/url.hpp"
#include "base/assert.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include <iostream>
#include <map>
#include "private.h"
#include "3party/liboauthcpp/include/liboauthcpp/liboauthcpp.h"
using namespace std;
using platform::HttpClient;
namespace osm
{
constexpr char const * kApiVersion = "/api/0.6";
constexpr char const * kFacebookCallbackPart = "/auth/facebook_access_token/callback?access_token=";
constexpr char const * kGoogleCallbackPart = "/auth/google_oauth2_access_token/callback?access_token=";
constexpr char const * kFacebookOAuthPart = "/auth/facebook?referer=%2Foauth%2Fauthorize%3Foauth_token%3D";
constexpr char const * kGoogleOAuthPart = "/auth/google?referer=%2Foauth%2Fauthorize%3Foauth_token%3D";
namespace
{
string FindAuthenticityToken(string const & body)
{
auto pos = body.find("name=\"authenticity_token\"");
if (pos == string::npos)
return string();
string const kValue = "value=\"";
auto start = body.find(kValue, pos);
if (start == string::npos)
return string();
start += kValue.length();
auto const end = body.find("\"", start);
return end == string::npos ? string() : body.substr(start, end - start);
}
string BuildPostRequest(map<string, string> const & params)
{
string result;
for (auto it = params.begin(); it != params.end(); ++it)
{
if (it != params.begin())
result += "&";
result += it->first + "=" + url::UrlEncode(it->second);
}
return result;
}
} // namespace
// static
bool OsmOAuth::IsValid(KeySecret const & ks) noexcept
{
return !(ks.first.empty() || ks.second.empty());
}
// static
bool OsmOAuth::IsValid(UrlRequestToken const & urt) noexcept
{
return !(urt.first.empty() || urt.second.first.empty() || urt.second.second.empty());
}
OsmOAuth::OsmOAuth(string const & consumerKey, string const & consumerSecret,
string const & baseUrl, string const & apiUrl) noexcept
: m_consumerKeySecret(consumerKey, consumerSecret), m_baseUrl(baseUrl), m_apiUrl(apiUrl)
{
}
// static
OsmOAuth OsmOAuth::ServerAuth() noexcept
{
#ifdef DEBUG
return DevServerAuth();
#else
return ProductionServerAuth();
#endif
}
// static
OsmOAuth OsmOAuth::ServerAuth(KeySecret const & userKeySecret) noexcept
{
OsmOAuth auth = ServerAuth();
auth.SetKeySecret(userKeySecret);
return auth;
}
// static
OsmOAuth OsmOAuth::IZServerAuth() noexcept
{
constexpr char const * kIZTestServer = "http://test.osmz.ru";
constexpr char const * kIZConsumerKey = "F0rURWssXDYxtm61279rHdyu3iSLYSP3LdF6DL3Y";
constexpr char const * kIZConsumerSecret = "IoR5TAedXxcybtd5tIBZqAK07rDRAuFMsQ4nhAP6";
return OsmOAuth(kIZConsumerKey, kIZConsumerSecret, kIZTestServer, kIZTestServer);
}
// static
OsmOAuth OsmOAuth::DevServerAuth() noexcept
{
constexpr char const * kOsmDevServer = "https://master.apis.dev.openstreetmap.org";
constexpr char const * kOsmDevConsumerKey = "eRtN6yKZZf34oVyBnyaVbsWtHIIeptLArQKdTwN3";
constexpr char const * kOsmDevConsumerSecret = "lC124mtm2VqvKJjSh35qBpKfrkeIjpKuGe38Hd1H";
return OsmOAuth(kOsmDevConsumerKey, kOsmDevConsumerSecret, kOsmDevServer, kOsmDevServer);
}
// static
OsmOAuth OsmOAuth::ProductionServerAuth() noexcept
{
constexpr char const * kOsmMainSiteURL = "https://www.openstreetmap.org";
constexpr char const * kOsmApiURL = "https://api.openstreetmap.org";
return OsmOAuth(OSM_CONSUMER_KEY, OSM_CONSUMER_SECRET, kOsmMainSiteURL, kOsmApiURL);
}
void OsmOAuth::SetKeySecret(KeySecret const & keySecret) noexcept { m_tokenKeySecret = keySecret; }
KeySecret const & OsmOAuth::GetKeySecret() const noexcept { return m_tokenKeySecret; }
bool OsmOAuth::IsAuthorized() const noexcept{ return IsValid(m_tokenKeySecret); }
// Opens a login page and extract a cookie and a secret token.
OsmOAuth::SessionID OsmOAuth::FetchSessionId(string const & subUrl, string const & cookies) const
{
string const url = m_baseUrl + subUrl + (cookies.empty() ? "?cookie_test=true" : "");
HttpClient request(url);
request.SetCookies(cookies);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("FetchSessionId Network error while connecting to", url));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", url));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(FetchSessionIdError, (DebugPrint(request)));
SessionID const sid = { request.CombinedCookies(), FindAuthenticityToken(request.ServerResponse()) };
if (sid.m_cookies.empty() || sid.m_token.empty())
MYTHROW(FetchSessionIdError, ("Cookies and/or token are empty for request", DebugPrint(request)));
return sid;
}
void OsmOAuth::LogoutUser(SessionID const & sid) const
{
HttpClient request(m_baseUrl + "/logout");
request.SetCookies(sid.m_cookies);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("LogoutUser Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(LogoutUserError, (DebugPrint(request)));
}
bool OsmOAuth::LoginUserPassword(string const & login, string const & password, SessionID const & sid) const
{
map<string, string> const params =
{
{"username", login},
{"password", password},
{"referer", "/"},
{"commit", "Login"},
{"authenticity_token", sid.m_token}
};
HttpClient request(m_baseUrl + "/login");
request.SetBodyData(BuildPostRequest(params), "application/x-www-form-urlencoded")
.SetCookies(sid.m_cookies)
.SetHandleRedirects(false);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("LoginUserPassword Network error while connecting to", request.UrlRequested()));
// At the moment, automatic redirects handling is buggy on Androids < 4.4.
// set_handle_redirects(false) works only for Android code, iOS one (and curl) still automatically follow all redirects.
if (request.ErrorCode() != HTTP::OK && request.ErrorCode() != HTTP::Found)
MYTHROW(LoginUserPasswordServerError, (DebugPrint(request)));
// Not redirected page is a 100% signal that login and/or password are invalid.
if (!request.WasRedirected())
return false;
// Check if we were redirected to some 3rd party site.
if (request.UrlReceived().find(m_baseUrl) != 0)
MYTHROW(UnexpectedRedirect, (DebugPrint(request)));
// m_baseUrl + "/login" means login and/or password are invalid.
return request.ServerResponse().find("/login") == string::npos;
}
bool OsmOAuth::LoginSocial(string const & callbackPart, string const & socialToken, SessionID const & sid) const
{
string const url = m_baseUrl + callbackPart + socialToken;
HttpClient request(url);
request.SetCookies(sid.m_cookies)
.SetHandleRedirects(false);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("LoginSocial Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK && request.ErrorCode() != HTTP::Found)
MYTHROW(LoginSocialServerError, (DebugPrint(request)));
// Not redirected page is a 100% signal that social login has failed.
if (!request.WasRedirected())
return false;
// Check if we were redirected to some 3rd party site.
if (request.UrlReceived().find(m_baseUrl) != 0)
MYTHROW(UnexpectedRedirect, (DebugPrint(request)));
// m_baseUrl + "/login" means login and/or password are invalid.
return request.ServerResponse().find("/login") == string::npos;
}
// Fakes a buttons press to automatically accept requested permissions.
string OsmOAuth::SendAuthRequest(string const & requestTokenKey, SessionID const & lastSid) const
{
// We have to get a new CSRF token, using existing cookies to open the correct page.
SessionID const & sid =
FetchSessionId("/oauth/authorize?oauth_token=" + requestTokenKey, lastSid.m_cookies);
map<string, string> const params =
{
{"oauth_token", requestTokenKey},
{"oauth_callback", ""},
{"authenticity_token", sid.m_token},
{"allow_read_prefs", "yes"},
{"allow_write_api", "yes"},
{"allow_write_gpx", "yes"},
{"allow_write_notes", "yes"},
{"commit", "Save changes"}
};
HttpClient request(m_baseUrl + "/oauth/authorize");
request.SetBodyData(BuildPostRequest(params), "application/x-www-form-urlencoded")
.SetCookies(sid.m_cookies)
.SetHandleRedirects(false);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("SendAuthRequest Network error while connecting to", request.UrlRequested()));
string const callbackURL = request.UrlReceived();
string const vKey = "oauth_verifier=";
auto const pos = callbackURL.find(vKey);
if (pos == string::npos)
MYTHROW(SendAuthRequestError, ("oauth_verifier is not found", DebugPrint(request)));
auto const end = callbackURL.find("&", pos);
return callbackURL.substr(pos + vKey.length(), end == string::npos ? end : end - pos - vKey.length());
}
RequestToken OsmOAuth::FetchRequestToken() const
{
OAuth::Consumer const consumer(m_consumerKeySecret.first, m_consumerKeySecret.second);
OAuth::Client oauth(&consumer);
string const requestTokenUrl = m_baseUrl + "/oauth/request_token";
string const requestTokenQuery = oauth.getURLQueryString(OAuth::Http::Get, requestTokenUrl + "?oauth_callback=oob");
HttpClient request(requestTokenUrl + "?" + requestTokenQuery);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("FetchRequestToken Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(FetchRequestTokenServerError, (DebugPrint(request)));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", request.UrlRequested()));
// Throws std::runtime_error.
OAuth::Token const reqToken = OAuth::Token::extract(request.ServerResponse());
return { reqToken.key(), reqToken.secret() };
}
KeySecret OsmOAuth::FinishAuthorization(RequestToken const & requestToken,
string const & verifier) const
{
OAuth::Consumer const consumer(m_consumerKeySecret.first, m_consumerKeySecret.second);
OAuth::Token const reqToken(requestToken.first, requestToken.second, verifier);
OAuth::Client oauth(&consumer, &reqToken);
string const accessTokenUrl = m_baseUrl + "/oauth/access_token";
string const queryString = oauth.getURLQueryString(OAuth::Http::Get, accessTokenUrl, "", true);
HttpClient request(accessTokenUrl + "?" + queryString);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("FinishAuthorization Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(FinishAuthorizationServerError, (DebugPrint(request)));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", request.UrlRequested()));
OAuth::KeyValuePairs const responseData = OAuth::ParseKeyValuePairs(request.ServerResponse());
// Throws std::runtime_error.
OAuth::Token const accessToken = OAuth::Token::extract(responseData);
return { accessToken.key(), accessToken.secret() };
}
// Given a web session id, fetches an OAuth access token.
KeySecret OsmOAuth::FetchAccessToken(SessionID const & sid) const
{
// Aquire a request token.
RequestToken const requestToken = FetchRequestToken();
// Faking a button press for access rights.
string const pin = SendAuthRequest(requestToken.first, sid);
LogoutUser(sid);
// Got pin, exchange it for the access token.
return FinishAuthorization(requestToken, pin);
}
bool OsmOAuth::AuthorizePassword(string const & login, string const & password)
{
SessionID const sid = FetchSessionId();
if (!LoginUserPassword(login, password, sid))
return false;
m_tokenKeySecret = FetchAccessToken(sid);
return true;
}
bool OsmOAuth::AuthorizeFacebook(string const & facebookToken)
{
SessionID const sid = FetchSessionId();
if (!LoginSocial(kFacebookCallbackPart, facebookToken, sid))
return false;
m_tokenKeySecret = FetchAccessToken(sid);
return true;
}
bool OsmOAuth::AuthorizeGoogle(string const & googleToken)
{
SessionID const sid = FetchSessionId();
if (!LoginSocial(kGoogleCallbackPart, googleToken, sid))
return false;
m_tokenKeySecret = FetchAccessToken(sid);
return true;
}
OsmOAuth::UrlRequestToken OsmOAuth::GetFacebookOAuthURL() const
{
RequestToken const requestToken = FetchRequestToken();
string const url = m_baseUrl + kFacebookOAuthPart + requestToken.first;
return UrlRequestToken(url, requestToken);
}
OsmOAuth::UrlRequestToken OsmOAuth::GetGoogleOAuthURL() const
{
RequestToken const requestToken = FetchRequestToken();
string const url = m_baseUrl + kGoogleOAuthPart + requestToken.first;
return UrlRequestToken(url, requestToken);
}
bool OsmOAuth::ResetPassword(string const & email) const
{
string const kForgotPasswordUrlPart = "/user/forgot-password";
SessionID const sid = FetchSessionId(kForgotPasswordUrlPart);
map<string, string> const params =
{
{"user[email]", email},
{"authenticity_token", sid.m_token},
{"commit", "Reset password"}
};
HttpClient request(m_baseUrl + kForgotPasswordUrlPart);
request.SetBodyData(BuildPostRequest(params), "application/x-www-form-urlencoded");
request.SetCookies(sid.m_cookies);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("ResetPassword Network error while connecting to", request.UrlRequested()));
if (request.ErrorCode() != HTTP::OK)
MYTHROW(ResetPasswordServerError, (DebugPrint(request)));
if (request.WasRedirected() && request.UrlReceived().find(m_baseUrl) != string::npos)
return true;
return false;
}
OsmOAuth::Response OsmOAuth::Request(string const & method, string const & httpMethod, string const & body) const
{
if (!IsValid(m_tokenKeySecret))
MYTHROW(InvalidKeySecret, ("User token (key and secret) are empty."));
OAuth::Consumer const consumer(m_consumerKeySecret.first, m_consumerKeySecret.second);
OAuth::Token const oatoken(m_tokenKeySecret.first, m_tokenKeySecret.second);
OAuth::Client oauth(&consumer, &oatoken);
OAuth::Http::RequestType reqType;
if (httpMethod == "GET")
reqType = OAuth::Http::Get;
else if (httpMethod == "POST")
reqType = OAuth::Http::Post;
else if (httpMethod == "PUT")
reqType = OAuth::Http::Put;
else if (httpMethod == "DELETE")
reqType = OAuth::Http::Delete;
else
MYTHROW(UnsupportedApiRequestMethod, ("Unsupported OSM API request method", httpMethod));
string url = m_apiUrl + kApiVersion + method;
string const query = oauth.getURLQueryString(reqType, url);
auto const qPos = url.find('?');
if (qPos != string::npos)
url = url.substr(0, qPos);
HttpClient request(url + "?" + query);
if (httpMethod != "GET")
request.SetBodyData(body, "application/xml", httpMethod);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("Request Network error while connecting to", url));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", url));
return Response(request.ErrorCode(), request.ServerResponse());
}
OsmOAuth::Response OsmOAuth::DirectRequest(string const & method, bool api) const
{
string const url = api ? m_apiUrl + kApiVersion + method : m_baseUrl + method;
HttpClient request(url);
if (!request.RunHttpRequest())
MYTHROW(NetworkError, ("DirectRequest Network error while connecting to", url));
if (request.WasRedirected())
MYTHROW(UnexpectedRedirect, ("Redirected to", request.UrlReceived(), "from", url));
return Response(request.ErrorCode(), request.ServerResponse());
}
string DebugPrint(OsmOAuth::Response const & code)
{
string r;
switch (code.first)
{
case OsmOAuth::HTTP::OK: r = "OK"; break;
case OsmOAuth::HTTP::BadXML: r = "BadXML"; break;
case OsmOAuth::HTTP::BadAuth: r = "BadAuth"; break;
case OsmOAuth::HTTP::Redacted: r = "Redacted"; break;
case OsmOAuth::HTTP::NotFound: r = "NotFound"; break;
case OsmOAuth::HTTP::WrongMethod: r = "WrongMethod"; break;
case OsmOAuth::HTTP::Conflict: r = "Conflict"; break;
case OsmOAuth::HTTP::Gone: r = "Gone"; break;
case OsmOAuth::HTTP::PreconditionFailed: r = "PreconditionFailed"; break;
case OsmOAuth::HTTP::URITooLong: r = "URITooLong"; break;
case OsmOAuth::HTTP::TooMuchData: r = "TooMuchData"; break;
default:
// No data from server in case of NetworkError.
if (code.first < 0)
return "NetworkError " + strings::to_string(code.first);
r = "HTTP " + strings::to_string(code.first);
}
return r + ": " + code.second;
}
} // namespace osm
| 37.881549
| 122
| 0.725797
|
smartyw
|
80bcde2c3c2754065b9a3d053ef6b1e9273b93b7
| 2,410
|
cpp
|
C++
|
RadeonGPUAnalyzerGUI/Src/rgSourceEditorTitlebar.cpp
|
jeongjoonyoo/AMD_RGA
|
26c6bfdf83f372eeadb1874420aa2ed55569d50f
|
[
"MIT"
] | 2
|
2019-05-18T11:39:59.000Z
|
2019-05-18T11:40:05.000Z
|
RadeonGPUAnalyzerGUI/Src/rgSourceEditorTitlebar.cpp
|
Acidburn0zzz/RGA
|
35cd028602e21f6b8853fdc86b16153b693acb72
|
[
"MIT"
] | null | null | null |
RadeonGPUAnalyzerGUI/Src/rgSourceEditorTitlebar.cpp
|
Acidburn0zzz/RGA
|
35cd028602e21f6b8853fdc86b16153b693acb72
|
[
"MIT"
] | null | null | null |
// C++.
#include <cassert>
#include <sstream>
// Local
#include <RadeonGPUAnalyzerGUI/Include/Qt/rgSourceEditorTitlebar.h>
#include <RadeonGPUAnalyzerGUI/Include/rgStringConstants.h>
#include <RadeonGPUAnalyzerGUI/Include/rgUtils.h>
rgSourceEditorTitlebar::rgSourceEditorTitlebar(QWidget* pParent) :
QFrame(pParent)
{
ui.setupUi(this);
// Initialize the title bar text and tooltip.
std::stringstream titlebarText;
titlebarText << STR_SOURCE_EDITOR_TITLEBAR_CORRELATION_DISABLED_A;
titlebarText << STR_SOURCE_EDITOR_TITLEBAR_CORRELATION_DISABLED_B;
ui.sourceCorrelationLabel->setText(titlebarText.str().c_str());
// Initialize the title bar contents to be hidden.
SetTitlebarContentsVisibility(false);
// Set the mouse cursor to pointing hand cursor.
SetCursor();
// Connect the signals.
ConnectSignals();
// Prep the dismiss message push button.
ui.dismissMessagePushButton->setIcon(QIcon(":/icons/deleteIcon.svg"));
ui.dismissMessagePushButton->setStyleSheet("border: none");
}
void rgSourceEditorTitlebar::ConnectSignals()
{
bool isConnected = connect(ui.dismissMessagePushButton, &QPushButton::clicked, this, &rgSourceEditorTitlebar::HandleDismissMessagePushButtonClicked);
assert(isConnected);
isConnected = connect(ui.dismissMessagePushButton, &QPushButton::clicked, this, &rgSourceEditorTitlebar::DismissMsgButtonClicked);
assert(isConnected);
}
void rgSourceEditorTitlebar::HandleDismissMessagePushButtonClicked(/* bool checked */)
{
SetTitlebarContentsVisibility(false);
}
void rgSourceEditorTitlebar::SetIsCorrelationEnabled(bool isEnabled)
{
// Only show the title bar content if source line correlation is disabled.
SetTitlebarContentsVisibility(!isEnabled);
}
void rgSourceEditorTitlebar::ShowMessage(const std::string& msg)
{
ui.sourceCorrelationLabel->setText(msg.c_str());
SetTitlebarContentsVisibility(true);
}
void rgSourceEditorTitlebar::SetCursor()
{
// Set the mouse cursor to pointing hand cursor.
ui.viewMaximizeButton->setCursor(Qt::PointingHandCursor);
ui.dismissMessagePushButton->setCursor(Qt::PointingHandCursor);
}
void rgSourceEditorTitlebar::SetTitlebarContentsVisibility(bool isVisible)
{
ui.sourceCorrelationIcon->setVisible(isVisible);
ui.sourceCorrelationLabel->setVisible(isVisible);
ui.dismissMessagePushButton->setVisible(isVisible);
}
| 33.013699
| 153
| 0.777178
|
jeongjoonyoo
|
80bd855e82392e09fc83f2c2ad73beb0cbcd3730
| 9,648
|
cpp
|
C++
|
src/test/fixtures.cpp
|
KuroGuo/firo
|
dbce40b3c7edb21fbebb014e6fe7ab700e649b6f
|
[
"MIT"
] | null | null | null |
src/test/fixtures.cpp
|
KuroGuo/firo
|
dbce40b3c7edb21fbebb014e6fe7ab700e649b6f
|
[
"MIT"
] | null | null | null |
src/test/fixtures.cpp
|
KuroGuo/firo
|
dbce40b3c7edb21fbebb014e6fe7ab700e649b6f
|
[
"MIT"
] | null | null | null |
#include "util.h"
#include "clientversion.h"
#include "primitives/transaction.h"
#include "random.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "utilmoneystr.h"
#include "test/test_bitcoin.h"
#include <stdint.h>
#include <vector>
#include <iostream>
#include "chainparams.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "sigma/openssl_context.h"
#include "validation.h"
#include "miner.h"
#include "pubkey.h"
#include "random.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "rpc/server.h"
#include "rpc/register.h"
#include "test/testutil.h"
#include "test/fixtures.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include "sigma.h"
#include "lelantus.h"
ZerocoinTestingSetupBase::ZerocoinTestingSetupBase():
TestingSetup(CBaseChainParams::REGTEST, "1") {
// Crean sigma state, just in case someone forgot to do so.
sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState();
sigmaState->Reset();
};
ZerocoinTestingSetupBase::~ZerocoinTestingSetupBase() {
// Clean sigma state after us.
sigma::CSigmaState *sigmaState = sigma::CSigmaState::GetState();
sigmaState->Reset();
}
CBlock ZerocoinTestingSetupBase::CreateBlock(const CScript& scriptPubKey) {
const CChainParams& chainparams = Params();
std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey);
CBlock block = pblocktemplate->block;
// IncrementExtraNonce creates a valid coinbase and merkleRoot
unsigned int extraNonce = 0;
IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
++block.nNonce;
}
return block;
}
bool ZerocoinTestingSetupBase::ProcessBlock(const CBlock &block) {
const CChainParams& chainparams = Params();
return ProcessNewBlock(chainparams, std::make_shared<const CBlock>(block), true, NULL);
}
// Create a new block with just given transactions, coinbase paying to
// scriptPubKey, and try to add it to the current chain.
CBlock ZerocoinTestingSetupBase::CreateAndProcessBlock(const CScript& scriptPubKey) {
CBlock block = CreateBlock(scriptPubKey);
BOOST_CHECK_MESSAGE(ProcessBlock(block), "Processing block failed");
return block;
}
void ZerocoinTestingSetupBase::CreateAndProcessEmptyBlocks(size_t block_numbers, const CScript& script) {
while (block_numbers--) {
CreateAndProcessBlock(script);
}
}
ZerocoinTestingSetup200::ZerocoinTestingSetup200()
{
BOOST_CHECK(pwalletMain->GetKeyFromPool(pubkey));
std::string strAddress = CBitcoinAddress(pubkey.GetID()).ToString();
pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
( "receive"));
//Mine 200 blocks so that we have funds for creating mints and we are over these limits:
//mBlockHeightConstants["ZC_V1_5_STARTING_BLOCK"] = 150;
//mBlockHeightConstants["ZC_CHECK_BUG_FIXED_AT_BLOCK"] = 140;
// Since sigma V3 implementation also over consensus.nMintV3SigmaStartBlock = 180;
scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
for (int i = 0; i < 200; i++)
{
CBlock b = CreateAndProcessBlock(scriptPubKey);
coinbaseTxns.push_back(*b.vtx[0]);
LOCK(cs_main);
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
}
}
}
ZerocoinTestingSetup109::ZerocoinTestingSetup109()
{
CPubKey newKey;
BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));
std::string strAddress = CBitcoinAddress(newKey.GetID()).ToString();
pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
( "receive"));
scriptPubKey = CScript() << ToByteVector(newKey/*coinbaseKey.GetPubKey()*/) << OP_CHECKSIG;
for (int i = 0; i < 109; i++)
{
CBlock b = CreateAndProcessBlock(scriptPubKey);
coinbaseTxns.push_back(*b.vtx[0]);
LOCK(cs_main);
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
}
}
}
MtpMalformedTestingSetup::MtpMalformedTestingSetup()
{
CPubKey newKey;
BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));
std::string strAddress = CBitcoinAddress(newKey.GetID()).ToString();
pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
( "receive"));
scriptPubKey = CScript() << ToByteVector(newKey/*coinbaseKey.GetPubKey()*/) << OP_CHECKSIG;
bool mtp = false;
CBlock b;
for (int i = 0; i < 150; i++)
{
b = CreateAndProcessBlock(scriptPubKey, mtp);
coinbaseTxns.push_back(*b.vtx[0]);
LOCK(cs_main);
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
}
}
}
CBlock MtpMalformedTestingSetup::CreateBlock(
const CScript& scriptPubKeyMtpMalformed, bool mtp = false) {
const CChainParams& chainparams = Params();
std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKeyMtpMalformed);
CBlock block = pblocktemplate->block;
// IncrementExtraNonce creates a valid coinbase and merkleRoot
unsigned int extraNonce = 0;
IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
++block.nNonce;
}
if(mtp) {
while (!CheckMerkleTreeProof(block, chainparams.GetConsensus())){
block.mtpHashValue = mtp::hash(block, Params().GetConsensus().powLimit);
}
}
else {
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
++block.nNonce;
}
}
//delete pblocktemplate;
return block;
}
// Create a new block with just given transactions, coinbase paying to
// scriptPubKeyMtpMalformed, and try to add it to the current chain.
CBlock MtpMalformedTestingSetup::CreateAndProcessBlock(
const CScript& scriptPubKeyMtpMalformed,
bool mtp = false) {
CBlock block = CreateBlock(scriptPubKeyMtpMalformed, mtp);
BOOST_CHECK_MESSAGE(ProcessBlock(block), "Processing block failed");
return block;
}
LelantusTestingSetup::LelantusTestingSetup() :
params(lelantus::Params::get_default()) {
CPubKey key;
{
LOCK(pwalletMain->cs_wallet);
key = pwalletMain->GenerateNewKey();
}
script = GetScriptForDestination(key.GetID());
}
CBlockIndex* LelantusTestingSetup::GenerateBlock(std::vector<CMutableTransaction> const &txns, CScript *script) {
auto last = chainActive.Tip();
CreateAndProcessBlock(txns, script ? *script : this->script);
auto block = chainActive.Tip();
if (block != last) {
pwalletMain->ScanForWalletTransactions(block, true);
}
return block != last ? block : nullptr;
}
void LelantusTestingSetup::GenerateBlocks(size_t blocks, CScript *script) {
while (blocks--) {
GenerateBlock({}, script);
}
}
std::vector<lelantus::PrivateCoin> LelantusTestingSetup::GenerateMints(
std::vector<CAmount> const &amounts) {
auto const &p = lelantus::Params::get_default();
std::vector<lelantus::PrivateCoin> coins;
for (auto a : amounts) {
std::vector<unsigned char> k(32);
GetRandBytes(k.data(), k.size());
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_create(OpenSSLContext::get_context(), &pubkey, k.data())) {
throw std::runtime_error("Fail to create public key");
}
auto serial = lelantus::PrivateCoin::serialNumberFromSerializedPublicKey(
OpenSSLContext::get_context(), &pubkey);
Scalar randomness;
randomness.randomize();
coins.emplace_back(p, serial, a, randomness, k, 0);
}
return coins;
}
std::vector<CHDMint> LelantusTestingSetup::GenerateMints(
std::vector<CAmount> const &amounts,
std::vector<CMutableTransaction> &txs) {
std::vector<lelantus::PrivateCoin> coins;
return GenerateMints(amounts, txs, coins);
}
std::vector<CHDMint> LelantusTestingSetup::GenerateMints(
std::vector<CAmount> const &amounts,
std::vector<CMutableTransaction> &txs,
std::vector<lelantus::PrivateCoin> &coins) {
std::vector<CHDMint> hdMints;
CWalletDB walletdb(pwalletMain->strWalletFile);
for (auto a : amounts) {
std::vector<std::pair<CWalletTx, CAmount>> wtxAndFee;
std::vector<CHDMint> mints;
auto result = pwalletMain->MintAndStoreLelantus(a, wtxAndFee, mints);
if (result != "") {
throw std::runtime_error(_("Fail to generate mints, ") + result);
}
for(auto itr : wtxAndFee)
txs.emplace_back(itr.first);
hdMints.insert(hdMints.end(), mints.begin(), mints.end());
}
return hdMints;
}
CPubKey LelantusTestingSetup::GenerateAddress() {
LOCK(pwalletMain->cs_wallet);
return pwalletMain->GenerateNewKey();
}
LelantusTestingSetup::~LelantusTestingSetup() {
lelantus::CLelantusState::GetState()->Reset();
}
| 31.42671
| 122
| 0.671953
|
KuroGuo
|
80be5327b4a40ed528ee97850b6ce595bc80ce65
| 17,311
|
cpp
|
C++
|
test/test_file.cpp
|
aleyooop/realm-core
|
9874d5164927ea39273b241a5af14b596a3233e9
|
[
"Apache-2.0"
] | 977
|
2016-09-27T12:54:24.000Z
|
2022-03-29T08:08:47.000Z
|
test/test_file.cpp
|
aleyooop/realm-core
|
9874d5164927ea39273b241a5af14b596a3233e9
|
[
"Apache-2.0"
] | 2,265
|
2016-09-27T13:01:26.000Z
|
2022-03-31T17:55:37.000Z
|
test/test_file.cpp
|
aleyooop/realm-core
|
9874d5164927ea39273b241a5af14b596a3233e9
|
[
"Apache-2.0"
] | 154
|
2016-09-27T14:02:56.000Z
|
2022-03-27T14:51:00.000Z
|
/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include "testsettings.hpp"
#ifdef TEST_FILE
#include <ostream>
#include <sstream>
#include <realm/util/file.hpp>
#include <realm/util/file_mapper.hpp>
#include "test.hpp"
#if REALM_PLATFORM_APPLE
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
using namespace realm::util;
using namespace realm::test_util;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
TEST(File_ExistsAndRemove)
{
TEST_PATH(path);
File(path, File::mode_Write);
CHECK(File::exists(path));
CHECK(File::try_remove(path));
CHECK(!File::exists(path));
CHECK(!File::try_remove(path));
}
TEST(File_IsSame)
{
TEST_PATH(path_1);
TEST_PATH(path_2);
// exFAT does not allocate inode numbers until the file is first non-empty,
// so all never-written-to files appear to be the same file
File(path_1, File::mode_Write).resize(1);
File(path_2, File::mode_Write).resize(1);
File f1(path_1, File::mode_Append);
File f2(path_1, File::mode_Read);
File f3(path_2, File::mode_Append);
CHECK(f1.is_same_file(f1));
CHECK(f1.is_same_file(f2));
CHECK(!f1.is_same_file(f3));
CHECK(!f2.is_same_file(f3));
}
TEST(File_Streambuf)
{
TEST_PATH(path);
{
File f(path, File::mode_Write);
File::Streambuf b(&f);
std::ostream out(&b);
out << "Line " << 1 << std::endl;
out << "Line " << 2 << std::endl;
}
{
File f(path, File::mode_Read);
char buffer[256];
size_t n = f.read(buffer);
std::string s_1(buffer, buffer + n);
std::ostringstream out;
out << "Line " << 1 << std::endl;
out << "Line " << 2 << std::endl;
std::string s_2 = out.str();
CHECK(s_1 == s_2);
}
}
TEST(File_Map)
{
TEST_PATH(path);
const char data[4096] = "12345678901234567890";
size_t len = strlen(data);
{
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(len);
File::Map<char> map(f, File::access_ReadWrite, len);
realm::util::encryption_read_barrier(map, 0, len);
memcpy(map.get_addr(), data, len);
realm::util::encryption_write_barrier(map, 0, len);
}
{
File f(path, File::mode_Read);
f.set_encryption_key(crypt_key());
File::Map<char> map(f, File::access_ReadOnly, len);
realm::util::encryption_read_barrier(map, 0, len);
CHECK(memcmp(map.get_addr(), data, len) == 0);
}
}
TEST(File_MapMultiplePages)
{
// two blocks of IV tables
const size_t count = 4096 / sizeof(size_t) * 256 * 2;
TEST_PATH(path);
{
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(count * sizeof(size_t));
File::Map<size_t> map(f, File::access_ReadWrite, count * sizeof(size_t));
realm::util::encryption_read_barrier(map, 0, count);
for (size_t i = 0; i < count; ++i)
map.get_addr()[i] = i;
realm::util::encryption_write_barrier(map, 0, count);
}
{
File f(path, File::mode_Read);
f.set_encryption_key(crypt_key());
File::Map<size_t> map(f, File::access_ReadOnly, count * sizeof(size_t));
realm::util::encryption_read_barrier(map, 0, count);
for (size_t i = 0; i < count; ++i) {
CHECK_EQUAL(map.get_addr()[i], i);
if (map.get_addr()[i] != i)
return;
}
}
}
TEST(File_ReaderAndWriter)
{
const size_t count = 4096 / sizeof(size_t) * 256 * 2;
TEST_PATH(path);
File writer(path, File::mode_Write);
writer.set_encryption_key(crypt_key());
writer.resize(count * sizeof(size_t));
File reader(path, File::mode_Read);
reader.set_encryption_key(crypt_key());
CHECK_EQUAL(writer.get_size(), reader.get_size());
File::Map<size_t> write(writer, File::access_ReadWrite, count * sizeof(size_t));
File::Map<size_t> read(reader, File::access_ReadOnly, count * sizeof(size_t));
for (size_t i = 0; i < count; i += 100) {
realm::util::encryption_read_barrier(write, i);
write.get_addr()[i] = i;
realm::util::encryption_write_barrier(write, i);
realm::util::encryption_read_barrier(read, i);
CHECK_EQUAL(read.get_addr()[i], i);
if (read.get_addr()[i] != i)
return;
}
}
TEST(File_Offset)
{
const size_t size = page_size();
const size_t count_per_page = size / sizeof(size_t);
// two blocks of IV tables
const size_t page_count = 256 * 2 / (size / 4096);
TEST_PATH(path);
{
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(page_count * size);
for (size_t i = 0; i < page_count; ++i) {
File::Map<size_t> map(f, i * size, File::access_ReadWrite, size);
for (size_t j = 0; j < count_per_page; ++j) {
realm::util::encryption_read_barrier(map, j);
map.get_addr()[j] = i * size + j;
realm::util::encryption_write_barrier(map, j);
}
}
}
{
File f(path, File::mode_Read);
f.set_encryption_key(crypt_key());
for (size_t i = 0; i < page_count; ++i) {
File::Map<size_t> map(f, i * size, File::access_ReadOnly, size);
for (size_t j = 0; j < count_per_page; ++j) {
realm::util::encryption_read_barrier(map, j);
CHECK_EQUAL(map.get_addr()[j], i * size + j);
if (map.get_addr()[j] != i * size + j)
return;
}
}
}
}
TEST(File_MultipleWriters)
{
const size_t count = 4096 / sizeof(size_t) * 256 * 2;
#if defined(_WIN32) && defined(REALM_ENABLE_ENCRYPTION)
// This test runs really slow on Windows with encryption
const size_t increments = 3000;
#else
const size_t increments = 100;
#endif
TEST_PATH(path);
{
File w1(path, File::mode_Write);
w1.set_encryption_key(crypt_key());
w1.resize(count * sizeof(size_t));
File w2(path, File::mode_Write);
w2.set_encryption_key(crypt_key());
w2.resize(count * sizeof(size_t));
File::Map<size_t> map1(w1, File::access_ReadWrite, count * sizeof(size_t));
File::Map<size_t> map2(w2, File::access_ReadWrite, count * sizeof(size_t));
for (size_t i = 0; i < count; i += increments) {
realm::util::encryption_read_barrier(map1, i);
++map1.get_addr()[i];
realm::util::encryption_write_barrier(map1, i);
realm::util::encryption_read_barrier(map2, i);
++map2.get_addr()[i];
realm::util::encryption_write_barrier(map2, i);
}
}
File reader(path, File::mode_Read);
reader.set_encryption_key(crypt_key());
File::Map<size_t> read(reader, File::access_ReadOnly, count * sizeof(size_t));
realm::util::encryption_read_barrier(read, 0, count);
for (size_t i = 0; i < count; i += increments) {
CHECK_EQUAL(read.get_addr()[i], 2);
if (read.get_addr()[i] != 2)
return;
}
}
TEST(File_SetEncryptionKey)
{
TEST_PATH(path);
File f(path, File::mode_Write);
const char key[64] = {0};
#if REALM_ENABLE_ENCRYPTION
f.set_encryption_key(key); // should not throw
#else
CHECK_THROW(f.set_encryption_key(key), std::runtime_error);
#endif
}
TEST(File_ReadWrite)
{
TEST_PATH(path);
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(100);
for (char i = 0; i < 100; ++i)
f.write(&i, 1);
f.seek(0);
for (char i = 0; i < 100; ++i) {
char read;
f.read(&read, 1);
CHECK_EQUAL(i, read);
}
}
TEST(File_Resize)
{
TEST_PATH(path);
File f(path, File::mode_Write);
f.set_encryption_key(crypt_key());
f.resize(page_size() * 2);
CHECK_EQUAL(page_size() * 2, f.get_size());
{
File::Map<unsigned char> m(f, File::access_ReadWrite, page_size() * 2);
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
m.get_addr()[i] = static_cast<unsigned char>(i);
realm::util::encryption_write_barrier(m, i);
}
// Resizing away the first write is indistinguishable in encrypted files
// from the process being interrupted before it does the first write,
// but with subsequent writes it can tell that there was once valid
// encrypted data there, so flush and write a second time
m.sync();
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
m.get_addr()[i] = static_cast<unsigned char>(i);
realm::util::encryption_write_barrier(m, i);
}
}
f.resize(page_size());
CHECK_EQUAL(page_size(), f.get_size());
{
File::Map<unsigned char> m(f, File::access_ReadOnly, page_size());
for (unsigned int i = 0; i < page_size(); ++i) {
realm::util::encryption_read_barrier(m, i);
CHECK_EQUAL(static_cast<unsigned char>(i), m.get_addr()[i]);
if (static_cast<unsigned char>(i) != m.get_addr()[i])
return;
}
}
f.resize(page_size() * 2);
CHECK_EQUAL(page_size() * 2, f.get_size());
{
File::Map<unsigned char> m(f, File::access_ReadWrite, page_size() * 2);
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
m.get_addr()[i] = static_cast<unsigned char>(i);
realm::util::encryption_write_barrier(m, i);
}
}
{
File::Map<unsigned char> m(f, File::access_ReadOnly, page_size() * 2);
for (unsigned int i = 0; i < page_size() * 2; ++i) {
realm::util::encryption_read_barrier(m, i);
CHECK_EQUAL(static_cast<unsigned char>(i), m.get_addr()[i]);
if (static_cast<unsigned char>(i) != m.get_addr()[i])
return;
}
}
}
TEST(File_NotFound)
{
TEST_PATH(path);
File file;
CHECK_THROW_EX(file.open(path), File::NotFound, e.get_path() == std::string(path));
}
TEST(File_PathNotFound)
{
File file;
CHECK_THROW(file.open(""), File::NotFound);
}
TEST(File_Exists)
{
TEST_PATH(path);
File file;
file.open(path, File::mode_Write); // Create the file
file.close();
CHECK_THROW_EX(file.open(path, File::access_ReadWrite, File::create_Must, File::flag_Trunc), File::Exists,
e.get_path() == std::string(path));
}
TEST(File_Move)
{
TEST_PATH(path);
File file_1(path, File::mode_Write);
CHECK(file_1.is_attached());
File file_2(std::move(file_1));
CHECK_NOT(file_1.is_attached());
CHECK(file_2.is_attached());
file_1 = std::move(file_2);
CHECK(file_1.is_attached());
CHECK_NOT(file_2.is_attached());
}
#if 0
TEST(File_PreallocResizing)
{
TEST_PATH(path);
File file(path, File::mode_Write);
CHECK(file.is_attached());
// we cannot test this with encryption...prealloc always allocates a full page
file.prealloc(0); // this is allowed
CHECK_EQUAL(file.get_size(), 0);
file.prealloc(100);
CHECK_EQUAL(file.get_size(), 100);
file.prealloc(50);
CHECK_EQUAL(file.get_size(), 100); // prealloc does not reduce size
// To expose the preallocation bug, we need to iterate over a large numbers, less than 4096.
// If the bug is present, we will allocate additional space to the file on every call, but if it is
// not present, the OS will preallocate 4096 only on the first call.
constexpr size_t init_size = 2048;
constexpr size_t dest_size = 3000;
for (size_t prealloc_space = init_size; prealloc_space <= dest_size; ++prealloc_space) {
file.prealloc(prealloc_space);
CHECK_EQUAL(file.get_size(), prealloc_space);
}
#if REALM_PLATFORM_APPLE
int fd = ::open(path.c_str(), O_RDONLY);
CHECK(fd >= 0);
struct stat statbuf;
CHECK(fstat(fd, &statbuf) == 0);
size_t allocated_size = statbuf.st_blocks;
CHECK_EQUAL(statbuf.st_size, dest_size);
CHECK(!int_multiply_with_overflow_detect(allocated_size, S_BLKSIZE));
// When performing prealloc, the OS has the option to preallocate more than the requeted space
// but we need to check that the preallocated space is within a reasonable bound.
// If space is being incorrectly preallocated (growing on each call) then we will have more than 3000KB
// of preallocated space, but if it is being allocated correctly (only when we need to expand) then we'll have
// a multiple of the optimal file system I/O operation (`stat -f %k .`) which is 4096 on HSF+.
// To give flexibility for file system prealloc implementations we check that the preallocated space is within
// at least 16 times the nominal requested size.
CHECK_LESS(allocated_size, 4096 * 16);
CHECK(::close(fd) == 0);
#endif
}
#endif
TEST(File_PreallocResizingAPFSBug)
{
TEST_PATH(path);
File file(path, File::mode_Write);
CHECK(file.is_attached());
file.write("aaaaaaaaaaaaaaaaaaaa"); // 20 a's
// calling prealloc on a newly created file would sometimes fail on APFS with EINVAL via fcntl(F_PREALLOCATE)
// this may not be the only way to trigger the error, but it does seem to be timing dependant.
file.prealloc(100);
CHECK_EQUAL(file.get_size(), 100);
// let's write past the first prealloc block (@ 4096) and verify it reads correctly too.
file.write("aaaaa");
// this will change the file size, but likely won't preallocate more space since the first call to prealloc
// will probably have allocated a whole 4096 block.
file.prealloc(200);
CHECK_EQUAL(file.get_size(), 200);
file.write("aa");
file.prealloc(5020); // expands to another 4096 block
constexpr size_t insert_pos = 5000;
const char* insert_str = "hello";
file.seek(insert_pos);
file.write(insert_str);
file.seek(insert_pos);
CHECK_EQUAL(file.get_size(), 5020);
constexpr size_t input_size = 6;
char input[input_size];
file.read(input, input_size);
CHECK_EQUAL(strncmp(input, insert_str, input_size), 0);
}
#ifndef _WIN32
TEST(File_GetUniqueID)
{
TEST_PATH(path_1);
TEST_PATH(path_2);
TEST_PATH(path_3);
File file1_1;
File file1_2;
File file2_1;
file1_1.open(path_1, File::mode_Write);
file1_2.open(path_1, File::mode_Read);
file2_1.open(path_2, File::mode_Write);
// exFAT does not allocate inode numbers until the file is first non-empty
file1_1.resize(1);
file2_1.resize(1);
File::UniqueID uid1_1 = file1_1.get_unique_id();
File::UniqueID uid1_2 = file1_2.get_unique_id();
File::UniqueID uid2_1 = file2_1.get_unique_id();
File::UniqueID uid2_2;
CHECK(File::get_unique_id(path_2, uid2_2));
CHECK(uid1_1 == uid1_2);
CHECK(uid2_1 == uid2_2);
CHECK(uid1_1 != uid2_1);
// Path doesn't exist
File::UniqueID uid3_1;
CHECK_NOT(File::get_unique_id(path_3, uid3_1));
// Test operator<
File::UniqueID uid4_1{0, 5};
File::UniqueID uid4_2{1, 42};
CHECK(uid4_1 < uid4_2);
CHECK_NOT(uid4_2 < uid4_1);
uid4_1 = {0, 1};
uid4_2 = {0, 2};
CHECK(uid4_1 < uid4_2);
CHECK_NOT(uid4_2 < uid4_1);
uid4_1 = uid4_2;
CHECK_NOT(uid4_1 < uid4_2);
CHECK_NOT(uid4_2 < uid4_1);
}
#endif
#endif // TEST_FILE
| 31.190991
| 114
| 0.621455
|
aleyooop
|
80be77e6041f1ac2db954c1ec238a0dc33252bf1
| 3,186
|
cpp
|
C++
|
Gui/VtkVis/VtkCompositeThresholdFilter.cpp
|
WenjieXu/ogs
|
0cd1b72ec824833bf949a8bbce073c82158ee443
|
[
"BSD-4-Clause"
] | 1
|
2021-11-21T17:29:38.000Z
|
2021-11-21T17:29:38.000Z
|
Gui/VtkVis/VtkCompositeThresholdFilter.cpp
|
WenjieXu/ogs
|
0cd1b72ec824833bf949a8bbce073c82158ee443
|
[
"BSD-4-Clause"
] | null | null | null |
Gui/VtkVis/VtkCompositeThresholdFilter.cpp
|
WenjieXu/ogs
|
0cd1b72ec824833bf949a8bbce073c82158ee443
|
[
"BSD-4-Clause"
] | null | null | null |
/**
* \file
* \author Lars Bilke
* \date 2010-10-25
* \brief Implementation of the VtkCompositeThresholdFilter class.
*
* \copyright
* Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
// ** INCLUDES **
#include "VtkCompositeThresholdFilter.h"
#include <vtkCellData.h>
#include <vtkThreshold.h>
#include <vtkUnstructuredGrid.h>
#include <vtkIntArray.h>
#include <vtkSmartPointer.h>
#include <limits>
VtkCompositeThresholdFilter::VtkCompositeThresholdFilter( vtkAlgorithm* inputAlgorithm )
: VtkCompositeFilter(inputAlgorithm)
{
this->init();
}
VtkCompositeThresholdFilter::~VtkCompositeThresholdFilter()
{
}
void VtkCompositeThresholdFilter::init()
{
// Set meta information about input and output data types
this->_inputDataObjectType = VTK_DATA_SET;
this->_outputDataObjectType = VTK_UNSTRUCTURED_GRID;
// Because this is the only filter here we cannot use vtkSmartPointer
vtkThreshold* threshold = vtkThreshold::New();
threshold->SetInputConnection(_inputAlgorithm->GetOutputPort());
// Sets a filter property which will be user editable
threshold->SetSelectedComponent(0);
// Setting the threshold to min / max values to ensure that the whole data
// is first processed. This is needed for correct lookup table generation.
const double dMin = std::numeric_limits<double>::lowest();
const double dMax = std::numeric_limits<double>::max();
threshold->ThresholdBetween(dMin, dMax);
// Create a list for the ThresholdBetween (vector) property.
QList<QVariant> thresholdRangeList;
// Insert the values (same values as above)
thresholdRangeList.push_back(dMin);
thresholdRangeList.push_back(dMax);
// Put that list in the property map
(*_algorithmUserVectorProperties)["Range"] = thresholdRangeList;
// Make a new entry in the property map for the SelectedComponent property
(*_algorithmUserProperties)["Selected Component"] = 0;
// Must all scalars match the criterium
threshold->SetAllScalars(1);
(*_algorithmUserProperties)["Evaluate all points"] = true;
// The threshold filter is last one and so it is also the _outputAlgorithm
_outputAlgorithm = threshold;
}
void VtkCompositeThresholdFilter::SetUserProperty( QString name, QVariant value )
{
VtkAlgorithmProperties::SetUserProperty(name, value);
// Use the same name as in init()
if (name.compare("Selected Component") == 0)
// Set the property on the algorithm
static_cast<vtkThreshold*>(_outputAlgorithm)->SetSelectedComponent(value.toInt());
else if (name.compare("Evaluate all points") == 0)
static_cast<vtkThreshold*>(_outputAlgorithm)->SetAllScalars(value.toBool());
}
void VtkCompositeThresholdFilter::SetUserVectorProperty( QString name, QList<QVariant> values )
{
VtkAlgorithmProperties::SetUserVectorProperty(name, values);
// Use the same name as in init()
if (name.compare("Range") == 0)
// Set the vector property on the algorithm
static_cast<vtkThreshold*>(_outputAlgorithm)->ThresholdBetween(
values[0].toDouble(), values[1].toDouble());
}
| 33.1875
| 95
| 0.752982
|
WenjieXu
|
80bfc03dca82f82722b71c57beed4f51541cc900
| 4,805
|
cpp
|
C++
|
alloctrace/test_main.cpp
|
crutchwalkfactory/jaikuengine-mobile-client
|
c47100ec009d47a4045b3d98addc9b8ad887b132
|
[
"MIT"
] | null | null | null |
alloctrace/test_main.cpp
|
crutchwalkfactory/jaikuengine-mobile-client
|
c47100ec009d47a4045b3d98addc9b8ad887b132
|
[
"MIT"
] | null | null | null |
alloctrace/test_main.cpp
|
crutchwalkfactory/jaikuengine-mobile-client
|
c47100ec009d47a4045b3d98addc9b8ad887b132
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2007-2009 Google Inc.
// Copyright (c) 2006-2007 Jaiku Ltd.
// Copyright (c) 2002-2006 Mika Raento and Renaud Petit
//
// This software is licensed at your choice under either 1 or 2 below.
//
// 1. MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// 2. Gnu General Public license 2.0
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//
// This file is part of the JaikuEngine mobile client.
#include <f32file.h>
#include "symbian_auto_ptr.h"
#include "app_context_impl.h"
void run_basic_and_interleaving(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("a0_top_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
char *a1=0;
{
CALLSTACKITEM_N(_CL(""), _CL("a1_top_1000"));
a1=(char*)User::Alloc(1000);
}
User::Free(a1);
char *a2=0;
{
CALLSTACKITEM_N(_CL(""), _CL("a2_top_1000"));
a2=(char*)User::Alloc(1000);
}
{
CALLSTACKITEM_N(_CL(""), _CL("a3_top_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
User::Free(a2);
}
void run_nested(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("b0_top_1000_own_0"));
{
CALLSTACKITEM_N(_CL(""), _CL("b0_top_1000_own_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
}
{
CALLSTACKITEM_N(_CL(""), _CL("b10_top_1000_own_0"));
{
CALLSTACKITEM_N(_CL(""), _CL("b11_top_1000_own_0"));
{
CALLSTACKITEM_N(_CL(""), _CL("b12_top_1000_own_1000"));
char* p=(char*)User::Alloc(1000);
User::Free(p);
}
}
}
}
void run_seq(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("c0_top_250_own_250_count_4"));
char* p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
p=(char*)User::Alloc(250);
User::Free(p); p=0;
}
{
CALLSTACKITEM_N(_CL(""), _CL("c1_top_1000_own_1000_count_4"));
char *p0=0, *p1=0, *p2=0, *p3=0;
p0=(char*)User::Alloc(250);
p1=(char*)User::Alloc(250);
p2=(char*)User::Alloc(250);
p3=(char*)User::Alloc(250);
User::Free(p0); p0=0;
User::Free(p1); p1=0;
User::Free(p2); p2=0;
User::Free(p3); p3=0;
}
}
void run_realloc(void)
{
{
CALLSTACKITEM_N(_CL(""), _CL("d0_top_1000_own_1000_count_2"));
char *p=0;
p=(char*)User::Alloc(250);
p=(char*)User::ReAlloc(p, 1000);
User::Free(p);
}
}
#ifdef __S60V3__
#include "allocator.h"
#endif
void run_tests(void)
{
#ifdef __S60V3__
RAllocator* orig=SwitchToLoggingAllocator();
#endif
RHeap *h=&(User::Heap());
TAny* (RHeap::* p)(TInt)=h->Alloc;
auto_ptr<CApp_context> c(CApp_context::NewL(false, _L("alloctest")));
run_basic_and_interleaving();
run_nested();
run_seq();
run_realloc();
#ifdef __S60V3__
SwitchBackAllocator(orig);
#endif
}
GLDEF_C int E32Main(void)
{
CTrapCleanup* cleanupStack = CTrapCleanup::New();
TRAPD(err, run_tests());
delete cleanupStack;
return 0;
}
//extern "C" {
#ifndef __S60V3__
void __stdcall _E32Startup(void);
#else
void __stdcall _E32Bootstrap(void);
#endif
void InstallHooks(void);
void __stdcall _TraceStartup(void) {
InstallHooks();
#ifndef __S60V3__
_E32Startup();
#else
_E32Bootstrap();
#endif
}
//};
| 25.972973
| 82
| 0.690739
|
crutchwalkfactory
|
80c24217e0114cb19af7e90b9f5d29c34d9537ad
| 5,933
|
cc
|
C++
|
net/cert/jwk_serializer_unittest.cc
|
nagineni/chromium-crosswalk
|
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
net/cert/jwk_serializer_unittest.cc
|
nagineni/chromium-crosswalk
|
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
net/cert/jwk_serializer_unittest.cc
|
nagineni/chromium-crosswalk
|
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 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 "net/cert/jwk_serializer.h"
#include "base/base64.h"
#include "base/values.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
#if !defined(USE_OPENSSL)
// This is the ASN.1 prefix for a P-256 public key. Specifically it's:
// SEQUENCE
// SEQUENCE
// OID id-ecPublicKey
// OID prime256v1
// BIT STRING, length 66, 0 trailing bits: 0x04
//
// The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
// public key. Following that are the two field elements as 32-byte,
// big-endian numbers, as required by the Channel ID.
static const unsigned char kP256SpkiPrefix[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04
};
static const unsigned int kEcCoordinateSize = 32U;
#endif
// This is a valid P-256 public key.
static const unsigned char kSpkiEc[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04,
0x29, 0x5d, 0x6e, 0xfe, 0x33, 0x77, 0x26, 0xea,
0x5b, 0xa4, 0xe6, 0x1b, 0x34, 0x6e, 0x7b, 0xa0,
0xa3, 0x8f, 0x33, 0x49, 0xa0, 0x9c, 0xae, 0x98,
0xbd, 0x46, 0x0d, 0xf6, 0xd4, 0x5a, 0xdc, 0x8a,
0x1f, 0x8a, 0xb2, 0x20, 0x51, 0xb7, 0xd2, 0x87,
0x0d, 0x53, 0x7e, 0x5d, 0x94, 0xa3, 0xe0, 0x34,
0x16, 0xa1, 0xcc, 0x10, 0x48, 0xcd, 0x70, 0x9c,
0x05, 0xd3, 0xd2, 0xca, 0xdf, 0x44, 0x2f, 0xf4
};
#if !defined(USE_OPENSSL)
// This is a P-256 public key with 0 X and Y values.
static const unsigned char kSpkiEcWithZeroXY[] = {
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
0x42, 0x00, 0x04,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
TEST(JwkSerializerNSSTest, ConvertSpkiFromDerToJwkEc) {
base::StringPiece spki;
base::DictionaryValue public_key_jwk;
EXPECT_FALSE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.empty());
// Test the result of a "normal" point on this curve.
spki.set(reinterpret_cast<const char*>(kSpkiEc), sizeof(kSpkiEc));
EXPECT_TRUE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
std::string string_value;
EXPECT_TRUE(public_key_jwk.GetString("alg", &string_value));
EXPECT_STREQ("EC", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("crv", &string_value));
EXPECT_STREQ("P-256", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("x", &string_value));
std::string decoded_coordinate;
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEc + sizeof(kP256SpkiPrefix),
kEcCoordinateSize));
EXPECT_TRUE(public_key_jwk.GetString("y", &string_value));
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEc + sizeof(kP256SpkiPrefix) + kEcCoordinateSize,
kEcCoordinateSize));
// Test the result of a corner case: leading 0s in the x, y coordinates are
// not trimmed, but the point is fixed-length encoded.
spki.set(reinterpret_cast<const char*>(kSpkiEcWithZeroXY),
sizeof(kSpkiEcWithZeroXY));
EXPECT_TRUE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.GetString("alg", &string_value));
EXPECT_STREQ("EC", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("crv", &string_value));
EXPECT_STREQ("P-256", string_value.c_str());
EXPECT_TRUE(public_key_jwk.GetString("x", &string_value));
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEcWithZeroXY + sizeof(kP256SpkiPrefix),
kEcCoordinateSize));
EXPECT_TRUE(public_key_jwk.GetString("y", &string_value));
EXPECT_TRUE(base::Base64Decode(string_value, &decoded_coordinate));
EXPECT_EQ(kEcCoordinateSize, decoded_coordinate.size());
EXPECT_EQ(0,
memcmp(decoded_coordinate.data(),
kSpkiEcWithZeroXY + sizeof(kP256SpkiPrefix) + kEcCoordinateSize,
kEcCoordinateSize));
}
#else
// For OpenSSL, JwkSerializer::ConvertSpkiFromDerToJwk() is not yet implemented
// and should return false. This unit test ensures that a stub implementation
// is present.
TEST(JwkSerializerOpenSSLTest, ConvertSpkiFromDerToJwkNotImplemented) {
base::StringPiece spki;
base::DictionaryValue public_key_jwk;
// The empty SPKI is trivially non-convertible...
EXPECT_FALSE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.empty());
// but even a valid SPKI is non-convertible via the stub OpenSSL
// implementation.
spki.set(reinterpret_cast<const char*>(kSpkiEc), sizeof(kSpkiEc));
EXPECT_FALSE(JwkSerializer::ConvertSpkiFromDerToJwk(spki, &public_key_jwk));
EXPECT_TRUE(public_key_jwk.empty());
}
#endif // !defined(USE_OPENSSL)
} // namespace net
| 39.553333
| 79
| 0.707062
|
nagineni
|
80c24b7d826a1b034e18ffa62ce8661006267914
| 5,300
|
cpp
|
C++
|
PersistentDSU.cpp
|
RohitTheBoss007/CodeforcesSolutions
|
4025270fb22a6c5c5276569b42e839f35b9ce09b
|
[
"MIT"
] | 2
|
2020-06-15T09:20:26.000Z
|
2020-10-01T19:24:07.000Z
|
PersistentDSU.cpp
|
RohitTheBoss007/Coding-Algorithms
|
4025270fb22a6c5c5276569b42e839f35b9ce09b
|
[
"MIT"
] | null | null | null |
PersistentDSU.cpp
|
RohitTheBoss007/Coding-Algorithms
|
4025270fb22a6c5c5276569b42e839f35b9ce09b
|
[
"MIT"
] | null | null | null |
// Problem: Persistent UnionFind (https://judge.yosupo.jp/problem/persistent_unionfind)
// Contest: Library Checker
// Time: 2020-12-16 23:45:07
// 私に忍び寄るのをやめてください、ありがとう
#include<bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define ll long long
#define int long long
#define mod 1000000007 //998244353
#define fast ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define f(i,n) for(ll i=0;i<n;i++)
#define fore(i, a, b) for (ll i = (ll)(a); i <= (ll)(b); ++i)
#define nl "\n"
#define trace(x) cerr<<#x<<": "<<x<<" "<<endl
#define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define x first
#define y second
#define vc vector
#define pb push_back
#define ar array
#define all(a) (a).begin(), (a).end()
#define rall(x) (x).rbegin(), (x).rend()
#define ms(v,n,x) fill(v,v+n,x);
#define init(c,a) memset(c,a,sizeof(c))
#define pll pair<ll,ll>
#define mll map<ll,ll>
#define sll set<ll>
#define vll vector<ll>
#define vpll vector<pll>
#define inf 9e18
#define cases ll T;cin>>T;while(T--)
#define BLOCK 500
//const double PI = 3.141592653589793238460;
template<typename T> bool mmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; }
template<typename T> bool mmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; }
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
// void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
template< typename T, int LOG >
struct PersistentArray {
struct Node {
T data;
Node *child[1 << LOG] = {};
Node() {}
Node(const T &data) : data(data) {}
};
Node *root;
PersistentArray() : root(nullptr) {}
T get(Node *t, int k) {
if(k == 0) return t->data;
return get(t->child[k & ((1 << LOG) - 1)], k >> LOG);
}
T get(const int &k) {
return get(root, k);
}
pair< Node *, T * > mutable_get(Node *t, int k) {
t = t ? new Node(*t) : new Node();
if(k == 0) return {t, &t->data};
auto p = mutable_get(t->child[k & ((1 << LOG) - 1)], k >> LOG);
t->child[k & ((1 << LOG) - 1)] = p.first;
return {t, p.second};
}
T *mutable_get(const int &k) {
auto ret = mutable_get(root, k);
root = ret.first;
return ret.second;
}
Node *build(Node *t, const T &data, int k) {
if(!t) t = new Node();
if(k == 0) {
t->data = data;
return t;
}
auto p = build(t->child[k & ((1 << LOG) - 1)], data, k >> LOG);
t->child[k & ((1 << LOG) - 1)] = p;
return t;
}
void build(const vector< T > &v) {
root = nullptr;
for(int i = 0; i < v.size(); i++) {
root = build(root, v[i], i);
}
}
};
/*
* @brief Persistent-Union-Find(永続Union-Find)
*/
struct PersistentUnionFind {
PersistentArray< int, 3 > data;
PersistentUnionFind() {}
PersistentUnionFind(int sz) {
data.build(vector< int >(sz, -1));
}
int find(int k) {
int p = data.get(k);
return p >= 0 ? find(p) : k;
}
int size(int k) {
return (-data.get(find(k)));
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if(x == y) return false;
auto u = data.get(x);
auto v = data.get(y);
if(u < v) {
auto a = data.mutable_get(x);
*a += v;
auto b = data.mutable_get(y);
*b = x;
} else {
auto a = data.mutable_get(y);
*a += u;
auto b = data.mutable_get(x);
*b = y;
}
return true;
}
};
int32_t main()
{
fast
cout << fixed << setprecision(12);
ll n,q;
cin>>n>>q;
vc<PersistentUnionFind> uf(q+1);
uf[0]= PersistentUnionFind(n);
fore(i,1,q){
ll t,k,u,v;
cin>>t>>k>>u>>v;k++;
if(t==0){
uf[i]=uf[k];
uf[i].unite(u,v);
}
else{
if(uf[k].find(u)==uf[k].find(v))cout<<1<<nl;
else cout<<0<<nl;
}
}
return 0;
}
| 25.603865
| 118
| 0.558113
|
RohitTheBoss007
|
80c5a2a27d50f3aa69dc4866d2f39309eece010a
| 3,440
|
hpp
|
C++
|
include/tao/json/events/debug.hpp
|
mallexxx/json
|
da7ae64ef1af13949a9983a92fddac44390c4951
|
[
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null |
include/tao/json/events/debug.hpp
|
mallexxx/json
|
da7ae64ef1af13949a9983a92fddac44390c4951
|
[
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null |
include/tao/json/events/debug.hpp
|
mallexxx/json
|
da7ae64ef1af13949a9983a92fddac44390c4951
|
[
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null |
// Copyright (c) 2016-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/json/
#ifndef TAO_JSON_EVENTS_DEBUG_HPP
#define TAO_JSON_EVENTS_DEBUG_HPP
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <ostream>
#include <string>
#include "../binary_view.hpp"
#include "../external/ryu.hpp"
#include "../internal/escape.hpp"
#include "../internal/hexdump.hpp"
namespace tao
{
namespace json
{
namespace events
{
// Events consumer that writes the events to a stream for debug purposes.
class debug
{
private:
std::ostream& os;
public:
explicit debug( std::ostream& in_os ) noexcept
: os( in_os )
{
}
void null()
{
os << "null\n";
}
void boolean( const bool v )
{
if( v ) {
os << "boolean: true\n";
}
else {
os << "boolean: false\n";
}
}
void number( const std::int64_t v )
{
os << "std::int64_t: " << v << '\n';
}
void number( const std::uint64_t v )
{
os << "std::uint64_t: " << v << '\n';
}
void number( const double v )
{
os << "double: ";
if( !std::isfinite( v ) ) {
os << v;
}
else {
ryu::d2s_stream( os, v );
}
os << '\n';
}
void string( const std::string_view v )
{
os << "string: \"";
internal::escape( os, v );
os << "\"\n";
}
void binary( const tao::binary_view v )
{
os << "binary: ";
internal::hexdump( os, v );
os << '\n';
}
void begin_array()
{
os << "begin array\n";
}
void begin_array( const std::size_t size )
{
os << "begin array " << size << '\n';
}
void element()
{
os << "element\n";
}
void end_array()
{
os << "end array\n";
}
void end_array( const std::size_t size )
{
os << "end array " << size << '\n';
}
void begin_object()
{
os << "begin object\n";
}
void begin_object( const std::size_t size )
{
os << "begin object " << size << '\n';
}
void key( const std::string_view v )
{
os << "key: \"";
internal::escape( os, v );
os << "\"\n";
}
void member()
{
os << "member\n";
}
void end_object()
{
os << "end object\n";
}
void end_object( const std::size_t size )
{
os << "end object " << size << '\n';
}
};
} // namespace events
} // namespace json
} // namespace tao
#endif
| 22.193548
| 82
| 0.371802
|
mallexxx
|
80c73e13996af716a05b3761f690bd9a902903d4
| 9,090
|
cpp
|
C++
|
src/translation_unit_base.cpp
|
achreto/fm-translation-framework
|
a46afcc43f94c8a224f32fcad988a830689a9256
|
[
"MIT"
] | null | null | null |
src/translation_unit_base.cpp
|
achreto/fm-translation-framework
|
a46afcc43f94c8a224f32fcad988a830689a9256
|
[
"MIT"
] | null | null | null |
src/translation_unit_base.cpp
|
achreto/fm-translation-framework
|
a46afcc43f94c8a224f32fcad988a830689a9256
|
[
"MIT"
] | null | null | null |
/**
* Translation Unit Base class implementation
*
* SPDX-License-Identifier: MIT
*
* Copyright (C) 2022, Reto Achermann (The University of British Columbia)
*/
#include "pv/PVBusMaster.h"
#include "pv/PVAccessWidth.h"
#include <framework/translation_unit_base.hpp>
#include <framework/interface_base.hpp>
#include <framework/logging.hpp>
/*
* -------------------------------------------------------------------------------------------
* Reset
* -------------------------------------------------------------------------------------------
*/
void TranslationUnitBase::reset(void)
{
Logging::info("resetting translation unit '%s'", this->_name.c_str());
this->get_state()->reset();
this->get_interface()->reset();
Logging::info("reset completed");
}
void TranslationUnitBase::set_reset(bool signal_level) { }
/*
* -------------------------------------------------------------------------------------------
* Printing Functionality
* -------------------------------------------------------------------------------------------
*/
// prints the global state
std::ostream &TranslationUnitBase::print_global_state(std::ostream &os)
{
return os;
}
// prints the translation steps for an address
std::ostream &TranslationUnitBase::print_translation(std::ostream &os, lvaddr_t addr)
{
return os;
}
/*
* -------------------------------------------------------------------------------------------------
* Configuration Space
* -------------------------------------------------------------------------------------------------
*/
pv::Tx_Result TranslationUnitBase::control_read(pv::ReadTransaction tx)
{
access_mode_t mode;
uint64_t value;
Logging::debug("TranslationUnit::control_read([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
// we want only to support aligned accesses to the configuration space
if (!tx.isAligned()) {
Logging::info("TranslationUnit::control_read(): unaligned data access.");
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
if (tx.isNonSecure()) {
if (tx.isPrivileged()) {
mode = ACCESS_MODE_NOSEC_READ;
} else {
mode = ACCESS_MODE_USER_READ;
}
} else {
mode = ACCESS_MODE_SEC_READ;
}
auto iface = this->get_interface();
bool r = iface->handle_register_read(tx.getAddress(), tx.getTransactionByteSize(), mode,
&value);
if (!r) {
Logging::debug("TranslationUnit::control_write(): read failed.");
return pv::Tx_Result(pv::Tx_Data::TX_TRANSFAULT);
}
switch (tx.getTransactionByteSize()) {
case 1: {
return tx.setReturnData8(value);
}
case 2: {
// XXX: work around,as the following statement somehow causes issues...
// return tx.setReturnData16(value);
*static_cast<uint16_t *>(tx.referenceDataValue()) = value;
return pv::Tx_Result(pv::Tx_Data::TX_OK);
}
case 4: {
return tx.setReturnData32(value);
}
case 8: {
return tx.setReturnData64(value);
}
default:
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
}
pv::Tx_Result TranslationUnitBase::control_write(pv::WriteTransaction tx)
{
access_mode_t mode;
uint64_t value;
Logging::debug("TranslationUnitBase::control_write([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
// we want only to support aligned accesses to the configuration space
if (!tx.isAligned()) {
Logging::debug("TranslationUnitBase::control_write(): unaligned data access.");
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
if (tx.isNonSecure()) {
if (tx.isPrivileged()) {
mode = ACCESS_MODE_NOSEC_READ;
} else {
mode = ACCESS_MODE_USER_READ;
}
} else {
mode = ACCESS_MODE_SEC_READ;
}
switch (tx.getTransactionByteSize()) {
case 1:
value = tx.getData8();
break;
case 2:
value = tx.getData16();
break;
case 4:
value = tx.getData32();
break;
case 8:
value = tx.getData64();
break;
default:
Logging::info("TranslationUnitBase::control_write(): unsupported transaction size.");
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
auto iface = this->get_interface();
bool r = iface->handle_register_write(tx.getAddress(), tx.getTransactionByteSize(), mode,
value);
if (!r) {
Logging::debug("TranslationUnitBase::control_write(): write failed.");
return pv::Tx_Result(pv::Tx_Data::TX_TRANSFAULT);
}
return pv::Tx_Result(pv::Tx_Data::TX_OK);
}
pv::Tx_Result TranslationUnitBase::control_debug_read(pv::ReadTransaction tx)
{
Logging::debug("TranslationUnitBase::control_debug_read([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
return this->control_read(tx);
}
pv::Tx_Result TranslationUnitBase::control_debug_write(pv::WriteTransaction tx)
{
Logging::debug("TranslationUnitBase::control_debug_write([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
return this->control_write(tx);
}
/*
* -------------------------------------------------------------------------------------------
* Translations
* -------------------------------------------------------------------------------------------
*/
#include "pv/RemapRequest.h"
#define BASE_PAGE_SIZE 4096
/// basic translate functionality. This doesn't change anything in the remap request
/// the specific translation unit needs to override this function to provide the actual
/// remapping/translatino function here.
unsigned TranslationUnitBase::handle_remap(pv::RemapRequest &req, unsigned *unpredictable)
{
Logging::debug("TranslationUnitBase::handle_remap()");
lpaddr_t addr = req.getOriginalTransactionAddress();
size_t size = 1; // can we get the size somehow?
// check the supported ranges
if (addr < this->_inaddr_range_min || addr + size > this->_inaddr_range_max) {
Logging::error("TranslationUnitBase::handle_remap - request 0x%lx out of supported range "
"0x%lx..0x%lx",
addr, this->_inaddr_range_min, this->_inaddr_range_max);
return 1;
}
const pv::TransactionAttributes *attr = req.getTransactionAttributes();
access_mode_t mode;
if (attr->isNormalWorld()) {
if (attr->isPrivileged()) {
if (req.isRead()) {
mode = ACCESS_MODE_NOSEC_READ;
} else {
mode = ACCESS_MODE_NOSEC_WRITE;
}
} else {
if (req.isRead()) {
mode = ACCESS_MODE_USER_READ;
} else {
mode = ACCESS_MODE_USER_WRITE;
}
}
} else {
if (req.isRead()) {
mode = ACCESS_MODE_SEC_READ;
} else {
mode = ACCESS_MODE_SEC_WRITE;
}
}
// set the translation to be valid only once, to get retriggered
req.setOnceOnly();
lpaddr_t dst;
bool r = this->do_translate(addr, size, mode, &dst);
if (!r) {
Logging::info("TranslationUnitBase::handle_remap() - translation failed");
return 1;
}
Logging::debug("TranslationUnitBase::handle_remap() - translated 0x%lx -> 0x%lx", addr, dst);
// set the remap base
req.setRemapPageBase(dst & ~(BASE_PAGE_SIZE - 1));
return 0;
}
DVM::error_response_t TranslationUnitBase::handle_dvm_msg(DVM::Message *msg, bool ptw)
{
return DVM::error_response_t(DVM::error_response_t::ok);
}
/*
* -------------------------------------------------------------------------------------------
* Translation table walk
* -------------------------------------------------------------------------------------------
*/
bool TranslationUnitBase::translation_table_walk(lpaddr_t addr, uint8_t width, uint64_t *data)
{
pv::AccessWidth access_width;
Logging::debug("TranslationUnitBase::translation_table_walk(0x%lx, %u)", addr, width);
if (this->_ttw_pvbus == nullptr) {
Logging::error("TranslationUnitBase::translation_table_walk - no page walker set!");
return false;
}
if (width == 64) {
access_width = pv::ACCESS_64_BITS;
} else if (width == 32) {
access_width = pv::ACCESS_32_BITS;
} else {
return false;
}
// setup the buffer descriptor
pv::RandomContextTransactionGenerator::buffer_t bt
= pv::RandomContextTransactionGenerator::buffer_t(access_width, data, 1);
// setup the transaction attributes
pv::TransactionAttributes ta = pv::TransactionAttributes();
ta.setPTW(true);
// a new ACE request
pv::ACERequest req = pv::ACERequest();
// do the translaction
pv::Tx_Result res = this->_ttw_pvbus->read(&ta, &req, (pv::bus_addr_t)addr, &bt);
// return success
return res.isOK();
}
| 30.199336
| 100
| 0.562376
|
achreto
|
80c7e24023da4a49c724c3ff8c1fd74df3d9528b
| 5,459
|
cpp
|
C++
|
cppLib/code/dep/G3D/source/UprightFrame.cpp
|
DrYaling/ProcedureContentGenerationForUnity
|
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
|
[
"MIT"
] | 3
|
2019-05-14T07:19:59.000Z
|
2019-05-14T08:08:25.000Z
|
cppLib/code/dep/G3D/source/UprightFrame.cpp
|
DrYaling/ProcedureContentGenerationForUnity
|
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
|
[
"MIT"
] | null | null | null |
cppLib/code/dep/G3D/source/UprightFrame.cpp
|
DrYaling/ProcedureContentGenerationForUnity
|
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
|
[
"MIT"
] | 1
|
2018-08-08T07:39:16.000Z
|
2018-08-08T07:39:16.000Z
|
/**
\file UprightFrame.cpp
\maintainer Morgan McGuire, http://graphics.cs.williams.edu
*/
#include "G3D/UprightFrame.h"
#include "G3D/BinaryInput.h"
#include "G3D/BinaryOutput.h"
namespace G3D {
UprightFrame::UprightFrame(const CoordinateFrame& cframe) {
Vector3 look = cframe.lookVector();
yaw = (float)(G3D::pi() + atan2(look.x, look.z));
pitch = asin(look.y);
translation = cframe.translation;
}
UprightFrame::UprightFrame(const Any& any) {
any.verifyName("UprightFrame");
any.verifyType(Any::TABLE);
translation = any["translation"];
pitch = any["pitch"];
yaw = any["yaw"];
}
Any UprightFrame::toAny() const {
Any any(Any::TABLE, "UprightFrame");
any["translation"] = translation;
any["pitch"] = pitch;
any["yaw"] = yaw;
return any;
}
UprightFrame& UprightFrame::operator=(const Any& any) {
*this = UprightFrame(any);
return *this;
}
CoordinateFrame UprightFrame::toCoordinateFrame() const {
CoordinateFrame cframe;
Matrix3 P(Matrix3::fromAxisAngle(Vector3::unitX(), pitch));
Matrix3 Y(Matrix3::fromAxisAngle(Vector3::unitY(), yaw));
cframe.rotation = Y * P;
cframe.translation = translation;
return cframe;
}
UprightFrame UprightFrame::operator+(const UprightFrame& other) const {
return UprightFrame(translation + other.translation, pitch + other.pitch, yaw + other.yaw);
}
UprightFrame UprightFrame::operator*(const float k) const {
return UprightFrame(translation * k, pitch * k, yaw * k);
}
void UprightFrame::unwrapYaw(UprightFrame* a, int N) {
// Use the first point to establish the wrapping convention
for (int i = 1; i < N; ++i) {
const float prev = a[i - 1].yaw;
float& cur = a[i].yaw;
// No two angles should be more than pi (i.e., 180-degrees) apart.
if (abs(cur - prev) > G3D::pi()) {
// These angles must have wrapped at zero, causing them
// to be interpolated the long way.
// Find canonical [0, 2pi] versions of these numbers
float p = (float)wrap(prev, twoPi());
float c = (float)wrap(cur, twoPi());
// Find the difference -pi < diff < pi between the current and previous values
float diff = c - p;
if (diff < -G3D::pi()) {
diff += (float)twoPi();
} else if (diff > G3D::pi()) {
diff -= (float)twoPi();
}
// Offset the current from the previous by the difference
// between them.
cur = prev + diff;
}
}
}
void UprightFrame::serialize(class BinaryOutput& b) const {
translation.serialize(b);
b.writeFloat32(pitch);
b.writeFloat32(yaw);
}
void UprightFrame::deserialize(class BinaryInput& b) {
translation.deserialize(b);
pitch = b.readFloat32();
yaw = b.readFloat32();
}
///////////////////////////////////////////////////////////////////////////////////////////
UprightSpline::UprightSpline() : Spline<UprightFrame>() {
}
UprightSpline::UprightSpline(const Any& any) {
any.verifyName("UprightSpline");
any.verifyType(Any::TABLE);
extrapolationMode = any["extrapolationMode"];
const Any& controlsAny = any["control"];
controlsAny.verifyType(Any::ARRAY);
control.resize(controlsAny.length());
for (int controlIndex = 0; controlIndex < control.length(); ++controlIndex) {
control[controlIndex] = controlsAny[controlIndex];
}
const Any& timesAny = any["time"];
timesAny.verifyType(Any::ARRAY);
time.resize(timesAny.length());
for (int timeIndex = 0; timeIndex < time.length(); ++timeIndex) {
time[timeIndex] = timesAny[timeIndex];
}
}
Any UprightSpline::toAny(const std::string& myName) const {
Any any(Any::TABLE, myName);
any["extrapolationMode"] = extrapolationMode;
Any controlsAny(Any::ARRAY);
for (int controlIndex = 0; controlIndex < control.length(); ++controlIndex) {
controlsAny.append(control[controlIndex]);
}
any["control"] = controlsAny;
Any timesAny(Any::ARRAY);
for (int timeIndex = 0; timeIndex < time.length(); ++timeIndex) {
timesAny.append(Any(time[timeIndex]));
}
any["time"] = timesAny;
return any;
}
Any UprightSpline::toAny() const {
return toAny("UprightSpline");
}
UprightSpline& UprightSpline::operator=(const Any& any) {
*this = UprightSpline(any);
return *this;
}
void UprightSpline::serialize(class BinaryOutput& b) const {
b.writeInt32(extrapolationMode);
b.writeInt32(control.size());
for (int i = 0; i < control.size(); ++i) {
control[i].serialize(b);
}
b.writeInt32(time.size());
for (int i = 0; i < time.size(); ++i) {
b.writeFloat32(time[i]);
}
}
void UprightSpline::deserialize(class BinaryInput& b) {
extrapolationMode = SplineExtrapolationMode(b.readInt32());
control.resize(b.readInt32());
for (int i = 0; i < control.size(); ++i) {
control[i].deserialize(b);
}
if (b.hasMore()) {
time.resize(b.readInt32());
for (int i = 0; i < time.size(); ++i) {
time[i] = b.readFloat32();
}
debugAssert(time.size() == control.size());
} else {
// Import legacy path
time.resize(control.size());
for (int i = 0; i < time.size(); ++i) {
time[i] = (float)i;
}
}
}
}
| 25.390698
| 95
| 0.599744
|
DrYaling
|
80c7ebb1fcac1999f8ba5ef57dd73c1c11ecc57f
| 68,985
|
cpp
|
C++
|
src/drivers/mcr3.cpp
|
pierrelouys/PSP-MAME4ALL
|
54374b0579b7e2377f015ac155d8f519addfaa1a
|
[
"Unlicense"
] | 1
|
2021-01-25T20:16:33.000Z
|
2021-01-25T20:16:33.000Z
|
src/drivers/mcr3.cpp
|
pierrelouys/PSP-MAME4ALL
|
54374b0579b7e2377f015ac155d8f519addfaa1a
|
[
"Unlicense"
] | 1
|
2021-05-24T20:28:35.000Z
|
2021-05-25T14:44:54.000Z
|
src/drivers/mcr3.cpp
|
PSP-Archive/PSP-MAME4ALL
|
54374b0579b7e2377f015ac155d8f519addfaa1a
|
[
"Unlicense"
] | null | null | null |
/***************************************************************************
MCR/III memory map (preliminary)
0000-3fff ROM 0
4000-7fff ROM 1
8000-cfff ROM 2
c000-dfff ROM 3
e000-e7ff RAM
e800-e9ff spriteram
f000-f7ff tiles
f800-f8ff palette ram
IN0
bit 0 : left coin
bit 1 : right coin
bit 2 : 1 player
bit 3 : 2 player
bit 4 : ?
bit 5 : tilt
bit 6 : ?
bit 7 : service
IN1,IN2
joystick, sometimes spinner
IN3
Usually dipswitches. Most game configuration is really done by holding down
the service key (F2) during the startup self-test.
IN4
extra inputs; also used to control sound for external boards
The MCR/III games used a plethora of sound boards; all of them seem to do
roughly the same thing. We have:
* Chip Squeak Deluxe (CSD) - used for music on Spy Hunter
* Turbo Chip Squeak (TCS) - used for all sound effects on Sarge
* Sounds Good (SG) - used for all sound effects on Rampage and Xenophobe
* Squawk & Talk (SNT) - used for speech on Discs of Tron
Known issues:
* Destruction Derby has no sound
* Destruction Derby player 3 and 4 steering wheels are not properly muxed
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "machine/6821pia.h"
void mcr3_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void mcr3_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void mcr3_videoram_w(int offset,int data);
void mcr3_paletteram_w(int offset,int data);
void rampage_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void spyhunt_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
int spyhunt_vh_start(void);
void spyhunt_vh_stop(void);
void spyhunt_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
extern unsigned char *spyhunt_alpharam;
extern int spyhunt_alpharam_size;
int crater_vh_start(void);
void mcr_init_machine(void);
int mcr_interrupt(void);
int dotron_interrupt(void);
extern int mcr_loadnvram;
void mcr_writeport(int port,int value);
int mcr_readport(int port);
void mcr_soundstatus_w (int offset,int data);
int mcr_soundlatch_r (int offset);
void mcr_pia_1_w (int offset, int data);
int mcr_pia_1_r (int offset);
int destderb_port_r(int offset);
void spyhunt_init_machine(void);
int spyhunt_port_1_r(int offset);
int spyhunt_port_2_r(int offset);
void spyhunt_writeport(int port,int value);
void rampage_init_machine(void);
void rampage_writeport(int port,int value);
void maxrpm_writeport(int port,int value);
int maxrpm_IN1_r(int offset);
int maxrpm_IN2_r(int offset);
void sarge_init_machine(void);
int sarge_IN1_r(int offset);
int sarge_IN2_r(int offset);
void sarge_writeport(int port,int value);
int dotron_vh_start(void);
void dotron_vh_stop(void);
int dotron_IN2_r(int offset);
void dotron_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void dotron_init_machine(void);
void dotron_writeport(int port,int value);
void crater_writeport(int port,int value);
/***************************************************************************
Memory maps
***************************************************************************/
static struct MemoryReadAddress readmem[] =
{
{ 0x0000, 0xdfff, MRA_ROM },
{ 0xe000, 0xe9ff, MRA_RAM },
{ 0xf000, 0xf7ff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem[] =
{
{ 0xe000, 0xe7ff, MWA_RAM },
{ 0x0000, 0xdfff, MWA_ROM },
{ 0xe800, 0xe9ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf000, 0xf7ff, mcr3_videoram_w, &videoram, &videoram_size },
{ 0xf800, 0xf8ff, mcr3_paletteram_w, &paletteram },
{ -1 } /* end of table */
};
static struct MemoryReadAddress rampage_readmem[] =
{
{ 0x0000, 0xdfff, MRA_ROM },
{ 0xe000, 0xebff, MRA_RAM },
{ 0xf000, 0xf7ff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress rampage_writemem[] =
{
{ 0xe000, 0xe7ff, MWA_RAM },
{ 0x0000, 0xdfff, MWA_ROM },
{ 0xe800, 0xebff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf000, 0xf7ff, mcr3_videoram_w, &videoram, &videoram_size },
{ 0xec00, 0xecff, mcr3_paletteram_w, &paletteram },
{ -1 } /* end of table */
};
static struct MemoryReadAddress spyhunt_readmem[] =
{
{ 0x0000, 0xdfff, MRA_ROM },
{ 0xe000, 0xebff, MRA_RAM },
{ 0xf000, 0xffff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress spyhunt_writemem[] =
{
{ 0xf000, 0xf7ff, MWA_RAM },
{ 0xe800, 0xebff, MWA_RAM, &spyhunt_alpharam, &spyhunt_alpharam_size },
{ 0xe000, 0xe7ff, videoram_w, &videoram, &videoram_size },
{ 0xf800, 0xf9ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xfa00, 0xfaff, mcr3_paletteram_w, &paletteram },
{ 0x0000, 0xdfff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sound_readmem[] =
{
{ 0x8000, 0x83ff, MRA_RAM },
{ 0x9000, 0x9003, mcr_soundlatch_r },
{ 0xa001, 0xa001, AY8910_read_port_0_r },
{ 0xb001, 0xb001, AY8910_read_port_1_r },
{ 0xf000, 0xf000, input_port_5_r },
{ 0xe000, 0xe000, MRA_NOP },
{ 0x0000, 0x3fff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress sound_writemem[] =
{
{ 0x8000, 0x83ff, MWA_RAM },
{ 0xa000, 0xa000, AY8910_control_port_0_w },
{ 0xa002, 0xa002, AY8910_write_port_0_w },
{ 0xb000, 0xb000, AY8910_control_port_1_w },
{ 0xb002, 0xb002, AY8910_write_port_1_w },
{ 0xc000, 0xc000, mcr_soundstatus_w },
{ 0xe000, 0xe000, MWA_NOP },
{ 0x0000, 0x3fff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress timber_sound_readmem[] =
{
{ 0x3000, 0x3fff, MRA_RAM },
{ 0x8000, 0x83ff, MRA_RAM },
{ 0x9000, 0x9003, mcr_soundlatch_r },
{ 0xa001, 0xa001, AY8910_read_port_0_r },
{ 0xb001, 0xb001, AY8910_read_port_1_r },
{ 0xf000, 0xf000, input_port_5_r },
{ 0xe000, 0xe000, MRA_NOP },
{ 0x0000, 0x2fff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress timber_sound_writemem[] =
{
{ 0x3000, 0x3fff, MWA_RAM },
{ 0x8000, 0x83ff, MWA_RAM },
{ 0xa000, 0xa000, AY8910_control_port_0_w },
{ 0xa002, 0xa002, AY8910_write_port_0_w },
{ 0xb000, 0xb000, AY8910_control_port_1_w },
{ 0xb002, 0xb002, AY8910_write_port_1_w },
{ 0xc000, 0xc000, mcr_soundstatus_w },
{ 0xe000, 0xe000, MWA_NOP },
{ 0x0000, 0x2fff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress csd_readmem[] =
{
{ 0x000000, 0x007fff, MRA_ROM },
{ 0x018000, 0x018007, mcr_pia_1_r },
{ 0x01c000, 0x01cfff, MRA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress csd_writemem[] =
{
{ 0x000000, 0x007fff, MWA_ROM },
{ 0x018000, 0x018007, mcr_pia_1_w },
{ 0x01c000, 0x01cfff, MWA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sg_readmem[] =
{
{ 0x000000, 0x01ffff, MRA_ROM },
{ 0x060000, 0x060007, mcr_pia_1_r },
{ 0x070000, 0x070fff, MRA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress sg_writemem[] =
{
{ 0x000000, 0x01ffff, MWA_ROM },
{ 0x060000, 0x060007, mcr_pia_1_w },
{ 0x070000, 0x070fff, MWA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryReadAddress snt_readmem[] =
{
{ 0x0000, 0x007f, MRA_RAM },
{ 0x0080, 0x0083, pia_1_r },
{ 0x0090, 0x0093, pia_2_r },
{ 0xd000, 0xffff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress snt_writemem[] =
{
{ 0x0000, 0x007f, MWA_RAM },
{ 0x0080, 0x0083, pia_1_w },
{ 0x0090, 0x0093, pia_2_w },
{ 0xd000, 0xffff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress tcs_readmem[] =
{
{ 0x0000, 0x03ff, MRA_RAM },
{ 0x6000, 0x6003, pia_1_r },
{ 0xc000, 0xffff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress tcs_writemem[] =
{
{ 0x0000, 0x03ff, MWA_RAM },
{ 0x6000, 0x6003, pia_1_w },
{ 0xc000, 0xffff, MWA_ROM },
{ -1 } /* end of table */
};
/***************************************************************************
Input port definitions
***************************************************************************/
INPUT_PORTS_START( tapper_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0xe0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0xe0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x04, 0x04, "Demo Sounds", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x40, 0x40, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x40, "Upright" )
PORT_DIPSETTING( 0x00, "Cocktail" )
PORT_BIT( 0xbb, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( dotron_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
#ifdef GP2X
PORT_ANALOGX( 0xff, 0x00, IPT_DIAL | IPF_REVERSE, 5, 0, 0, 0, 0, 0, OSD_JOY_FIRE5, OSD_JOY_FIRE6, 16 )
#else
PORT_ANALOGX( 0xff, 0x00, IPT_DIAL | IPF_REVERSE, 50, 0, 0, 0, OSD_KEY_Z, OSD_KEY_X, 0, 0, 4 )
#endif
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BITX(0x10, IP_ACTIVE_LOW, IPT_BUTTON3, "Aim Down", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX(0x20, IP_ACTIVE_LOW, IPT_BUTTON4, "Aim Up", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON2 )
/* we default to Environmental otherwise speech is disabled */
PORT_DIPNAME( 0x80, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x80, "Upright" )
PORT_DIPSETTING( 0x00, "Environmental" )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x01, 0x01, "Coin Meters", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "1" )
PORT_DIPSETTING( 0x00, "2" )
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* fake port to make aiming up & down easier */
PORT_ANALOG ( 0xff, 0x00, IPT_TRACKBALL_Y, 100, 0, 0, 0 )
INPUT_PORTS_END
INPUT_PORTS_START( destderb_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x20, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 -- the high 6 bits contain the sterring wheel value */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_ANALOG ( 0xfc, 0x00, IPT_DIAL | IPF_REVERSE, 50, 0, 0, 0 )
PORT_START /* IN2 -- the high 6 bits contain the sterring wheel value */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_ANALOG ( 0xfc, 0x00, IPT_DIAL | IPF_REVERSE, 50, 0, 0, 0 )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x01, 0x01, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "2P Upright" )
PORT_DIPSETTING( 0x00, "4P Upright" )
PORT_DIPNAME( 0x02, 0x02, "Difficulty", IP_KEY_NONE )
PORT_DIPSETTING( 0x02, "Normal" )
PORT_DIPSETTING( 0x00, "Harder" )
PORT_DIPNAME( 0x04, 0x04, "Free Play", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x08, 0x08, "Reward Screen", IP_KEY_NONE )
PORT_DIPSETTING( 0x08, "Expanded" )
PORT_DIPSETTING( 0x00, "Limited" )
PORT_DIPNAME( 0x30, 0x30, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x20, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x00, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x30, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x10, "1 Coin/2 Credits" )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN4 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER3 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER4 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER4 )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( timber_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x04, 0x04, "Demo Sounds", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( rampage_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_TILT )
PORT_BITX( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x20, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x03, 0x03, "Difficulty", IP_KEY_NONE )
PORT_DIPSETTING( 0x02, "Easy" )
PORT_DIPSETTING( 0x03, "Normal" )
PORT_DIPSETTING( 0x01, "Hard" )
PORT_DIPSETTING( 0x00, "Free Play" )
PORT_DIPNAME( 0x04, 0x04, "Score Option", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Keep score when continuing" )
PORT_DIPSETTING( 0x00, "Lose score when continuing" )
PORT_DIPNAME( 0x08, 0x08, "Coin A", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x08, "1 Coin/1 Credit" )
PORT_DIPNAME( 0x70, 0x70, "Coin B", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "3 Coins/1 Credit" )
PORT_DIPSETTING( 0x10, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x70, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x60, "1 Coin/2 Credits" )
PORT_DIPSETTING( 0x50, "1 Coin/3 Credits" )
PORT_DIPSETTING( 0x40, "1 Coin/4 Credits" )
PORT_DIPSETTING( 0x30, "1 Coin/5 Credits" )
PORT_DIPSETTING( 0x20, "1 Coin/6 Credits" )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Rack Advance", OSD_KEY_F1, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN4 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER3 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( maxrpm_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 | IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON4 | IPF_PLAYER2 )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x08, 0x08, "Free Play", IP_KEY_NONE )
PORT_DIPSETTING( 0x08, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x30, 0x30, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x20, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x30, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x10, "1 Coin/2 Credits" )
/* 0x00 says 2 Coins/2 Credits in service mode, but gives 1 Coin/1 Credit */
PORT_BIT( 0xc7, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* new fake for acceleration */
PORT_ANALOGX( 0xff, 0x30, IPT_AD_STICK_Y | IPF_PLAYER2, 100, 0, 0x30, 0xff, OSD_KEY_UP, OSD_KEY_DOWN, IPT_JOYSTICK_UP, IPT_JOYSTICK_DOWN, 1 )
PORT_START /* new fake for acceleration */
PORT_ANALOGX( 0xff, 0x30, IPT_AD_STICK_Y | IPF_PLAYER1, 100, 0, 0x30, 0xff, OSD_KEY_UP, OSD_KEY_DOWN, IPT_JOYSTICK_UP, IPT_JOYSTICK_DOWN, 1 )
PORT_START /* new fake for steering */
PORT_ANALOGX( 0xff, 0x74, IPT_AD_STICK_X | IPF_PLAYER2 | IPF_REVERSE, 80, 0, 0x34, 0xb4, OSD_KEY_LEFT, OSD_KEY_RIGHT, IPT_JOYSTICK_LEFT, IPT_JOYSTICK_RIGHT, 2 )
PORT_START /* new fake for steering */
PORT_ANALOGX( 0xff, 0x74, IPT_AD_STICK_X | IPF_PLAYER1 | IPF_REVERSE, 80, 0, 0x34, 0xb4, OSD_KEY_LEFT, OSD_KEY_RIGHT, IPT_JOYSTICK_LEFT, IPT_JOYSTICK_RIGHT, 2 )
PORT_START /* fake for shifting */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( sarge_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_TILT )
PORT_BITX( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x20, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_UP | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_DOWN | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_UP | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_DOWN | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x08, 0x08, "Free Play", IP_KEY_NONE )
PORT_DIPSETTING( 0x08, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x30, 0x30, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x20, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x30, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x10, "1 Coin/2 Credits" )
/* 0x00 says 2 Coins/2 Credits in service mode, but gives 1 Coin/1 Credit */
PORT_BIT( 0xc7, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* fake port for single joystick control */
/* This fake port is handled via sarge_IN1_r and sarge_IN2_r */
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
INPUT_PORTS_END
INPUT_PORTS_START( spyhunt_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x10, IP_ACTIVE_LOW, IPT_BUTTON6 | IPF_TOGGLE, "Gear Shift", OSD_KEY_ENTER, IP_JOY_DEFAULT, 0 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_SERVICE )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_KEY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 -- various buttons, low 5 bits */
PORT_BITX( 0x01, IP_ACTIVE_LOW, IPT_BUTTON4, "Oil Slick", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5, "Missiles", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3, "Weapon Truck", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2, "Smoke Screen", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1, "Machine Guns", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BIT( 0x60, IP_ACTIVE_HIGH, IPT_UNUSED ) /* CSD status bits */
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 -- actually not used at all, but read as a trakport */
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches -- low 4 bits only */
PORT_DIPNAME( 0x01, 0x01, "Game Timer", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "1:00" )
PORT_DIPSETTING( 0x01, "1:30" )
PORT_DIPNAME( 0x02, 0x02, "Demo Sounds", IP_KEY_NONE )
PORT_DIPSETTING( 0x02, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* new fake for acceleration */
PORT_ANALOGX( 0xff, 0x30, IPT_AD_STICK_Y | IPF_REVERSE, 100, 0, 0x30, 0xff, OSD_KEY_UP, OSD_KEY_DOWN, OSD_JOY_UP, OSD_JOY_DOWN, 1 )
PORT_START /* new fake for steering */
PORT_ANALOGX( 0xff, 0x74, IPT_AD_STICK_X | IPF_CENTER, 80, 0, 0x34, 0xb4, OSD_KEY_LEFT, OSD_KEY_RIGHT, OSD_JOY_LEFT, OSD_JOY_RIGHT, 2 )
INPUT_PORTS_END
INPUT_PORTS_START( crater_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_ANALOGX( 0xff, 0x00, IPT_DIAL | IPF_REVERSE, 25, 0, 0, 0, OSD_KEY_Z, OSD_KEY_X, 0, 0, 4 )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
static struct IOReadPort readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, input_port_1_r },
{ 0x02, 0x02, input_port_2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort dt_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, input_port_1_r },
{ 0x02, 0x02, dotron_IN2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort destderb_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x02, destderb_port_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort maxrpm_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, maxrpm_IN1_r },
{ 0x02, 0x02, maxrpm_IN2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort sarge_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, sarge_IN1_r },
{ 0x02, 0x02, sarge_IN2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort spyhunt_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, spyhunt_port_1_r },
{ 0x02, 0x02, spyhunt_port_2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOWritePort writeport[] =
{
{ 0, 0xff, mcr_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort sh_writeport[] =
{
{ 0, 0xff, spyhunt_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort cr_writeport[] =
{
{ 0, 0xff, crater_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort rm_writeport[] =
{
{ 0, 0xff, rampage_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort mr_writeport[] =
{
{ 0, 0xff, maxrpm_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort sa_writeport[] =
{
{ 0, 0xff, sarge_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort dt_writeport[] =
{
{ 0, 0xff, dotron_writeport },
{ -1 } /* end of table */
};
/***************************************************************************
Graphics layouts
***************************************************************************/
/* generic character layouts */
/* note that characters are half the resolution of sprites in each direction, so we generate
them at double size */
/* 1024 characters; used by tapper, timber, rampage */
static struct GfxLayout mcr3_charlayout_1024 =
{
16, 16,
1024,
4,
{ 1024*16*8, 1024*16*8+1, 0, 1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14 },
{ 0, 0, 2*8, 2*8, 4*8, 4*8, 6*8, 6*8, 8*8, 8*8, 10*8, 10*8, 12*8, 12*8, 14*8, 14*8 },
16*8
};
/* 512 characters; used by dotron, destderb */
static struct GfxLayout mcr3_charlayout_512 =
{
16, 16,
512,
4,
{ 512*16*8, 512*16*8+1, 0, 1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14 },
{ 0, 0, 2*8, 2*8, 4*8, 4*8, 6*8, 6*8, 8*8, 8*8, 10*8, 10*8, 12*8, 12*8, 14*8, 14*8 },
16*8
};
/* generic sprite layouts */
/* 512 sprites; used by rampage */
#define X (512*128*8)
#define Y (2*X)
#define Z (3*X)
static struct GfxLayout mcr3_spritelayout_512 =
{
32,32,
512,
4,
{ 0, 1, 2, 3 },
{ Z+0, Z+4, Y+0, Y+4, X+0, X+4, 0, 4, Z+8, Z+12, Y+8, Y+12, X+8, X+12, 8, 12,
Z+16, Z+20, Y+16, Y+20, X+16, X+20, 16, 20, Z+24, Z+28, Y+24, Y+28,
X+24, X+28, 24, 28 },
{ 0, 32, 32*2, 32*3, 32*4, 32*5, 32*6, 32*7, 32*8, 32*9, 32*10, 32*11,
32*12, 32*13, 32*14, 32*15, 32*16, 32*17, 32*18, 32*19, 32*20, 32*21,
32*22, 32*23, 32*24, 32*25, 32*26, 32*27, 32*28, 32*29, 32*30, 32*31 },
128*8
};
#undef X
#undef Y
#undef Z
/* 256 sprites; used by tapper, timber, destderb, spyhunt */
#define X (256*128*8)
#define Y (2*X)
#define Z (3*X)
static struct GfxLayout mcr3_spritelayout_256 =
{
32,32,
256,
4,
{ 0, 1, 2, 3 },
{ Z+0, Z+4, Y+0, Y+4, X+0, X+4, 0, 4, Z+8, Z+12, Y+8, Y+12, X+8, X+12, 8, 12,
Z+16, Z+20, Y+16, Y+20, X+16, X+20, 16, 20, Z+24, Z+28, Y+24, Y+28,
X+24, X+28, 24, 28 },
{ 0, 32, 32*2, 32*3, 32*4, 32*5, 32*6, 32*7, 32*8, 32*9, 32*10, 32*11,
32*12, 32*13, 32*14, 32*15, 32*16, 32*17, 32*18, 32*19, 32*20, 32*21,
32*22, 32*23, 32*24, 32*25, 32*26, 32*27, 32*28, 32*29, 32*30, 32*31 },
128*8
};
#undef X
#undef Y
#undef Z
/* 128 sprites; used by dotron */
#define X (128*128*8)
#define Y (2*X)
#define Z (3*X)
static struct GfxLayout mcr3_spritelayout_128 =
{
32,32,
128,
4,
{ 0, 1, 2, 3 },
{ Z+0, Z+4, Y+0, Y+4, X+0, X+4, 0, 4, Z+8, Z+12, Y+8, Y+12, X+8, X+12, 8, 12,
Z+16, Z+20, Y+16, Y+20, X+16, X+20, 16, 20, Z+24, Z+28, Y+24, Y+28,
X+24, X+28, 24, 28 },
{ 0, 32, 32*2, 32*3, 32*4, 32*5, 32*6, 32*7, 32*8, 32*9, 32*10, 32*11,
32*12, 32*13, 32*14, 32*15, 32*16, 32*17, 32*18, 32*19, 32*20, 32*21,
32*22, 32*23, 32*24, 32*25, 32*26, 32*27, 32*28, 32*29, 32*30, 32*31 },
128*8
};
#undef X
#undef Y
#undef Z
/***************************** spyhunt layouts **********************************/
/* 128 32x16 characters; used by spyhunt */
static struct GfxLayout spyhunt_charlayout_128 =
{
32, 32, /* we pixel double and split in half */
128,
4,
{ 0, 1, 128*128*8, 128*128*8+1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14, 16, 16, 18, 18, 20, 20, 22, 22, 24, 24, 26, 26, 28, 28, 30, 30 },
{ 0, 0, 8*8, 8*8, 16*8, 16*8, 24*8, 24*8, 32*8, 32*8, 40*8, 40*8, 48*8, 48*8, 56*8, 56*8,
64*8, 64*8, 72*8, 72*8, 80*8, 80*8, 88*8, 88*8, 96*8, 96*8, 104*8, 104*8, 112*8, 112*8, 120*8, 120*8 },
128*8
};
/* of course, Spy Hunter just *had* to be different than everyone else... */
static struct GfxLayout spyhunt_alphalayout =
{
16, 16,
256,
2,
{ 0, 1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14 },
{ 0, 0, 2*8, 2*8, 4*8, 4*8, 6*8, 6*8, 8*8, 8*8, 10*8, 10*8, 12*8, 12*8, 14*8, 14*8 },
16*8
};
static struct GfxDecodeInfo tapper_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_1024, 0, 4 },
{ 1, 0x8000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo dotron_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_512, 0, 4 },
{ 1, 0x4000, &mcr3_spritelayout_128, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo destderb_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_512, 0, 4 },
{ 1, 0x4000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo timber_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_1024, 0, 4 },
{ 1, 0x8000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo rampage_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_1024, 0, 4 },
{ 1, 0x8000, &mcr3_spritelayout_512, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo sarge_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_512, 0, 4 },
{ 1, 0x4000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo spyhunt_gfxdecodeinfo[] =
{
{ 1, 0x0000, &spyhunt_charlayout_128, 1*16, 1 }, /* top half */
{ 1, 0x0004, &spyhunt_charlayout_128, 1*16, 1 }, /* bottom half */
{ 1, 0x8000, &mcr3_spritelayout_256, 0*16, 1 },
{ 1, 0x28000, &spyhunt_alphalayout, 8*16, 1 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo crater_gfxdecodeinfo[] =
{
{ 1, 0x0000, &spyhunt_charlayout_128, 3*16, 1 }, /* top half */
{ 1, 0x0004, &spyhunt_charlayout_128, 3*16, 1 }, /* bottom half */
{ 1, 0x8000, &mcr3_spritelayout_256, 0*16, 4 },
{ 1, 0x28000, &spyhunt_alphalayout, 8*16, 1 },
{ -1 } /* end of array */
};
/***************************************************************************
Sound interfaces
***************************************************************************/
static struct AY8910interface ay8910_interface =
{
2, /* 2 chips */
2000000, /* 2 MHz ?? */
{ 255, 255 },
{ 0 },
{ 0 },
{ 0 },
{ 0 }
};
static struct DACinterface dac_interface =
{
1,
{ 255 }
};
static struct TMS5220interface tms5220_interface =
{
640000,
192,
0
};
/***************************************************************************
Machine drivers
***************************************************************************/
static struct MachineDriver tapper_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,readport,writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
tapper_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
mcr3_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
static struct MachineDriver dotron_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,dt_readport,dt_writeport,
dotron_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
},
{
CPU_M6802 | CPU_AUDIO_CPU,
3580000/4, /* .8 Mhz */
3,
snt_readmem,snt_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
dotron_init_machine,
/* video hardware */
/* 32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 }, - MAB 09/30/98, changed the screen size for the backdrop */
800, 600, { 0, 800-1, 0, 600-1 },
dotron_gfxdecodeinfo,
254, 4*16, /* The extra colors are for the backdrop */
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
dotron_vh_start,
dotron_vh_stop,
dotron_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
},
{
SOUND_TMS5220,
&tms5220_interface
}
}
};
static struct MachineDriver destderb_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,destderb_readport,writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
destderb_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
mcr3_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
static struct MachineDriver timber_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,readport,writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
timber_sound_readmem,timber_sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
timber_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
mcr3_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
static struct MachineDriver rampage_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
rampage_readmem,rampage_writemem,readport,rm_writeport,
mcr_interrupt,1
},
{
CPU_M68000 | CPU_AUDIO_CPU,
7500000, /* 7.5 Mhz */
2,
sg_readmem,sg_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU synchronization is done via timers */
rampage_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
rampage_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
rampage_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver maxrpm_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
rampage_readmem,rampage_writemem,maxrpm_readport,mr_writeport,
mcr_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU synchronization is done via timers */
rampage_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
rampage_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
rampage_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver sarge_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
rampage_readmem,rampage_writemem,sarge_readport,sa_writeport,
mcr_interrupt,1
},
{
CPU_M6809 | CPU_AUDIO_CPU,
2250000, /* 2.25 Mhz??? */
2,
tcs_readmem,tcs_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU synchronization is done via timers */
sarge_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
sarge_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
rampage_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver spyhunt_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
spyhunt_readmem,spyhunt_writemem,spyhunt_readport,sh_writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
},
{
CPU_M68000 | CPU_AUDIO_CPU,
7500000, /* Actually 7.5 Mhz, but the 68000 emulator isn't accurate */
3,
csd_readmem,csd_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
spyhunt_init_machine,
/* video hardware */
31*16, 30*16, { 0, 31*16-1, 0, 30*16-1 },
spyhunt_gfxdecodeinfo,
8*16+4, 8*16+4,
spyhunt_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_MODIFIES_PALETTE,
0,
spyhunt_vh_start,
spyhunt_vh_stop,
spyhunt_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
},
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver crater_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
spyhunt_readmem,spyhunt_writemem,readport,cr_writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
30*16, 30*16, { 0, 30*16-1, 0, 30*16-1 },
crater_gfxdecodeinfo,
8*16+4, 8*16+4,
spyhunt_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_MODIFIES_PALETTE,
0,
crater_vh_start,
spyhunt_vh_stop,
spyhunt_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
/***************************************************************************
High score save/load
***************************************************************************/
static int mcr3_hiload(int addr, int len)
{
unsigned char *RAM = Machine->memory_region[0];
/* see if it's okay to load */
if (mcr_loadnvram)
{
void *f;
f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,0);
if (f)
{
osd_fread(f,&RAM[addr],len);
osd_fclose (f);
}
return 1;
}
else return 0; /* we can't load the hi scores yet */
}
static void mcr3_hisave(int addr, int len)
{
unsigned char *RAM = Machine->memory_region[0];
void *f;
f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,1);
if (f)
{
osd_fwrite(f,&RAM[addr],len);
osd_fclose (f);
}
}
static int tapper_hiload(void) { return mcr3_hiload(0xe000, 0x9d); }
static void tapper_hisave(void) { mcr3_hisave(0xe000, 0x9d); }
static int dotron_hiload(void) { return mcr3_hiload(0xe543, 0xac); }
static void dotron_hisave(void) { mcr3_hisave(0xe543, 0xac); }
static int destderb_hiload(void) { return mcr3_hiload(0xe4e6, 0x153); }
static void destderb_hisave(void) { mcr3_hisave(0xe4e6, 0x153); }
static int timber_hiload(void) { return mcr3_hiload(0xe000, 0x9f); }
static void timber_hisave(void) { mcr3_hisave(0xe000, 0x9f); }
static int rampage_hiload(void) { return mcr3_hiload(0xe631, 0x3f); }
static void rampage_hisave(void) { mcr3_hisave(0xe631, 0x3f); }
static int spyhunt_hiload(void) { return mcr3_hiload(0xf42b, 0xfb); }
static void spyhunt_hisave(void) { mcr3_hisave(0xf42b, 0xfb); }
static int crater_hiload(void) { return mcr3_hiload(0xf5fb, 0xa3); }
static void crater_hisave(void) { mcr3_hisave(0xf5fb, 0xa3); }
/***************************************************************************
ROM decoding
***************************************************************************/
static void spyhunt_decode (void)
{
unsigned char *RAM = Machine->memory_region[0];
/* some versions of rom 11d have the top and bottom 8k swapped; to enable us to work with either
a correct set or a swapped set (both of which pass the checksum!), we swap them here */
if (RAM[0xa000] != 0x0c)
{
int i;
unsigned char temp;
for (i = 0;i < 0x2000;i++)
{
temp = RAM[0xa000 + i];
RAM[0xa000 + i] = RAM[0xc000 + i];
RAM[0xc000 + i] = temp;
}
}
}
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( tapper_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "tappg0.bin", 0x0000, 0x4000, 0x127171d1 )
ROM_LOAD( "tappg1.bin", 0x4000, 0x4000, 0x9d6a47f7 )
ROM_LOAD( "tappg2.bin", 0x8000, 0x4000, 0x3a1f8778 )
ROM_LOAD( "tappg3.bin", 0xc000, 0x2000, 0xe8dcdaa4 )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "tapbg1.bin", 0x00000, 0x4000, 0x2a30238c )
ROM_LOAD( "tapbg0.bin", 0x04000, 0x4000, 0x394ab576 )
ROM_LOAD( "tapfg7.bin", 0x08000, 0x4000, 0x070b4c81 )
ROM_LOAD( "tapfg6.bin", 0x0c000, 0x4000, 0xa37aef36 )
ROM_LOAD( "tapfg5.bin", 0x10000, 0x4000, 0x800f7c8a )
ROM_LOAD( "tapfg4.bin", 0x14000, 0x4000, 0x32674ee6 )
ROM_LOAD( "tapfg3.bin", 0x18000, 0x4000, 0x818fffd4 )
ROM_LOAD( "tapfg2.bin", 0x1c000, 0x4000, 0x67e37690 )
ROM_LOAD( "tapfg1.bin", 0x20000, 0x4000, 0x32509011 )
ROM_LOAD( "tapfg0.bin", 0x24000, 0x4000, 0x8412c808 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "tapsnda7.bin", 0x0000, 0x1000, 0x0e8bb9d5 )
ROM_LOAD( "tapsnda8.bin", 0x1000, 0x1000, 0x0cf0e29b )
ROM_LOAD( "tapsnda9.bin", 0x2000, 0x1000, 0x31eb6dc6 )
ROM_LOAD( "tapsda10.bin", 0x3000, 0x1000, 0x01a9be6a )
ROM_END
ROM_START( sutapper_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "5791", 0x0000, 0x4000, 0x87119cc4 )
ROM_LOAD( "5792", 0x4000, 0x4000, 0x4c23ad89 )
ROM_LOAD( "5793", 0x8000, 0x4000, 0xfecbf683 )
ROM_LOAD( "5794", 0xc000, 0x2000, 0x5bdc1916 )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "5790", 0x00000, 0x4000, 0xac1558c1 )
ROM_LOAD( "5789", 0x04000, 0x4000, 0xfa66cab5 )
ROM_LOAD( "5801", 0x08000, 0x4000, 0xd70defa7 )
ROM_LOAD( "5802", 0x0c000, 0x4000, 0xd4f114b9 )
ROM_LOAD( "5799", 0x10000, 0x4000, 0x02c69432 )
ROM_LOAD( "5800", 0x14000, 0x4000, 0xebf1f948 )
ROM_LOAD( "5797", 0x18000, 0x4000, 0xf10a1d05 )
ROM_LOAD( "5798", 0x1c000, 0x4000, 0x614990cd )
ROM_LOAD( "5795", 0x20000, 0x4000, 0x5d987c92 )
ROM_LOAD( "5796", 0x24000, 0x4000, 0xde5700b4 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "5788", 0x0000, 0x1000, 0x5c1d0982 )
ROM_LOAD( "5787", 0x1000, 0x1000, 0x09e74ed8 )
ROM_LOAD( "5786", 0x2000, 0x1000, 0xc3e98284 )
ROM_LOAD( "5785", 0x3000, 0x1000, 0xced2fd47 )
ROM_END
ROM_START( rbtapper_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "rbtpg0.bin", 0x0000, 0x4000, 0x20b9adf4 )
ROM_LOAD( "rbtpg1.bin", 0x4000, 0x4000, 0x87e616c2 )
ROM_LOAD( "rbtpg2.bin", 0x8000, 0x4000, 0x0b332c97 )
ROM_LOAD( "rbtpg3.bin", 0xc000, 0x2000, 0x698c06f2 )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "rbtbg1.bin", 0x00000, 0x4000, 0x44dfa483 )
ROM_LOAD( "rbtbg0.bin", 0x04000, 0x4000, 0x510b13de )
ROM_LOAD( "rbtfg7.bin", 0x08000, 0x4000, 0x8dbf0c36 )
ROM_LOAD( "rbtfg6.bin", 0x0c000, 0x4000, 0x441201a0 )
ROM_LOAD( "rbtfg5.bin", 0x10000, 0x4000, 0x9eeca46e )
ROM_LOAD( "rbtfg4.bin", 0x14000, 0x4000, 0x8c79e7d7 )
ROM_LOAD( "rbtfg3.bin", 0x18000, 0x4000, 0x3e725e77 )
ROM_LOAD( "rbtfg2.bin", 0x1c000, 0x4000, 0x4ee8b624 )
ROM_LOAD( "rbtfg1.bin", 0x20000, 0x4000, 0x1c0b8791 )
ROM_LOAD( "rbtfg0.bin", 0x24000, 0x4000, 0xe99f6018 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "rbtsnda7.bin", 0x0000, 0x1000, 0x5c1d0982 )
ROM_LOAD( "rbtsnda8.bin", 0x1000, 0x1000, 0x09e74ed8 )
ROM_LOAD( "rbtsnda9.bin", 0x2000, 0x1000, 0xc3e98284 )
ROM_LOAD( "rbtsda10.bin", 0x3000, 0x1000, 0xced2fd47 )
ROM_END
struct GameDriver tapper_driver =
{
__FILE__,
0,
"tapper",
"Tapper (Budweiser)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria",
0,
&tapper_machine_driver,
0,
tapper_rom,
0, 0,
0,
0, /* sound_prom */
tapper_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
tapper_hiload, tapper_hisave
};
struct GameDriver sutapper_driver =
{
__FILE__,
&tapper_driver,
"sutapper",
"Tapper (Suntory)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria",
0,
&tapper_machine_driver,
0,
sutapper_rom,
0, 0,
0,
0, /* sound_prom */
tapper_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
tapper_hiload, tapper_hisave
};
struct GameDriver rbtapper_driver =
{
__FILE__,
&tapper_driver,
"rbtapper",
"Tapper (Root Beer)",
"1984",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria",
0,
&tapper_machine_driver,
0,
rbtapper_rom,
0, 0,
0,
0, /* sound_prom */
tapper_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
tapper_hiload, tapper_hisave
};
ROM_START( dotron_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "loc-pg0.1c", 0x0000, 0x4000, 0xba0da15f )
ROM_LOAD( "loc-pg1.2c", 0x4000, 0x4000, 0xdc300191 )
ROM_LOAD( "loc-pg2.3c", 0x8000, 0x4000, 0xab0b3800 )
ROM_LOAD( "loc-pg1.4c", 0xc000, 0x2000, 0xf98c9f8e )
ROM_REGION_DISPOSE(0x14000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "loc-bg2.6f", 0x00000, 0x2000, 0x40167124 )
ROM_LOAD( "loc-bg1.5f", 0x02000, 0x2000, 0xbb2d7a5d )
ROM_LOAD( "loc-a.cp0", 0x04000, 0x2000, 0xb35f5374 )
ROM_LOAD( "loc-b.cp9", 0x06000, 0x2000, 0x565a5c48 )
ROM_LOAD( "loc-c.cp8", 0x08000, 0x2000, 0xef45d146 )
ROM_LOAD( "loc-d.cp7", 0x0a000, 0x2000, 0x5e8a3ef3 )
ROM_LOAD( "loc-e.cp6", 0x0c000, 0x2000, 0xce957f1a )
ROM_LOAD( "loc-f.cp5", 0x0e000, 0x2000, 0xd26053ce )
ROM_LOAD( "loc-g.cp4", 0x10000, 0x2000, 0x57a2b1ff )
ROM_LOAD( "loc-h.cp3", 0x12000, 0x2000, 0x3bb4d475 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "sound0.a7", 0x0000, 0x1000, 0x6d39bf19 )
ROM_LOAD( "sound1.a8", 0x1000, 0x1000, 0xac872e1d )
ROM_LOAD( "sound2.a9", 0x2000, 0x1000, 0xe8ef6519 )
ROM_LOAD( "sound3.a10", 0x3000, 0x1000, 0x6b5aeb02 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "pre.u3", 0xd000, 0x1000, 0xc3d0f762 )
ROM_LOAD( "pre.u4", 0xe000, 0x1000, 0x7ca79b43 )
ROM_LOAD( "pre.u5", 0xf000, 0x1000, 0x24e9618e )
ROM_END
ROM_START( dotrone_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "loc-cpu1", 0x0000, 0x4000, 0xeee31b8c )
ROM_LOAD( "loc-cpu2", 0x4000, 0x4000, 0x75ba6ad3 )
ROM_LOAD( "loc-cpu3", 0x8000, 0x4000, 0x94bb1a0e )
ROM_LOAD( "loc-cpu4", 0xc000, 0x2000, 0xc137383c )
ROM_REGION_DISPOSE(0x14000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "loc-bg2.6f", 0x00000, 0x2000, 0x40167124 )
ROM_LOAD( "loc-bg1.5f", 0x02000, 0x2000, 0xbb2d7a5d )
ROM_LOAD( "loc-a.cp0", 0x04000, 0x2000, 0xb35f5374 )
ROM_LOAD( "loc-b.cp9", 0x06000, 0x2000, 0x565a5c48 )
ROM_LOAD( "loc-c.cp8", 0x08000, 0x2000, 0xef45d146 )
ROM_LOAD( "loc-d.cp7", 0x0a000, 0x2000, 0x5e8a3ef3 )
ROM_LOAD( "loc-e.cp6", 0x0c000, 0x2000, 0xce957f1a )
ROM_LOAD( "loc-f.cp5", 0x0e000, 0x2000, 0xd26053ce )
ROM_LOAD( "loc-g.cp4", 0x10000, 0x2000, 0x57a2b1ff )
ROM_LOAD( "loc-h.cp3", 0x12000, 0x2000, 0x3bb4d475 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "loc-a", 0x0000, 0x1000, 0x2de6a8a8 )
ROM_LOAD( "loc-b", 0x1000, 0x1000, 0x4097663e )
ROM_LOAD( "loc-c", 0x2000, 0x1000, 0xf576b9e7 )
ROM_LOAD( "loc-d", 0x3000, 0x1000, 0x74b0059e )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "pre.u3", 0xd000, 0x1000, 0xc3d0f762 )
ROM_LOAD( "pre.u4", 0xe000, 0x1000, 0x7ca79b43 )
ROM_LOAD( "pre.u5", 0xf000, 0x1000, 0x24e9618e )
ROM_END
struct GameDriver dotron_driver =
{
__FILE__,
0,
"dotron",
"Discs of Tron (Upright)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nAlan J. McCormick (speech info)\nMathis Rosenhauer(backdrop support)\nMike Balfour(backdrop support)\nBrandon Kirkpatrick (backdrop)",
0,
&dotron_machine_driver,
0,
dotron_rom,
0, 0,
0,
0, /* sound_prom */
dotron_input_ports,
0, 0,0,
ORIENTATION_FLIP_X,
dotron_hiload, dotron_hisave
};
struct GameDriver dotrone_driver =
{
__FILE__,
&dotron_driver,
"dotrone",
"Discs of Tron (Environmental)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nAlan J. McCormick (speech info)\nMathis Rosenhauer(backdrop support)\nMike Balfour(backdrop support)\nBrandon Kirkpatrick (backdrop)",
0,
&dotron_machine_driver,
0,
dotrone_rom,
0, 0,
0,
0, /* sound_prom */
dotron_input_ports,
0, 0,0,
ORIENTATION_FLIP_X,
dotron_hiload, dotron_hisave
};
ROM_START( destderb_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "dd_pro", 0x0000, 0x4000, 0x8781b367 )
ROM_LOAD( "dd_pro1", 0x4000, 0x4000, 0x4c713bfe )
ROM_LOAD( "dd_pro2", 0x8000, 0x4000, 0xc2cbd2a4 )
ROM_REGION_DISPOSE(0x24000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "dd_bg0.6f", 0x00000, 0x2000, 0xcf80be19 )
ROM_LOAD( "dd_bg1.5f", 0x02000, 0x2000, 0x4e173e52 )
ROM_LOAD( "dd_fg-3.a10", 0x04000, 0x4000, 0x801d9b86 )
ROM_LOAD( "dd_fg-7.a9", 0x08000, 0x4000, 0x0ec3f60a )
ROM_LOAD( "dd_fg-2.a8", 0x0c000, 0x4000, 0x6cab7b95 )
ROM_LOAD( "dd_fg-6.a7", 0x10000, 0x4000, 0xabfb9a8b )
ROM_LOAD( "dd_fg-1.a6", 0x14000, 0x4000, 0x70259651 )
ROM_LOAD( "dd_fg-5.a5", 0x18000, 0x4000, 0x5fe99007 )
ROM_LOAD( "dd_fg-0.a4", 0x1c000, 0x4000, 0xe57a4de6 )
ROM_LOAD( "dd_fg-4.a3", 0x20000, 0x4000, 0x55aa667f )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "dd_ssio.a7", 0x0000, 0x1000, 0xc95cf31e )
ROM_LOAD( "dd_ssio.a8", 0x1000, 0x1000, 0x12aaa48e )
ROM_END
struct GameDriver destderb_driver =
{
__FILE__,
0,
"destderb",
"Demolition Derby",
"1984",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nBrad Oliver",
0,
&destderb_machine_driver,
0,
destderb_rom,
0, 0,
0,
0, /* sound_prom */
destderb_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
destderb_hiload, destderb_hisave
};
ROM_START( timber_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "timpg0.bin", 0x0000, 0x4000, 0x377032ab )
ROM_LOAD( "timpg1.bin", 0x4000, 0x4000, 0xfd772836 )
ROM_LOAD( "timpg2.bin", 0x8000, 0x4000, 0x632989f9 )
ROM_LOAD( "timpg3.bin", 0xc000, 0x2000, 0xdae8a0dc )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "timbg1.bin", 0x00000, 0x4000, 0xb1cb2651 )
ROM_LOAD( "timbg0.bin", 0x04000, 0x4000, 0x2ae352c4 )
ROM_LOAD( "timfg7.bin", 0x08000, 0x4000, 0xd9c27475 )
ROM_LOAD( "timfg6.bin", 0x0c000, 0x4000, 0x244778e8 )
ROM_LOAD( "timfg5.bin", 0x10000, 0x4000, 0xeb636216 )
ROM_LOAD( "timfg4.bin", 0x14000, 0x4000, 0xb7105eb7 )
ROM_LOAD( "timfg3.bin", 0x18000, 0x4000, 0x37c03272 )
ROM_LOAD( "timfg2.bin", 0x1c000, 0x4000, 0xe2c2885c )
ROM_LOAD( "timfg1.bin", 0x20000, 0x4000, 0x81de4a73 )
ROM_LOAD( "timfg0.bin", 0x24000, 0x4000, 0x7f3a4f59 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "tima7.bin", 0x0000, 0x1000, 0xc615dc3e )
ROM_LOAD( "tima8.bin", 0x1000, 0x1000, 0x83841c87 )
ROM_LOAD( "tima9.bin", 0x2000, 0x1000, 0x22bcdcd3 )
ROM_END
struct GameDriver timber_driver =
{
__FILE__,
0,
"timber",
"Timber",
"1984",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nBrad Oliver",
0,
&timber_machine_driver,
0,
timber_rom,
0, 0,
0,
0, /* sound_prom */
timber_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
timber_hiload, timber_hisave
};
ROM_START( rampage_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "pro-0.rv3", 0x0000, 0x8000, 0x2f7ca03c )
ROM_LOAD( "pro-1.rv3", 0x8000, 0x8000, 0xd89bd9a4 )
ROM_REGION_DISPOSE(0x48000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "bg-0", 0x00000, 0x04000, 0xc0d8b7a5 )
ROM_LOAD( "bg-1", 0x04000, 0x04000, 0x2f6e3aa1 )
ROM_LOAD( "fg-3", 0x08000, 0x10000, 0x81e1de40 )
ROM_LOAD( "fg-2", 0x18000, 0x10000, 0x9489f714 )
ROM_LOAD( "fg-1", 0x28000, 0x10000, 0x8728532b )
ROM_LOAD( "fg-0", 0x38000, 0x10000, 0x0974be5d )
ROM_REGION(0x20000) /* 128k for the Sounds Good board */
ROM_LOAD_EVEN( "ramp_u7.snd", 0x00000, 0x8000, 0xcffd7fa5 )
ROM_LOAD_ODD ( "ramp_u17.snd", 0x00000, 0x8000, 0xe92c596b )
ROM_LOAD_EVEN( "ramp_u8.snd", 0x10000, 0x8000, 0x11f787e4 )
ROM_LOAD_ODD ( "ramp_u18.snd", 0x10000, 0x8000, 0x6b8bf5e1 )
ROM_END
void rampage_rom_decode (void)
{
int i;
/* Rampage tile graphics are inverted */
for (i = 0; i < 0x8000; i++)
Machine->memory_region[1][i] ^= 0xff;
}
struct GameDriver rampage_driver =
{
__FILE__,
0,
"rampage",
"Rampage",
"1986",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&rampage_machine_driver,
0,
rampage_rom,
rampage_rom_decode, 0,
0,
0, /* sound_prom */
rampage_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
rampage_hiload, rampage_hisave
};
ROM_START( powerdrv_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "pdrv3b.bin", 0x0000, 0x8000, 0xd870b704 )
ROM_LOAD( "pdrv5b.bin", 0x8000, 0x8000, 0xfa0544ad )
ROM_REGION_DISPOSE(0x48000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "pdrv15a.bin", 0x00000, 0x04000, 0xb858b5a8 )
ROM_LOAD( "pdrv14b.bin", 0x04000, 0x04000, 0x12ee7fc2 )
ROM_LOAD( "pdrv4e.bin", 0x08000, 0x10000, 0xde400335 )
ROM_LOAD( "pdrv5e.bin", 0x18000, 0x10000, 0x4cb4780e )
ROM_LOAD( "pdrv6e.bin", 0x28000, 0x10000, 0x1a1f7f81 )
ROM_LOAD( "pdrv8e.bin", 0x38000, 0x10000, 0xdd3a2adc )
ROM_REGION(0x20000) /* 128k for the Sounds Good board */
ROM_LOAD_EVEN( "pdsndu7.bin", 0x00000, 0x8000, 0x78713e78 )
ROM_LOAD_ODD ( "pdsndu17.bin", 0x00000, 0x8000, 0xc41de6e4 )
ROM_LOAD_EVEN( "pdsndu8.bin", 0x10000, 0x8000, 0x15714036 )
ROM_LOAD_ODD ( "pdsndu18.bin", 0x10000, 0x8000, 0xcae14c70 )
ROM_END
struct GameDriver powerdrv_driver =
{
__FILE__,
0,
"powerdrv",
"Power Drive",
"????",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&rampage_machine_driver,
0,
powerdrv_rom,
rampage_rom_decode, 0,
0,
0, /* sound_prom */
rampage_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
0, 0
};
ROM_START( maxrpm_rom )
ROM_REGION(0x12000) /* 64k for code */
ROM_LOAD( "pro.0", 0x00000, 0x8000, 0x3f9ec35f )
ROM_LOAD( "pro.1", 0x08000, 0x6000, 0xf628bb30 )
ROM_CONTINUE( 0x10000, 0x2000 ) /* unused? but there seems to be stuff in here */
/* loading it at e000 causes rogue sprites to appear on screen */
ROM_REGION_DISPOSE(0x48000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "bg-0", 0x00000, 0x4000, 0xe3fb693a )
ROM_LOAD( "bg-1", 0x04000, 0x4000, 0x50d1db6c )
ROM_LOAD( "fg-3", 0x08000, 0x8000, 0x9ae3eb52 )
ROM_LOAD( "fg-2", 0x18000, 0x8000, 0x38be8505 )
ROM_LOAD( "fg-1", 0x28000, 0x8000, 0xe54b7f2a )
ROM_LOAD( "fg-0", 0x38000, 0x8000, 0x1d1435c1 )
ROM_END
struct GameDriver maxrpm_driver =
{
__FILE__,
0,
"maxrpm",
"Max RPM",
"1986",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&maxrpm_machine_driver,
0,
maxrpm_rom,
rampage_rom_decode, 0,
0,
0, /* sound_prom */
maxrpm_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
rampage_hiload, rampage_hisave
};
ROM_START( sarge_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "cpu_3b.bin", 0x0000, 0x8000, 0xda31a58f )
ROM_LOAD( "cpu_5b.bin", 0x8000, 0x8000, 0x6800e746 )
ROM_REGION_DISPOSE(0x24000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "til_15a.bin", 0x00000, 0x2000, 0x685001b8 )
ROM_LOAD( "til_14b.bin", 0x02000, 0x2000, 0x8449eb45 )
ROM_LOAD( "spr_4e.bin", 0x04000, 0x8000, 0xc382267d )
ROM_LOAD( "spr_5e.bin", 0x0c000, 0x8000, 0xc832375c )
ROM_LOAD( "spr_6e.bin", 0x14000, 0x8000, 0x7cc6fb28 )
ROM_LOAD( "spr_8e.bin", 0x1c000, 0x8000, 0x93fac29d )
ROM_REGION(0x10000) /* 64k for the Turbo Cheap Squeak */
ROM_LOAD( "tcs_u5.bin", 0xc000, 0x2000, 0xa894ef8a )
ROM_LOAD( "tcs_u4.bin", 0xe000, 0x2000, 0x6ca6faf3 )
ROM_END
void sarge_rom_decode (void)
{
int i;
/* Sarge tile graphics are inverted */
for (i = 0; i < 0x4000; i++)
Machine->memory_region[1][i] ^= 0xff;
}
struct GameDriver sarge_driver =
{
__FILE__,
0,
"sarge",
"Sarge",
"1985",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&sarge_machine_driver,
0,
sarge_rom,
sarge_rom_decode, 0,
0,
0, /* sound_prom */
sarge_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
0, 0
};
ROM_START( spyhunt_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "cpu_pg0.6d", 0x0000, 0x2000, 0x1721b88f )
ROM_LOAD( "cpu_pg1.7d", 0x2000, 0x2000, 0x909d044f )
ROM_LOAD( "cpu_pg2.8d", 0x4000, 0x2000, 0xafeeb8bd )
ROM_LOAD( "cpu_pg3.9d", 0x6000, 0x2000, 0x5e744381 )
ROM_LOAD( "cpu_pg4.10d", 0x8000, 0x2000, 0xa3033c15 )
ROM_LOAD( "cpu_pg5.11d", 0xA000, 0x4000, 0x88aa1e99 )
ROM_REGION_DISPOSE(0x29000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "cpu_bg2.5a", 0x0000, 0x2000, 0xba0fd626 )
ROM_LOAD( "cpu_bg3.6a", 0x2000, 0x2000, 0x7b482d61 )
ROM_LOAD( "cpu_bg0.3a", 0x4000, 0x2000, 0xdea34fed )
ROM_LOAD( "cpu_bg1.4a", 0x6000, 0x2000, 0x8f64525f )
ROM_LOAD( "vid_6fg.a2", 0x8000, 0x4000, 0x8cb8a066 )
ROM_LOAD( "vid_7fg.a1", 0xc000, 0x4000, 0x940fe17e )
ROM_LOAD( "vid_4fg.a4", 0x10000, 0x4000, 0x7ca4941b )
ROM_LOAD( "vid_5fg.a3", 0x14000, 0x4000, 0x2d9fbcec )
ROM_LOAD( "vid_2fg.a6", 0x18000, 0x4000, 0x62c8bfa5 )
ROM_LOAD( "vid_3fg.a5", 0x1c000, 0x4000, 0xb894934d )
ROM_LOAD( "vid_0fg.a8", 0x20000, 0x4000, 0x292c5466 )
ROM_LOAD( "vid_1fg.a7", 0x24000, 0x4000, 0x9fe286ec )
ROM_LOAD( "cpu_alph.10g", 0x28000, 0x1000, 0x936dc87f )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "snd_0sd.a8", 0x0000, 0x1000, 0xc95cf31e )
ROM_LOAD( "snd_1sd.a7", 0x1000, 0x1000, 0x12aaa48e )
ROM_REGION(0x8000) /* 32k for the Chip Squeak Deluxe */
ROM_LOAD_EVEN( "csd_u7a.u7", 0x00000, 0x2000, 0x6e689fe7 )
ROM_LOAD_ODD ( "csd_u17b.u17", 0x00000, 0x2000, 0x0d9ddce6 )
ROM_LOAD_EVEN( "csd_u8c.u8", 0x04000, 0x2000, 0x35563cd0 )
ROM_LOAD_ODD ( "csd_u18d.u18", 0x04000, 0x2000, 0x63d3f5b1 )
ROM_END
struct GameDriver spyhunt_driver =
{
__FILE__,
0,
"spyhunt",
"Spy Hunter",
"1983",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver\nLawnmower Man",
0,
&spyhunt_machine_driver,
0,
spyhunt_rom,
spyhunt_decode, 0,
0,
0, /* sound_prom */
spyhunt_input_ports,
0, 0,0,
ORIENTATION_ROTATE_90,
spyhunt_hiload, spyhunt_hisave
};
ROM_START( crater_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "crcpu.6d", 0x0000, 0x2000, 0xad31f127 )
ROM_LOAD( "crcpu.7d", 0x2000, 0x2000, 0x3743c78f )
ROM_LOAD( "crcpu.8d", 0x4000, 0x2000, 0xc95f9088 )
ROM_LOAD( "crcpu.9d", 0x6000, 0x2000, 0xa03c4b11 )
ROM_LOAD( "crcpu.10d", 0x8000, 0x2000, 0x44ae4cbd )
ROM_REGION_DISPOSE(0x29000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "crcpu.5a", 0x00000, 0x2000, 0x2fe4a6e1 )
ROM_LOAD( "crcpu.6a", 0x02000, 0x2000, 0xd0659042 )
ROM_LOAD( "crcpu.3a", 0x04000, 0x2000, 0x9d73504a )
ROM_LOAD( "crcpu.4a", 0x06000, 0x2000, 0x42a47dff )
ROM_LOAD( "crvid.a9", 0x08000, 0x4000, 0x811f152d )
ROM_LOAD( "crvid.a10", 0x0c000, 0x4000, 0x7a22d6bc )
ROM_LOAD( "crvid.a7", 0x10000, 0x4000, 0x9fa307d5 )
ROM_LOAD( "crvid.a8", 0x14000, 0x4000, 0x4b913498 )
ROM_LOAD( "crvid.a5", 0x18000, 0x4000, 0x9bdec312 )
ROM_LOAD( "crvid.a6", 0x1c000, 0x4000, 0x5bf954e0 )
ROM_LOAD( "crvid.a3", 0x20000, 0x4000, 0x2c2f5b29 )
ROM_LOAD( "crvid.a4", 0x24000, 0x4000, 0x579a8e36 )
ROM_LOAD( "crcpu.10g", 0x28000, 0x1000, 0x6fe53c8d )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "crsnd4.a7", 0x0000, 0x1000, 0xfd666cb5 )
ROM_LOAD( "crsnd1.a8", 0x1000, 0x1000, 0x90bf2c4c )
ROM_LOAD( "crsnd2.a9", 0x2000, 0x1000, 0x3b8deef1 )
ROM_LOAD( "crsnd3.a10", 0x3000, 0x1000, 0x05803453 )
ROM_END
struct GameDriver crater_driver =
{
__FILE__,
0,
"crater",
"Crater Raider",
"1984",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver\nLawnmower Man",
0,
&crater_machine_driver,
0,
crater_rom,
0, 0,
0,
0, /* sound_prom */
crater_input_ports,
0, 0,0,
ORIENTATION_FLIP_X,
crater_hiload, crater_hisave
};
| 29.543897
| 186
| 0.681757
|
pierrelouys
|
80c98983d664cca7b9dc656ae9f59552415a5233
| 118
|
cpp
|
C++
|
project653/src/component723/cpp/lib2.cpp
|
gradle/perf-native-large
|
af00fd258fbe9c7d274f386e46847fe12062cc71
|
[
"Apache-2.0"
] | 2
|
2016-11-23T17:25:24.000Z
|
2016-11-23T17:25:27.000Z
|
project653/src/component723/cpp/lib2.cpp
|
gradle/perf-native-large
|
af00fd258fbe9c7d274f386e46847fe12062cc71
|
[
"Apache-2.0"
] | 15
|
2016-09-15T03:19:32.000Z
|
2016-09-17T09:15:32.000Z
|
project653/src/component723/cpp/lib2.cpp
|
gradle/perf-native-large
|
af00fd258fbe9c7d274f386e46847fe12062cc71
|
[
"Apache-2.0"
] | 2
|
2019-11-09T16:26:55.000Z
|
2021-01-13T10:51:09.000Z
|
#include <stdio.h>
#include <component723/lib1.h>
int component723_2 () {
printf("Hello world!\n");
return 0;
}
| 13.111111
| 30
| 0.661017
|
gradle
|
80ca1ab3449e46af8d331c9fade430d018de3345
| 17,343
|
cc
|
C++
|
third_party/incubator-tvm/nnvm/src/top/nn/pooling.cc
|
KnowingNothing/akg-test
|
114d8626b824b9a31af50a482afc07ab7121862b
|
[
"Apache-2.0"
] | 286
|
2020-06-23T06:40:44.000Z
|
2022-03-30T01:27:49.000Z
|
third_party/incubator-tvm/nnvm/src/top/nn/pooling.cc
|
KnowingNothing/akg-test
|
114d8626b824b9a31af50a482afc07ab7121862b
|
[
"Apache-2.0"
] | 10
|
2020-07-31T03:26:59.000Z
|
2021-12-27T15:00:54.000Z
|
third_party/incubator-tvm/nnvm/src/top/nn/pooling.cc
|
KnowingNothing/akg-test
|
114d8626b824b9a31af50a482afc07ab7121862b
|
[
"Apache-2.0"
] | 30
|
2020-07-17T01:04:14.000Z
|
2021-12-27T14:05:19.000Z
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file pooling.cc
* \brief Property def of pooling operators.
*/
#include <nnvm/op.h>
#include <nnvm/node.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/compiler/op_attr_types.h>
#include <nnvm/compiler/util.h>
#include <nnvm/top/nn.h>
#include "nn_common.h"
#include "../op_common.h"
#include "../elemwise_op_common.h"
#include "topi/nn/pooling.h"
namespace nnvm {
namespace top {
using namespace air;
using namespace nnvm::compiler;
DMLC_REGISTER_PARAMETER(MaxPool2DParam);
template <typename T>
inline bool Pool2DInferShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape>* in_shape,
std::vector<TShape>* out_shape) {
const T& param = nnvm::get<T>(attrs.parsed);
CHECK_EQ(in_shape->size(), 1U);
CHECK_EQ(out_shape->size(), 1U);
TShape dshape = (*in_shape)[0];
if (dshape.ndim() == 0) return false;
CHECK_GE(dshape.ndim(), 2U)
<< "Pool2D only support input >= 2-D: input must have height and width";
Layout layout(param.layout);
CHECK(layout.contains('H') && layout.contains('W') &&
!layout.contains('h') && !layout.contains('w'))
<< "Invalid layout " << layout
<< ". Pool2D layout must have H and W, which cannot be split";
const auto hidx = layout.indexof('H');
const auto widx = layout.indexof('W');
dim_t pad_h, pad_w;
if (param.padding.ndim() == 1) {
pad_h = param.padding[0] * 2;
pad_w = param.padding[0] * 2;
} else if (param.padding.ndim() == 2) {
// (top, left)
pad_h = param.padding[0] * 2;
pad_w = param.padding[1] * 2;
} else if (param.padding.ndim() == 4) {
// (top, left, bottom, right)
pad_h = param.padding[0] + param.padding[2];
pad_w = param.padding[1] + param.padding[3];
} else {
return false;
}
TShape oshape = dshape;
CHECK(param.pool_size[0] <= dshape[hidx] + pad_h)
<< "pool size (" << param.pool_size[0] << ") exceeds input (" << dshape[hidx]
<< " padded to " << (dshape[hidx] + pad_h) << ")";
CHECK(param.pool_size[1] <= dshape[widx] + pad_w)
<< "pool size (" << param.pool_size[1] << ") exceeds input (" << dshape[widx]
<< " padded to " << (dshape[widx] + pad_w) << ")";
if (!param.ceil_mode) {
oshape[hidx] = ((dshape[hidx] + pad_h - param.pool_size[0]) /
param.strides[0]) + 1;
oshape[widx] = ((dshape[widx] + pad_w - param.pool_size[1]) /
param.strides[1]) + 1;
} else {
oshape[hidx] = ((dshape[hidx] + pad_h - param.pool_size[0] +
param.strides[0] - 1) / param.strides[0]) + 1;
oshape[widx] = ((dshape[widx] + pad_w - param.pool_size[1] +
param.strides[1] - 1) / param.strides[1]) + 1;
}
NNVM_ASSIGN_OUTPUT_SHAPE(attrs, *out_shape, 0, oshape);
return true;
}
template <typename T>
inline bool Pool2DCorrectLayout(const NodeAttrs& attrs,
std::vector<Layout> *ilayouts,
const std::vector<Layout> *last_ilayouts,
std::vector<Layout> *olayouts) {
const T ¶m = nnvm::get<T>(attrs.parsed);
CHECK_EQ(ilayouts->size(), 1);
CHECK_EQ(last_ilayouts->size(), 1);
CHECK_EQ(olayouts->size(), 1);
Layout input = (*ilayouts)[0];
const Layout layout(param.layout);
if (input.defined()) {
CHECK(input.convertible(layout)) << "Invalid input layout " << input;
if (input.indexof('W') != layout.indexof('W') ||
input.indexof('H') != layout.indexof('H') ||
input.contains('w') || input.contains('h')) {
// as long as the index doesn't change for width and height
// pool2d can keep the input layout.
input = layout;
}
} else {
input = layout;
}
NNVM_ASSIGN_LAYOUT(*ilayouts, 0, input);
NNVM_ASSIGN_LAYOUT(*olayouts, 0, input);
return true;
}
NNVM_REGISTER_OP(max_pool2d)
.describe(R"code(Max pooling operation for one dimensional data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, out_height, out_width) if `layout` is `NCHW`.
out_height and out_width are calculated as::
out_height = floor((height+padding[0]+padding[2]-pool_size[0])/strides[0])+1
out_width = floor((width+padding[1]+padding[3]-pool_size[1])/strides[1])+1
where padding will be an expanded array based on number of values passed as::
one int : all sides same padding used.
two int : bottom, right use same as top and left.
four int: padding width in the order of (top, left, bottom, right).
When `ceil_mode` is `True`, ceil will be used instead of floor in this
equation.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(MaxPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<MaxPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<MaxPool2DParam>)
.set_num_outputs(1)
.set_num_inputs(1)
.set_attr<FInferShape>("FInferShape", Pool2DInferShape<MaxPool2DParam>)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", Pool2DCorrectLayout<MaxPool2DParam>)
.set_attr<FTVMCompute>("FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const MaxPool2DParam& param = nnvm::get<MaxPool2DParam>(attrs.parsed);
auto pool_size = ShapeToArray(param.pool_size);
auto strides = ShapeToArray(param.strides);
auto padding = ShapeToArray(param.padding);
auto ceil_mode = param.ceil_mode;
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "max_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1) << "max_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1) << "max_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
if (param.padding.ndim() == 1) {
padding.push_back(padding[0]);
padding.push_back(padding[0]);
padding.push_back(padding[0]);
} else if (param.padding.ndim() == 2) {
padding.push_back(padding[0]);
padding.push_back(padding[1]);
}
return Array<Tensor>{
topi::nn::pool(inputs[0], pool_size, strides, padding,
topi::nn::kMaxPool, ceil_mode, layout.name())};
})
.set_attr<FGradient>(
"FGradient", [](const NodePtr& n,
const std::vector<NodeEntry>& ograds) {
return MakeGradNode("_max_pool2d_grad", n,
{ograds[0], n->inputs[0], NodeEntry{n, 0, 0}},
n->attrs.dict);
})
.set_support_level(2);
NNVM_REGISTER_OP(_max_pool2d_grad)
.describe(R"code(Max pooling 2D grad.
)code" NNVM_ADD_FILELINE)
.add_argument("ograd", "4D Tensor", "Output grad.")
.add_argument("input", "4D Tensor", "Input data of max_pool2d grad.")
.add_argument("output", "4D Tensor", "Output data of max_pool2d grad.")
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<MaxPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<MaxPool2DParam>)
.set_attr<FInferShape>("FInferShape", AssignOutputAttr<TShape, 1, 0>)
.set_attr<FInferType>("FInferType", ElemwiseType<3, 1>)
.set_attr<TIsBackward>("TIsBackward", true);
DMLC_REGISTER_PARAMETER(AvgPool2DParam);
NNVM_REGISTER_OP(avg_pool2d)
.describe(R"code(Average pooling operation for one dimensional data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, out_height, out_width) if `layout` is `NCHW`.
out_height and out_width are calculated as::
out_height = floor((height+padding[0]+padding[2]-pool_size[0])/strides[0])+1
out_width = floor((width+padding[1]+padding[3]-pool_size[1])/strides[1])+1
where padding will be an expanded array based on number of values passed as::
one int : all sides same padding used.
two int : bottom, right use same as top and left.
four int: padding width in the order of (top, left, bottom, right).
When `ceil_mode` is `True`, ceil will be used instead of floor in this
equation.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(AvgPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<AvgPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<AvgPool2DParam>)
.set_attr<FInferShape>("FInferShape", Pool2DInferShape<AvgPool2DParam>)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", Pool2DCorrectLayout<AvgPool2DParam>)
.set_attr<FTVMCompute>("FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const AvgPool2DParam& param = nnvm::get<AvgPool2DParam>(attrs.parsed);
auto pool_size = ShapeToArray(param.pool_size);
auto strides = ShapeToArray(param.strides);
auto padding = ShapeToArray(param.padding);
auto ceil_mode = param.ceil_mode;
auto count_include_pad = param.count_include_pad;
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "avg_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1) << "avg_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1) << "avg_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
if (param.padding.ndim() == 1) {
padding.push_back(padding[0]);
padding.push_back(padding[0]);
padding.push_back(padding[0]);
} else if (param.padding.ndim() == 2) {
padding.push_back(padding[0]);
padding.push_back(padding[1]);
}
return Array<Tensor>{
topi::nn::pool(inputs[0], pool_size, strides, padding,
topi::nn::kAvgPool, ceil_mode, layout.name(), count_include_pad)};
})
.set_num_outputs(1)
.set_num_inputs(1)
.set_support_level(2);
DMLC_REGISTER_PARAMETER(GlobalPool2DParam);
inline bool GlobalPool2DInferShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape>* in_shape,
std::vector<TShape>* out_shape) {
static const Layout kNCHW("NCHW");
const GlobalPool2DParam& param = nnvm::get<GlobalPool2DParam>(attrs.parsed);
CHECK_EQ(in_shape->size(), 1U);
CHECK_EQ(out_shape->size(), 1U);
TShape dshape = (*in_shape)[0];
if (dshape.ndim() == 0) return false;
CHECK_GE(dshape.ndim(), 2U)
<< "Pool2D only support input >= 2-D: input must have height and width";
Layout layout(param.layout);
CHECK(layout.contains('H') && layout.contains('W') &&
!layout.contains('h') && !layout.contains('w'))
<< "Invalid layout " << layout
<< ". Pool2D layout must have H and W, which cannot be split";
const auto hidx = layout.indexof('H');
const auto widx = layout.indexof('W');
TShape oshape = dshape;
oshape[hidx] = oshape[widx] = 1;
NNVM_ASSIGN_OUTPUT_SHAPE(attrs, *out_shape, 0, oshape);
return true;
}
inline bool GlobalPool2DCorrectLayout(const NodeAttrs& attrs,
std::vector<Layout> *ilayouts,
const std::vector<Layout> *last_ilayouts,
std::vector<Layout> *olayouts) {
const GlobalPool2DParam ¶m = nnvm::get<GlobalPool2DParam>(attrs.parsed);
CHECK_EQ(ilayouts->size(), 1);
CHECK_EQ(last_ilayouts->size(), 1);
CHECK_EQ(olayouts->size(), 1);
Layout input = (*ilayouts)[0];
const Layout layout(param.layout);
if (input.defined()) {
CHECK(input.convertible(layout)) << "Invalid input layout " << input;
if (input.indexof('W') != layout.indexof('W') ||
input.indexof('H') != layout.indexof('H') ||
input.contains('w') || input.contains('h')) {
// as long as the index doesn't change for width and height
// pool2d can keep the input layout.
input = layout;
}
} else {
input = layout;
}
NNVM_ASSIGN_LAYOUT(*ilayouts, 0, input);
NNVM_ASSIGN_LAYOUT(*olayouts, 0, input);
return true;
}
NNVM_REGISTER_OP(global_max_pool2d)
.describe(R"code(Global max pooling operation for 2D data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, 1, 1) if `layout` is `NCHW`.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(GlobalPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<GlobalPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<GlobalPool2DParam>)
.set_attr<FInferShape>("FInferShape", GlobalPool2DInferShape)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", GlobalPool2DCorrectLayout)
.set_attr<FTVMCompute>(
"FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const GlobalPool2DParam& param = nnvm::get<GlobalPool2DParam>(attrs.parsed);
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "global_max_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1)
<< "global_max_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1)
<< "global_max_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
return Array<Tensor>{
topi::nn::global_pool(inputs[0], topi::nn::kMaxPool, layout.name()) };
})
.set_num_outputs(1)
.set_num_inputs(1)
.set_support_level(2);
NNVM_REGISTER_OP(global_avg_pool2d)
.describe(R"code(Global average pooling operation for 2D data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, 1, 1) if `layout` is `NCHW`.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(GlobalPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<GlobalPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<GlobalPool2DParam>)
.set_attr<FInferShape>("FInferShape", GlobalPool2DInferShape)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", GlobalPool2DCorrectLayout)
.set_attr<FTVMCompute>(
"FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const GlobalPool2DParam& param = nnvm::get<GlobalPool2DParam>(attrs.parsed);
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "global_avg_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1)
<< "global_avg_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1)
<< "global_avg_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
return Array<Tensor>{
topi::nn::global_pool(inputs[0], topi::nn::kAvgPool, layout.name()) };
})
.set_num_outputs(1)
.set_num_inputs(1)
.set_support_level(2);
} // namespace top
} // namespace nnvm
| 39.777523
| 91
| 0.659056
|
KnowingNothing
|
80ca4c1fac04ac410563ed7d8aa939c84589ad08
| 7,349
|
cpp
|
C++
|
libs/settings/tests/unit/setting_tests.cpp
|
jinmannwong/ledger
|
f3b129c127e107603e08bb192eb695d23eb17dbc
|
[
"Apache-2.0"
] | null | null | null |
libs/settings/tests/unit/setting_tests.cpp
|
jinmannwong/ledger
|
f3b129c127e107603e08bb192eb695d23eb17dbc
|
[
"Apache-2.0"
] | null | null | null |
libs/settings/tests/unit/setting_tests.cpp
|
jinmannwong/ledger
|
f3b129c127e107603e08bb192eb695d23eb17dbc
|
[
"Apache-2.0"
] | 2
|
2019-11-13T10:55:24.000Z
|
2019-11-13T11:37:09.000Z
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "settings/setting.hpp"
#include "settings/setting_collection.hpp"
#include "gtest/gtest.h"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace {
using fetch::settings::Setting;
using fetch::settings::SettingCollection;
TEST(SettingTests, CheckUInt32)
{
SettingCollection collection{};
Setting<uint32_t> setting{collection, "foo", 0, "A sample setting"};
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0);
EXPECT_EQ(setting.value(), 0u);
std::istringstream iss{"401"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0u);
EXPECT_EQ(setting.value(), 401u);
}
TEST(SettingTests, CheckSizet)
{
SettingCollection collection{};
Setting<std::size_t> setting{collection, "block-interval", 250u, "A sample setting"};
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 250u);
std::istringstream iss{"40100"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 40100u);
}
TEST(SettingTests, CheckDouble)
{
SettingCollection collection{};
Setting<double> setting{collection, "threshold", 10.0, "A sample setting"};
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 10.0);
std::istringstream iss{"3.145"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 3.145);
}
TEST(SettingTests, CheckBool)
{
SettingCollection collection{};
Setting<bool> setting{collection, "flag", false, "A sample setting"};
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
for (auto const &on_value : {"true", "1", "on", "enabled"})
{
setting.Update(false);
std::istringstream iss{on_value};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), true);
}
for (auto const &off_value : {"false", "0", "off", "disabled"})
{
setting.Update(true);
std::istringstream iss{off_value};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
}
}
TEST(SettingTests, CheckStringList)
{
using StringArray = std::vector<std::string>;
SettingCollection collection{};
Setting<StringArray> setting{collection, "peers", {}, "A sample setting"};
EXPECT_EQ(setting.name(), "peers");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), StringArray{});
EXPECT_EQ(setting.value(), StringArray{});
{
setting.Update(StringArray{});
std::istringstream iss{"foo"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "peers");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), StringArray{});
EXPECT_EQ(setting.value(), StringArray({"foo"}));
}
{
setting.Update(StringArray{});
std::istringstream iss{"foo,bar,baz"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "peers");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), StringArray{});
EXPECT_EQ(setting.value(), StringArray({"foo", "bar", "baz"}));
}
}
TEST(SettingTests, CheckUInt32Invalid)
{
SettingCollection collection{};
Setting<uint32_t> setting{collection, "foo", 0, "A sample setting"};
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0);
EXPECT_EQ(setting.value(), 0u);
std::istringstream iss{"blah blah blah"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0u);
EXPECT_EQ(setting.value(), 0u);
}
TEST(SettingTests, CheckBoolInvalid)
{
SettingCollection collection{};
Setting<bool> setting{collection, "flag", false, "A sample setting"};
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
for (auto const &on_value : {"blah", "please", "gogogo", "launch"})
{
setting.Update(false);
std::istringstream iss{on_value};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
}
}
TEST(SettingTests, CheckSizetInvalid)
{
SettingCollection collection{};
Setting<std::size_t> setting{collection, "block-interval", 250u, "A sample setting"};
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 250u);
std::istringstream iss{"twenty-four"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 250u);
}
TEST(SettingTests, CheckDoubleInvalid)
{
SettingCollection collection{};
Setting<double> setting{collection, "threshold", 10.0, "A sample setting"};
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 10.0);
std::istringstream iss{"very-small-number"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 10.0);
}
} // namespace
| 29.753036
| 87
| 0.68608
|
jinmannwong
|
80ccef118362e7a49e597bc41752dd6e1eba9513
| 1,022
|
cpp
|
C++
|
Solutions/Construct Binary Tree from Preorder and Inorder/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | 1
|
2015-04-13T10:58:30.000Z
|
2015-04-13T10:58:30.000Z
|
Solutions/Construct Binary Tree from Preorder and Inorder/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | null | null | null |
Solutions/Construct Binary Tree from Preorder and Inorder/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
return f(preorder, 0, preorder.size(), inorder, 0, inorder.size());
}
TreeNode *f(vector<int> &preorder, int pre_start, int pre_end, vector<int> &inorder, int in_start, int in_end) {
if (pre_start >= pre_end || in_start >= in_end) {
return NULL;
}
int root_val = preorder[pre_start];
TreeNode *root = new TreeNode(root_val);
int i = in_start;
for(; inorder[i] != root_val; i++);
int left_dis = i - in_start;
root->left = f(preorder, pre_start+1, pre_start + 1 + left_dis, inorder, in_start, i);
root->right = f(preorder, pre_start+1+left_dis, pre_end, inorder, i+1, in_end);
return root;
}
};
int main()
{
return 0;
}
| 29.2
| 116
| 0.605675
|
Crayzero
|
80cfaf2424afefc32430d5f4d5443d473de4894f
| 2,922
|
cpp
|
C++
|
generator/opentable_dataset.cpp
|
ToshUxanoff/omim
|
a8acb5821c72bd78847d1c49968b14d15b1e06ee
|
[
"Apache-2.0"
] | 1
|
2019-03-13T08:21:40.000Z
|
2019-03-13T08:21:40.000Z
|
generator/opentable_dataset.cpp
|
MohammadMoeinfar/omim
|
7b7d1990143bc3cbe218ea14b5428d0fc02d78fc
|
[
"Apache-2.0"
] | null | null | null |
generator/opentable_dataset.cpp
|
MohammadMoeinfar/omim
|
7b7d1990143bc3cbe218ea14b5428d0fc02d78fc
|
[
"Apache-2.0"
] | null | null | null |
#include "generator/opentable_dataset.hpp"
#include "generator/feature_builder.hpp"
#include "generator/sponsored_scoring.hpp"
#include "indexer/classificator.hpp"
#include "indexer/ftypes_matcher.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include <iomanip>
#include <iostream>
#include "boost/algorithm/string/replace.hpp"
namespace generator
{
// OpentableRestaurant ------------------------------------------------------------------------------
OpentableRestaurant::OpentableRestaurant(std::string const & src)
{
vector<std::string> rec;
strings::ParseCSVRow(src, '\t', rec);
CHECK_EQUAL(rec.size(), FieldsCount(), ("Error parsing restaurants.tsv line:",
boost::replace_all_copy(src, "\t", "\\t")));
CLOG(LDEBUG, strings::to_uint(rec[FieldIndex(Fields::Id)], m_id.Get()), ());
CLOG(LDEBUG, strings::to_double(rec[FieldIndex(Fields::Latitude)], m_latLon.lat), ());
CLOG(LDEBUG, strings::to_double(rec[FieldIndex(Fields::Longtitude)], m_latLon.lon), ());
m_name = rec[FieldIndex(Fields::Name)];
m_address = rec[FieldIndex(Fields::Address)];
m_descUrl = rec[FieldIndex(Fields::DescUrl)];
}
// OpentableDataset ---------------------------------------------------------------------------------
template <>
bool OpentableDataset::NecessaryMatchingConditionHolds(FeatureBuilder1 const & fb) const
{
if (fb.GetName(StringUtf8Multilang::kDefaultCode).empty())
return false;
return ftypes::IsEatChecker::Instance()(fb.GetTypes());
}
template <>
void OpentableDataset::PreprocessMatchedOsmObject(ObjectId const matchedObjId, FeatureBuilder1 & fb,
function<void(FeatureBuilder1 &)> const fn) const
{
auto const & restaurant = m_storage.GetObjectById(matchedObjId);
auto & metadata = fb.GetMetadata();
metadata.Set(feature::Metadata::FMD_SPONSORED_ID, strings::to_string(restaurant.m_id.Get()));
FeatureParams & params = fb.GetParams();
// params.AddAddress(restaurant.address);
// TODO(mgsergio): addr:full ???
params.AddName(StringUtf8Multilang::GetLangByCode(StringUtf8Multilang::kDefaultCode),
restaurant.m_name);
auto const & clf = classif();
params.AddType(clf.GetTypeByPath({"sponsored", "opentable"}));
fn(fb);
}
template <>
OpentableDataset::ObjectId OpentableDataset::FindMatchingObjectIdImpl(FeatureBuilder1 const & fb) const
{
auto const name = fb.GetName(StringUtf8Multilang::kDefaultCode);
if (name.empty())
return Object::InvalidObjectId();
// Find |kMaxSelectedElements| nearest values to a point.
auto const nearbyIds = m_storage.GetNearestObjects(MercatorBounds::ToLatLon(fb.GetKeyPoint()));
for (auto const objId : nearbyIds)
{
if (sponsored_scoring::Match(m_storage.GetObjectById(objId), fb).IsMatched())
return objId;
}
return Object::InvalidObjectId();
}
} // namespace generator
| 33.586207
| 103
| 0.675565
|
ToshUxanoff
|
80d0265eea34fb6d29f59358db1b032017bedec2
| 539
|
cc
|
C++
|
net/http/http_status_code.cc
|
pozdnyakov/chromium-crosswalk
|
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2020-05-03T06:33:56.000Z
|
2021-11-14T18:39:42.000Z
|
net/http/http_status_code.cc
|
pozdnyakov/chromium-crosswalk
|
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
net/http/http_status_code.cc
|
pozdnyakov/chromium-crosswalk
|
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 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 "net/http/http_status_code.h"
#include "base/logging.h"
namespace net {
const char* GetHttpReasonPhrase(HttpStatusCode code) {
switch (code) {
#define HTTP_STATUS(label, code, reason) case HTTP_ ## label: return reason;
#include "net/http/http_status_code_list.h"
#undef HTTP_STATUS
default:
NOTREACHED();
}
return "";
}
} // namespace net
| 20.730769
| 76
| 0.719852
|
pozdnyakov
|
80d0dc49bf7c748cde25fa9974b35878fe8d6bde
| 10,047
|
hpp
|
C++
|
src/3rd party/boost/boost/spirit/debug/debug_node.hpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | 8
|
2016-01-25T20:18:51.000Z
|
2019-03-06T07:00:04.000Z
|
src/3rd party/boost/boost/spirit/debug/debug_node.hpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | null | null | null |
src/3rd party/boost/boost/spirit/debug/debug_node.hpp
|
OLR-xray/OLR-3.0
|
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
|
[
"Apache-2.0"
] | 3
|
2016-02-14T01:20:43.000Z
|
2021-02-03T11:19:11.000Z
|
/*=============================================================================
Spirit v1.6.0
Copyright (c) 2001-2003 Joel de Guzman
Copyright (c) 2002-2003 Hartmut Kaiser
Copyright (c) 2003 Gustavo Guerra
http://spirit.sourceforge.net/
Permission to copy, use, modify, sell and distribute this software is
granted provided this copyright notice appears in all copies. This
software is provided "as is" without express or implied warranty, and
with no claim as to its suitability for any purpose.
=============================================================================*/
#if !defined(BOOST_SPIRIT_DEBUG_NODE_HPP)
#define BOOST_SPIRIT_DEBUG_NODE_HPP
#if !defined(BOOST_SPIRIT_DEBUG_MAIN_HPP)
#error "You must include boost/spirit/debug.hpp, not boost/spirit/debug/debug_node.hpp"
#endif
#if defined(BOOST_SPIRIT_DEBUG)
#include <string>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/spirit/core/primitives/primitives.hpp> // for iscntrl_
namespace boost { namespace spirit {
///////////////////////////////////////////////////////////////////////////////
//
// Debug helper classes for rules, which ensure maximum non-intrusiveness of
// the Spirit debug support
//
///////////////////////////////////////////////////////////////////////////////
namespace impl {
struct token_printer_aux_for_chars
{
template<typename CharT>
static void print(CharT c)
{
if (c == static_cast<CharT>('\a'))
BOOST_SPIRIT_DEBUG_OUT << "\\a";
else if (c == static_cast<CharT>('\b'))
BOOST_SPIRIT_DEBUG_OUT << "\\b";
else if (c == static_cast<CharT>('\f'))
BOOST_SPIRIT_DEBUG_OUT << "\\f";
else if (c == static_cast<CharT>('\n'))
BOOST_SPIRIT_DEBUG_OUT << "\\n";
else if (c == static_cast<CharT>('\r'))
BOOST_SPIRIT_DEBUG_OUT << "\\r";
else if (c == static_cast<CharT>('\t'))
BOOST_SPIRIT_DEBUG_OUT << "\\t";
else if (c == static_cast<CharT>('\v'))
BOOST_SPIRIT_DEBUG_OUT << "\\v";
else if (iscntrl_(c))
BOOST_SPIRIT_DEBUG_OUT << "\\" << static_cast<int>(c);
else
BOOST_SPIRIT_DEBUG_OUT << static_cast<char>(c);
}
};
// for token types where the comparison with char constants wouldn't work
struct token_printer_aux_for_other_types
{
template<typename CharT>
static void print(CharT c)
{
BOOST_SPIRIT_DEBUG_OUT << c;
}
};
template <typename CharT>
struct token_printer_aux
: mpl::if_<
mpl::and_<
is_convertible<CharT, char>,
is_convertible<char, CharT> >,
token_printer_aux_for_chars,
token_printer_aux_for_other_types
>::type
{
};
template<typename CharT>
inline void token_printer(CharT c)
{
#if !defined(BOOST_SPIRIT_DEBUG_TOKEN_PRINTER)
token_printer_aux<CharT>::print(c);
#else
BOOST_SPIRIT_DEBUG_TOKEN_PRINTER(BOOST_SPIRIT_DEBUG_OUT, c);
#endif
}
///////////////////////////////////////////////////////////////////////////////
//
// Dump infos about the parsing state of a rule
//
///////////////////////////////////////////////////////////////////////////////
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
template <typename IteratorT>
inline void
print_node_info(bool hit, int level, bool close, std::string const& name,
IteratorT first, IteratorT last)
{
if (!name.empty())
{
for (int i = 0; i < level; ++i)
BOOST_SPIRIT_DEBUG_OUT << " ";
if (close)
{
if (hit)
BOOST_SPIRIT_DEBUG_OUT << "/";
else
BOOST_SPIRIT_DEBUG_OUT << "#";
}
BOOST_SPIRIT_DEBUG_OUT << name << ":\t\"";
IteratorT iter = first;
IteratorT ilast = last;
for (int j = 0; j < BOOST_SPIRIT_DEBUG_PRINT_SOME; ++j)
{
if (iter == ilast)
break;
token_printer(*iter);
++iter;
}
BOOST_SPIRIT_DEBUG_OUT << "\"\n";
}
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
template <typename ResultT>
inline ResultT &
print_closure_info(ResultT &hit, int level, std::string const& name)
{
if (!name.empty()) {
for (int i = 0; i < level-1; ++i)
BOOST_SPIRIT_DEBUG_OUT << " ";
// for now, print out the return value only
BOOST_SPIRIT_DEBUG_OUT
<< "^" << name << ":\t" << hit.value() << "\n";
}
return hit;
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
}
///////////////////////////////////////////////////////////////////////////////
//
// Implementation note: The parser_context_linker, parser_scanner_linker and
// closure_context_linker classes are wrapped by a PP constant to allow
// redefinition of this classes outside of Spirit
//
///////////////////////////////////////////////////////////////////////////////
#if !defined(BOOST_SPIRIT_PARSER_CONTEXT_LINKER_DEFINED)
#define BOOST_SPIRIT_PARSER_CONTEXT_LINKER_DEFINED
///////////////////////////////////////////////////////////////////////////
//
// parser_context_linker is a debug wrapper for the ContextT template
// parameter of the rule<>, subrule<> and the grammar<> classes
//
///////////////////////////////////////////////////////////////////////////
template<typename ContextT>
struct parser_context_linker : public ContextT
{
typedef ContextT base_t;
template <typename ParserT>
parser_context_linker(ParserT const& p)
: ContextT(p) {}
template <typename ParserT, typename ScannerT>
void pre_parse(ParserT const& p, ScannerT &scan)
{
this->base_t::pre_parse(p, scan);
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
if (trace_parser(p)) {
impl::print_node_info(
false,
scan.get_level(),
false,
parser_name(p),
scan.first,
scan.last);
}
scan.get_level()++;
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
}
template <typename ResultT, typename ParserT, typename ScannerT>
ResultT& post_parse(ResultT& hit, ParserT const& p, ScannerT &scan)
{
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
--scan.get_level();
if (trace_parser(p)) {
impl::print_node_info(
hit,
scan.get_level(),
true,
parser_name(p),
scan.first,
scan.last);
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
return this->base_t::post_parse(hit, p, scan);
}
};
#endif // !defined(BOOST_SPIRIT_PARSER_CONTEXT_LINKER_DEFINED)
#if !defined(BOOST_SPIRIT_PARSER_SCANNER_LINKER_DEFINED)
#define BOOST_SPIRIT_PARSER_SCANNER_LINKER_DEFINED
///////////////////////////////////////////////////////////////////////////////
// This class is to avoid linker problems and to ensure a real singleton
// 'level' variable
struct debug_support
{
int& get_level()
{
static int level = 0;
return level;
}
};
template<typename ScannerT>
struct parser_scanner_linker : public ScannerT
{
parser_scanner_linker(ScannerT const &scan_) : ScannerT(scan_)
{}
int &get_level()
{ return debug.get_level(); }
private: debug_support debug;
};
#endif // !defined(BOOST_SPIRIT_PARSER_SCANNER_LINKER_DEFINED)
#if !defined(BOOST_SPIRIT_CLOSURE_CONTEXT_LINKER_DEFINED)
#define BOOST_SPIRIT_CLOSURE_CONTEXT_LINKER_DEFINED
///////////////////////////////////////////////////////////////////////////
//
// closure_context_linker is a debug wrapper for the closure template
// parameter of the rule<>, subrule<> and grammar classes
//
///////////////////////////////////////////////////////////////////////////
template<typename ContextT>
struct closure_context_linker : public parser_context_linker<ContextT>
{
typedef parser_context_linker<ContextT> base_t;
template <typename ParserT>
closure_context_linker(ParserT const& p)
: parser_context_linker<ContextT>(p) {}
template <typename ParserT, typename ScannerT>
void pre_parse(ParserT const& p, ScannerT &scan)
{ this->base_t::pre_parse(p, scan); }
template <typename ResultT, typename ParserT, typename ScannerT>
ResultT&
post_parse(ResultT& hit, ParserT const& p, ScannerT &scan)
{
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
if (hit && trace_parser(p)) {
// for now, print out the return value only
return impl::print_closure_info(
this->base_t::post_parse(hit, p, scan),
scan.get_level(),
parser_name(p)
);
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
return this->base_t::post_parse(hit, p, scan);
}
};
#endif // !defined(BOOST_SPIRIT_CLOSURE_CONTEXT_LINKER_DEFINED)
}} // namespace boost::spirit
#endif // defined(BOOST_SPIRIT_DEBUG)
#endif // !defined(BOOST_SPIRIT_DEBUG_NODE_HPP)
| 32.099042
| 87
| 0.542052
|
OLR-xray
|
80d1daf65975d4ba1be7f6e8b285cceed09f71e9
| 1,605
|
cpp
|
C++
|
logger.cpp
|
chenyoujie/GeoDa
|
87504344512bd0da2ccadfb160ecd1e918a52f06
|
[
"BSL-1.0"
] | null | null | null |
logger.cpp
|
chenyoujie/GeoDa
|
87504344512bd0da2ccadfb160ecd1e918a52f06
|
[
"BSL-1.0"
] | null | null | null |
logger.cpp
|
chenyoujie/GeoDa
|
87504344512bd0da2ccadfb160ecd1e918a52f06
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2005, 2006
// Seweryn Habdank-Wojewodzki
// Distributed under the Boost Software License,
// Version 1.0.
// (copy at http://www.boost.org/LICENSE_1_0.txt)
#include "logger.h"
#if !defined(CLEANLOG)
#define FTLOG
#if !defined(DEBUG)
#undef FTLOG
#undef TLOG
#endif
//#if defined (FTLOG)
//#include <fstream>
//#else
#include <iostream>
// http://www.msobczak.com/prog/bin/nullstream.zip
#include "nullstream.h"
//#endif
logger_t::logger_t()
{}
bool logger_t::is_activated = true;
#if defined(TLOG)
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr<std::ostream>( new NullStream );
std::ostream * logger_t::outstream = &std::cout;
#elif defined (ETLOG)
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr <std::ostream>( new NullStream );
std::ostream * logger_t::outstream = &std::cerr;
#elif defined (FTLOG)
//std::auto_ptr <std::ostream> logger_t::outstream_helper_ptr
//= std::auto_ptr<std::ostream>( new std::ofstream ("oldlogger.txt"));
//std::ostream * logger_t::outstream = outstream_helper_ptr.get();
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr <std::ostream>( new NullStream );
std::ostream * logger_t::outstream = &std::cout;
// here is a place for user defined output stream
// and compiler flag
#else
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr<std::ostream>( new NullStream );
std::ostream* logger_t::outstream = outstream_helper_ptr.get();
#endif
logger_t & logger()
{
static logger_t* ans = new logger_t();
return *ans;
}
#endif
// !CLEANLOG
| 24.692308
| 70
| 0.721495
|
chenyoujie
|
80d25aae65572a296eec5063154ff3838cf4b360
| 7,058
|
cpp
|
C++
|
shared/test/unit_test/helpers/bit_helpers_tests.cpp
|
troels/compute-runtime
|
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
|
[
"Intel",
"MIT"
] | 778
|
2017-09-29T20:02:43.000Z
|
2022-03-31T15:35:28.000Z
|
shared/test/unit_test/helpers/bit_helpers_tests.cpp
|
troels/compute-runtime
|
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
|
[
"Intel",
"MIT"
] | 478
|
2018-01-26T16:06:45.000Z
|
2022-03-30T10:19:10.000Z
|
shared/test/unit_test/helpers/bit_helpers_tests.cpp
|
troels/compute-runtime
|
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
|
[
"Intel",
"MIT"
] | 215
|
2018-01-30T08:39:32.000Z
|
2022-03-29T11:08:51.000Z
|
/*
* Copyright (C) 2019-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/helpers/bit_helpers.h"
#include "gtest/gtest.h"
using namespace NEO;
TEST(IsBitSetTests, givenDifferentValuesWhenTestingIsBitSetThenCorrectValueIsReturned) {
size_t field1 = 0;
size_t field2 = 0b1;
size_t field3 = 0b1000;
size_t field4 = 0b1010;
EXPECT_FALSE(isBitSet(field1, 0));
EXPECT_FALSE(isBitSet(field1, 1));
EXPECT_FALSE(isBitSet(field1, 2));
EXPECT_FALSE(isBitSet(field1, 3));
EXPECT_TRUE(isBitSet(field2, 0));
EXPECT_FALSE(isBitSet(field2, 1));
EXPECT_FALSE(isBitSet(field2, 2));
EXPECT_FALSE(isBitSet(field2, 3));
EXPECT_FALSE(isBitSet(field3, 0));
EXPECT_FALSE(isBitSet(field3, 1));
EXPECT_FALSE(isBitSet(field3, 2));
EXPECT_TRUE(isBitSet(field3, 3));
EXPECT_FALSE(isBitSet(field4, 0));
EXPECT_TRUE(isBitSet(field4, 1));
EXPECT_FALSE(isBitSet(field4, 2));
EXPECT_TRUE(isBitSet(field4, 3));
}
TEST(IsAnyBitSetTests, givenDifferentValuesWhenTestingIsAnyBitSetThenCorrectValueIsReturned) {
EXPECT_FALSE(isAnyBitSet(0, 0));
EXPECT_FALSE(isAnyBitSet(0, 0b1));
EXPECT_FALSE(isAnyBitSet(0, 0b10));
EXPECT_FALSE(isAnyBitSet(0, 0b1000));
EXPECT_FALSE(isAnyBitSet(0, 0b1010));
EXPECT_FALSE(isAnyBitSet(0, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1, 0));
EXPECT_TRUE(isAnyBitSet(0b1, 0b1));
EXPECT_FALSE(isAnyBitSet(0b1, 0b10));
EXPECT_FALSE(isAnyBitSet(0b1, 0b1000));
EXPECT_FALSE(isAnyBitSet(0b1, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b10, 0));
EXPECT_FALSE(isAnyBitSet(0b10, 0b1));
EXPECT_TRUE(isAnyBitSet(0b10, 0b10));
EXPECT_FALSE(isAnyBitSet(0b10, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b10, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b10, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1000, 0));
EXPECT_FALSE(isAnyBitSet(0b1000, 0b1));
EXPECT_FALSE(isAnyBitSet(0b1000, 0b10));
EXPECT_TRUE(isAnyBitSet(0b1000, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b1000, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1000, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1010, 0));
EXPECT_FALSE(isAnyBitSet(0b1010, 0b1));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b10));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1111, 0));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b10));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1111));
}
TEST(IsValueSetTests, givenDifferentValuesWhenTestingIsValueSetThenCorrectValueIsReturned) {
size_t field1 = 0;
size_t field2 = 0b1;
size_t field3 = 0b10;
size_t field4 = 0b1000;
size_t field5 = 0b1010;
size_t field6 = 0b1111;
EXPECT_FALSE(isValueSet(field1, field2));
EXPECT_FALSE(isValueSet(field1, field3));
EXPECT_FALSE(isValueSet(field1, field4));
EXPECT_FALSE(isValueSet(field1, field5));
EXPECT_FALSE(isValueSet(field1, field6));
EXPECT_TRUE(isValueSet(field2, field2));
EXPECT_FALSE(isValueSet(field2, field3));
EXPECT_FALSE(isValueSet(field2, field4));
EXPECT_FALSE(isValueSet(field2, field5));
EXPECT_FALSE(isValueSet(field2, field6));
EXPECT_FALSE(isValueSet(field3, field2));
EXPECT_TRUE(isValueSet(field3, field3));
EXPECT_FALSE(isValueSet(field3, field4));
EXPECT_FALSE(isValueSet(field3, field5));
EXPECT_FALSE(isValueSet(field3, field6));
EXPECT_FALSE(isValueSet(field4, field2));
EXPECT_FALSE(isValueSet(field4, field3));
EXPECT_TRUE(isValueSet(field4, field4));
EXPECT_FALSE(isValueSet(field4, field5));
EXPECT_FALSE(isValueSet(field4, field6));
EXPECT_FALSE(isValueSet(field5, field2));
EXPECT_TRUE(isValueSet(field5, field3));
EXPECT_TRUE(isValueSet(field5, field4));
EXPECT_TRUE(isValueSet(field5, field5));
EXPECT_FALSE(isValueSet(field5, field6));
EXPECT_TRUE(isValueSet(field6, field2));
EXPECT_TRUE(isValueSet(field6, field3));
EXPECT_TRUE(isValueSet(field6, field4));
EXPECT_TRUE(isValueSet(field6, field5));
EXPECT_TRUE(isValueSet(field6, field6));
}
TEST(IsFieldValidTests, givenDifferentValuesWhenTestingIsFieldValidThenCorrectValueIsReturned) {
size_t field1 = 0;
size_t field2 = 0b1;
size_t field3 = 0b10;
size_t field4 = 0b1000;
size_t field5 = 0b1010;
size_t field6 = 0b1111;
EXPECT_TRUE(isFieldValid(field1, field1));
EXPECT_TRUE(isFieldValid(field1, field2));
EXPECT_TRUE(isFieldValid(field1, field3));
EXPECT_TRUE(isFieldValid(field1, field4));
EXPECT_TRUE(isFieldValid(field1, field5));
EXPECT_TRUE(isFieldValid(field1, field6));
EXPECT_FALSE(isFieldValid(field2, field1));
EXPECT_TRUE(isFieldValid(field2, field2));
EXPECT_FALSE(isFieldValid(field2, field3));
EXPECT_FALSE(isFieldValid(field2, field4));
EXPECT_FALSE(isFieldValid(field2, field5));
EXPECT_TRUE(isFieldValid(field2, field6));
EXPECT_FALSE(isFieldValid(field3, field1));
EXPECT_FALSE(isFieldValid(field3, field2));
EXPECT_TRUE(isFieldValid(field3, field3));
EXPECT_FALSE(isFieldValid(field3, field4));
EXPECT_TRUE(isFieldValid(field3, field5));
EXPECT_TRUE(isFieldValid(field3, field6));
EXPECT_FALSE(isFieldValid(field4, field1));
EXPECT_FALSE(isFieldValid(field4, field2));
EXPECT_FALSE(isFieldValid(field4, field3));
EXPECT_TRUE(isFieldValid(field4, field4));
EXPECT_TRUE(isFieldValid(field4, field5));
EXPECT_TRUE(isFieldValid(field4, field6));
EXPECT_FALSE(isFieldValid(field5, field1));
EXPECT_FALSE(isFieldValid(field5, field2));
EXPECT_FALSE(isFieldValid(field5, field3));
EXPECT_FALSE(isFieldValid(field5, field4));
EXPECT_TRUE(isFieldValid(field5, field5));
EXPECT_TRUE(isFieldValid(field5, field6));
EXPECT_FALSE(isFieldValid(field6, field1));
EXPECT_FALSE(isFieldValid(field6, field2));
EXPECT_FALSE(isFieldValid(field6, field3));
EXPECT_FALSE(isFieldValid(field6, field4));
EXPECT_FALSE(isFieldValid(field6, field5));
EXPECT_TRUE(isFieldValid(field6, field6));
}
TEST(SetBitsTests, givenDifferentValuesWhenTestingSetBitsThenCorrectValueIsReturned) {
EXPECT_EQ(0b0u, setBits(0b0, false, 0b0));
EXPECT_EQ(0b0u, setBits(0b0, false, 0b1));
EXPECT_EQ(0b1u, setBits(0b1, false, 0b0));
EXPECT_EQ(0b0u, setBits(0b1, false, 0b1));
EXPECT_EQ(0b0u, setBits(0b0, true, 0b0));
EXPECT_EQ(0b1u, setBits(0b0, true, 0b1));
EXPECT_EQ(0b1u, setBits(0b1, true, 0b0));
EXPECT_EQ(0b1u, setBits(0b1, true, 0b1));
EXPECT_EQ(0b1010u, setBits(0b1010, false, 0b101));
EXPECT_EQ(0b1111u, setBits(0b1010, true, 0b101));
EXPECT_EQ(0b101u, setBits(0b101, false, 0b1010));
EXPECT_EQ(0b1111u, setBits(0b101, true, 0b1010));
EXPECT_EQ(0b0u, setBits(0b1010, false, 0b1010));
EXPECT_EQ(0b1010u, setBits(0b1010, true, 0b1010));
}
| 35.29
| 96
| 0.726693
|
troels
|
80d44a51c750cbd6805e532bfbf036a23be0346d
| 4,283
|
cpp
|
C++
|
src/qt/qtbase/tests/manual/gestures/graphicsview/gestures.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | 1
|
2020-04-30T15:47:35.000Z
|
2020-04-30T15:47:35.000Z
|
src/qt/qtbase/tests/manual/gestures/graphicsview/gestures.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/tests/manual/gestures/graphicsview/gestures.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "gestures.h"
#include <QTouchEvent>
Qt::GestureType ThreeFingerSlideGesture::Type = Qt::CustomGesture;
QGesture *ThreeFingerSlideGestureRecognizer::create(QObject *)
{
return new ThreeFingerSlideGesture;
}
QGestureRecognizer::Result ThreeFingerSlideGestureRecognizer::recognize(QGesture *state, QObject *, QEvent *event)
{
ThreeFingerSlideGesture *d = static_cast<ThreeFingerSlideGesture *>(state);
QGestureRecognizer::Result result;
switch (event->type()) {
case QEvent::TouchBegin:
result = QGestureRecognizer::MayBeGesture;
case QEvent::TouchEnd:
if (d->gestureFired)
result = QGestureRecognizer::FinishGesture;
else
result = QGestureRecognizer::CancelGesture;
case QEvent::TouchUpdate:
if (d->state() != Qt::NoGesture) {
QTouchEvent *ev = static_cast<QTouchEvent*>(event);
if (ev->touchPoints().size() == 3) {
d->gestureFired = true;
result = QGestureRecognizer::TriggerGesture;
} else {
result = QGestureRecognizer::MayBeGesture;
for (int i = 0; i < ev->touchPoints().size(); ++i) {
const QTouchEvent::TouchPoint &pt = ev->touchPoints().at(i);
const int distance = (pt.pos().toPoint() - pt.startPos().toPoint()).manhattanLength();
if (distance > 20) {
result = QGestureRecognizer::CancelGesture;
}
}
}
} else {
result = QGestureRecognizer::CancelGesture;
}
break;
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove:
if (d->state() != Qt::NoGesture)
result = QGestureRecognizer::Ignore;
else
result = QGestureRecognizer::CancelGesture;
break;
default:
result = QGestureRecognizer::Ignore;
break;
}
return result;
}
void ThreeFingerSlideGestureRecognizer::reset(QGesture *state)
{
static_cast<ThreeFingerSlideGesture *>(state)->gestureFired = false;
QGestureRecognizer::reset(state);
}
QGesture *RotateGestureRecognizer::create(QObject *)
{
return new QGesture;
}
QGestureRecognizer::Result RotateGestureRecognizer::recognize(QGesture *, QObject *, QEvent *event)
{
switch (event->type()) {
case QEvent::TouchBegin:
case QEvent::TouchEnd:
case QEvent::TouchUpdate:
break;
default:
break;
}
return QGestureRecognizer::Ignore;
}
void RotateGestureRecognizer::reset(QGesture *state)
{
QGestureRecognizer::reset(state);
}
#include "moc_gestures.cpp"
| 34.540323
| 114
| 0.646276
|
power-electro
|
80d62f7474f6918680b328a909d7424fc487703b
| 47,022
|
cxx
|
C++
|
swig-2.0.4/Source/Modules/chicken.cxx
|
vidkidz/crossbridge
|
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
|
[
"MIT"
] | 1
|
2016-04-09T02:58:13.000Z
|
2016-04-09T02:58:13.000Z
|
swig-2.0.4/Source/Modules/chicken.cxx
|
vidkidz/crossbridge
|
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
|
[
"MIT"
] | null | null | null |
swig-2.0.4/Source/Modules/chicken.cxx
|
vidkidz/crossbridge
|
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
|
[
"MIT"
] | null | null | null |
/* -----------------------------------------------------------------------------
* This file is part of SWIG, which is licensed as a whole under version 3
* (or any later version) of the GNU General Public License. Some additional
* terms also apply to certain portions of SWIG. The full details of the SWIG
* license and copyrights can be found in the LICENSE and COPYRIGHT files
* included with the SWIG source code as distributed by the SWIG developers
* and at http://www.swig.org/legal.html.
*
* chicken.cxx
*
* CHICKEN language module for SWIG.
* ----------------------------------------------------------------------------- */
char cvsroot_chicken_cxx[] = "$Id: chicken.cxx 12558 2011-03-26 23:25:14Z wsfulton $";
#include "swigmod.h"
#include <ctype.h>
static const char *usage = (char *) "\
\
CHICKEN Options (available with -chicken)\n\
-closprefix <prefix> - Prepend <prefix> to all clos identifiers\n\
-noclosuses - Do not (declare (uses ...)) in scheme file\n\
-nocollection - Do not register pointers with chicken garbage\n\
collector and export destructors\n\
-nounit - Do not (declare (unit ...)) in scheme file\n\
-proxy - Export TinyCLOS class definitions\n\
-unhideprimitive - Unhide the primitive: symbols\n\
-useclassprefix - Prepend the class name to all clos identifiers\n\
\n";
static char *module = 0;
static char *chicken_path = (char *) "chicken";
static int num_methods = 0;
static File *f_begin = 0;
static File *f_runtime = 0;
static File *f_header = 0;
static File *f_wrappers = 0;
static File *f_init = 0;
static String *chickentext = 0;
static String *closprefix = 0;
static String *swigtype_ptr = 0;
static String *f_sym_size = 0;
/* some options */
static int declare_unit = 1;
static int no_collection = 0;
static int clos_uses = 1;
/* C++ Support + Clos Classes */
static int clos = 0;
static String *c_class_name = 0;
static String *class_name = 0;
static String *short_class_name = 0;
static int in_class = 0;
static int have_constructor = 0;
static bool exporting_destructor = false;
static bool exporting_constructor = false;
static String *constructor_name = 0;
static String *member_name = 0;
/* sections of the .scm code */
static String *scm_const_defs = 0;
static String *clos_class_defines = 0;
static String *clos_methods = 0;
/* Some clos options */
static int useclassprefix = 0;
static String *clossymnameprefix = 0;
static int hide_primitive = 1;
static Hash *primitive_names = 0;
/* Used for overloading constructors */
static int has_constructor_args = 0;
static List *constructor_arg_types = 0;
static String *constructor_dispatch = 0;
static Hash *overload_parameter_lists = 0;
class CHICKEN:public Language {
public:
virtual void main(int argc, char *argv[]);
virtual int top(Node *n);
virtual int functionWrapper(Node *n);
virtual int variableWrapper(Node *n);
virtual int constantWrapper(Node *n);
virtual int classHandler(Node *n);
virtual int memberfunctionHandler(Node *n);
virtual int membervariableHandler(Node *n);
virtual int constructorHandler(Node *n);
virtual int destructorHandler(Node *n);
virtual int validIdentifier(String *s);
virtual int staticmembervariableHandler(Node *n);
virtual int staticmemberfunctionHandler(Node *n);
virtual int importDirective(Node *n);
protected:
void addMethod(String *scheme_name, String *function);
/* Return true iff T is a pointer type */
int isPointer(SwigType *t);
void dispatchFunction(Node *n);
String *chickenNameMapping(String *, const_String_or_char_ptr );
String *chickenPrimitiveName(String *);
String *runtimeCode();
String *defaultExternalRuntimeFilename();
String *buildClosFunctionCall(List *types, const_String_or_char_ptr closname, const_String_or_char_ptr funcname);
};
/* -----------------------------------------------------------------------
* swig_chicken() - Instantiate module
* ----------------------------------------------------------------------- */
static Language *new_swig_chicken() {
return new CHICKEN();
}
extern "C" {
Language *swig_chicken(void) {
return new_swig_chicken();
}
}
void CHICKEN::main(int argc, char *argv[]) {
int i;
SWIG_library_directory(chicken_path);
// Look for certain command line options
for (i = 1; i < argc; i++) {
if (argv[i]) {
if (strcmp(argv[i], "-help") == 0) {
fputs(usage, stdout);
SWIG_exit(0);
} else if (strcmp(argv[i], "-proxy") == 0) {
clos = 1;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-closprefix") == 0) {
if (argv[i + 1]) {
clossymnameprefix = NewString(argv[i + 1]);
Swig_mark_arg(i);
Swig_mark_arg(i + 1);
i++;
} else {
Swig_arg_error();
}
} else if (strcmp(argv[i], "-useclassprefix") == 0) {
useclassprefix = 1;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-unhideprimitive") == 0) {
hide_primitive = 0;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-nounit") == 0) {
declare_unit = 0;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-noclosuses") == 0) {
clos_uses = 0;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-nocollection") == 0) {
no_collection = 1;
Swig_mark_arg(i);
}
}
}
if (!clos)
hide_primitive = 0;
// Add a symbol for this module
Preprocessor_define("SWIGCHICKEN 1", 0);
// Set name of typemaps
SWIG_typemap_lang("chicken");
// Read in default typemaps */
SWIG_config_file("chicken.swg");
allow_overloading();
}
int CHICKEN::top(Node *n) {
String *chicken_filename = NewString("");
File *f_scm;
String *scmmodule;
/* Initialize all of the output files */
String *outfile = Getattr(n, "outfile");
f_begin = NewFile(outfile, "w", SWIG_output_files());
if (!f_begin) {
FileErrorDisplay(outfile);
SWIG_exit(EXIT_FAILURE);
}
f_runtime = NewString("");
f_init = NewString("");
f_header = NewString("");
f_wrappers = NewString("");
chickentext = NewString("");
closprefix = NewString("");
f_sym_size = NewString("");
primitive_names = NewHash();
overload_parameter_lists = NewHash();
/* Register file targets with the SWIG file handler */
Swig_register_filebyname("header", f_header);
Swig_register_filebyname("wrapper", f_wrappers);
Swig_register_filebyname("begin", f_begin);
Swig_register_filebyname("runtime", f_runtime);
Swig_register_filebyname("init", f_init);
Swig_register_filebyname("chicken", chickentext);
Swig_register_filebyname("closprefix", closprefix);
clos_class_defines = NewString("");
clos_methods = NewString("");
scm_const_defs = NewString("");
Swig_banner(f_begin);
Printf(f_runtime, "\n");
Printf(f_runtime, "#define SWIGCHICKEN\n");
if (no_collection)
Printf(f_runtime, "#define SWIG_CHICKEN_NO_COLLECTION 1\n");
Printf(f_runtime, "\n");
/* Set module name */
module = Swig_copy_string(Char(Getattr(n, "name")));
scmmodule = NewString(module);
Replaceall(scmmodule, "_", "-");
Printf(f_header, "#define SWIG_init swig_%s_init\n", module);
Printf(f_header, "#define SWIG_name \"%s\"\n", scmmodule);
Printf(f_wrappers, "#ifdef __cplusplus\n");
Printf(f_wrappers, "extern \"C\" {\n");
Printf(f_wrappers, "#endif\n\n");
Language::top(n);
SwigType_emit_type_table(f_runtime, f_wrappers);
Printf(f_wrappers, "#ifdef __cplusplus\n");
Printf(f_wrappers, "}\n");
Printf(f_wrappers, "#endif\n");
Printf(f_init, "C_kontinue (continuation, ret);\n");
Printf(f_init, "}\n\n");
Printf(f_init, "#ifdef __cplusplus\n");
Printf(f_init, "}\n");
Printf(f_init, "#endif\n");
Printf(chicken_filename, "%s%s.scm", SWIG_output_directory(), module);
if ((f_scm = NewFile(chicken_filename, "w", SWIG_output_files())) == 0) {
FileErrorDisplay(chicken_filename);
SWIG_exit(EXIT_FAILURE);
}
Swig_banner_target_lang(f_scm, ";;");
Printf(f_scm, "\n");
if (declare_unit)
Printv(f_scm, "(declare (unit ", scmmodule, "))\n\n", NIL);
Printv(f_scm, "(declare \n",
tab4, "(hide swig-init swig-init-return)\n",
tab4, "(foreign-declare \"C_extern void swig_", module, "_init(C_word,C_word,C_word) C_noret;\"))\n", NIL);
Printv(f_scm, "(define swig-init (##core#primitive \"swig_", module, "_init\"))\n", NIL);
Printv(f_scm, "(define swig-init-return (swig-init))\n\n", NIL);
if (clos) {
//Printf (f_scm, "(declare (uses tinyclos))\n");
//New chicken versions have tinyclos as an egg
Printf(f_scm, "(require-extension tinyclos)\n");
Replaceall(closprefix, "$module", scmmodule);
Printf(f_scm, "%s\n", closprefix);
Printf(f_scm, "%s\n", clos_class_defines);
Printf(f_scm, "%s\n", clos_methods);
} else {
Printf(f_scm, "%s\n", scm_const_defs);
}
Printf(f_scm, "%s\n", chickentext);
Close(f_scm);
Delete(f_scm);
char buftmp[20];
sprintf(buftmp, "%d", num_methods);
Replaceall(f_init, "$nummethods", buftmp);
Replaceall(f_init, "$symsize", f_sym_size);
if (hide_primitive)
Replaceall(f_init, "$veclength", buftmp);
else
Replaceall(f_init, "$veclength", "0");
Delete(chicken_filename);
Delete(chickentext);
Delete(closprefix);
Delete(overload_parameter_lists);
Delete(clos_class_defines);
Delete(clos_methods);
Delete(scm_const_defs);
/* Close all of the files */
Delete(primitive_names);
Delete(scmmodule);
Dump(f_runtime, f_begin);
Dump(f_header, f_begin);
Dump(f_wrappers, f_begin);
Wrapper_pretty_print(f_init, f_begin);
Delete(f_header);
Delete(f_wrappers);
Delete(f_sym_size);
Delete(f_init);
Close(f_begin);
Delete(f_runtime);
Delete(f_begin);
return SWIG_OK;
}
int CHICKEN::functionWrapper(Node *n) {
String *name = Getattr(n, "name");
String *iname = Getattr(n, "sym:name");
SwigType *d = Getattr(n, "type");
ParmList *l = Getattr(n, "parms");
Parm *p;
int i;
String *wname;
Wrapper *f;
String *mangle = NewString("");
String *get_pointers;
String *cleanup;
String *argout;
String *tm;
String *overname = 0;
String *declfunc = 0;
String *scmname;
bool any_specialized_arg = false;
List *function_arg_types = NewList();
int num_required;
int num_arguments;
int have_argout;
Printf(mangle, "\"%s\"", SwigType_manglestr(d));
if (Getattr(n, "sym:overloaded")) {
overname = Getattr(n, "sym:overname");
} else {
if (!addSymbol(iname, n))
return SWIG_ERROR;
}
f = NewWrapper();
wname = NewString("");
get_pointers = NewString("");
cleanup = NewString("");
argout = NewString("");
declfunc = NewString("");
scmname = NewString(iname);
Replaceall(scmname, "_", "-");
/* Local vars */
Wrapper_add_local(f, "resultobj", "C_word resultobj");
/* Write code to extract function parameters. */
emit_parameter_variables(l, f);
/* Attach the standard typemaps */
emit_attach_parmmaps(l, f);
Setattr(n, "wrap:parms", l);
/* Get number of required and total arguments */
num_arguments = emit_num_arguments(l);
num_required = emit_num_required(l);
Append(wname, Swig_name_wrapper(iname));
if (overname) {
Append(wname, overname);
}
// Check for interrupts
Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
Printv(f->def, "static ", "void ", wname, " (C_word argc, C_word closure, C_word continuation", NIL);
Printv(declfunc, "void ", wname, "(C_word,C_word,C_word", NIL);
/* Generate code for argument marshalling */
for (i = 0, p = l; i < num_arguments; i++) {
while (checkAttribute(p, "tmap:in:numinputs", "0")) {
p = Getattr(p, "tmap:in:next");
}
SwigType *pt = Getattr(p, "type");
String *ln = Getattr(p, "lname");
Printf(f->def, ", C_word scm%d", i + 1);
Printf(declfunc, ",C_word");
/* Look for an input typemap */
if ((tm = Getattr(p, "tmap:in"))) {
String *parse = Getattr(p, "tmap:in:parse");
if (!parse) {
String *source = NewStringf("scm%d", i + 1);
Replaceall(tm, "$source", source);
Replaceall(tm, "$target", ln);
Replaceall(tm, "$input", source);
Setattr(p, "emit:input", source); /* Save the location of
the object */
if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
} else {
Replaceall(tm, "$disown", "0");
}
if (i >= num_required)
Printf(get_pointers, "if (argc-2>%i && (%s)) {\n", i, source);
Printv(get_pointers, tm, "\n", NIL);
if (i >= num_required)
Printv(get_pointers, "}\n", NIL);
if (clos) {
if (i < num_required) {
if (strcmp("void", Char(pt)) != 0) {
Node *class_node = 0;
String *clos_code = Getattr(p, "tmap:in:closcode");
class_node = classLookup(pt);
if (clos_code && class_node) {
String *class_name = NewStringf("<%s>", Getattr(class_node, "sym:name"));
Replaceall(class_name, "_", "-");
Append(function_arg_types, class_name);
Append(function_arg_types, Copy(clos_code));
any_specialized_arg = true;
Delete(class_name);
} else {
Append(function_arg_types, "<top>");
Append(function_arg_types, "$input");
}
}
}
}
Delete(source);
}
p = Getattr(p, "tmap:in:next");
continue;
} else {
Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
break;
}
}
/* finish argument marshalling */
Printf(f->def, ") {");
Printf(declfunc, ")");
if (num_required != num_arguments) {
Append(function_arg_types, "^^##optional$$");
}
/* First check the number of arguments is correct */
if (num_arguments != num_required)
Printf(f->code, "if (argc-2<%i || argc-2>%i) C_bad_argc(argc,%i);\n", num_required, num_arguments, num_required + 2);
else
Printf(f->code, "if (argc!=%i) C_bad_argc(argc,%i);\n", num_arguments + 2, num_arguments + 2);
/* Now piece together the first part of the wrapper function */
Printv(f->code, get_pointers, NIL);
/* Insert constraint checking code */
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:check"))) {
Replaceall(tm, "$target", Getattr(p, "lname"));
Printv(f->code, tm, "\n", NIL);
p = Getattr(p, "tmap:check:next");
} else {
p = nextSibling(p);
}
}
/* Insert cleanup code */
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:freearg"))) {
Replaceall(tm, "$source", Getattr(p, "lname"));
Printv(cleanup, tm, "\n", NIL);
p = Getattr(p, "tmap:freearg:next");
} else {
p = nextSibling(p);
}
}
/* Insert argument output code */
have_argout = 0;
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:argout"))) {
if (!have_argout) {
have_argout = 1;
// Print initial argument output code
Printf(argout, "SWIG_Chicken_SetupArgout\n");
}
Replaceall(tm, "$source", Getattr(p, "lname"));
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$arg", Getattr(p, "emit:input"));
Replaceall(tm, "$input", Getattr(p, "emit:input"));
Printf(argout, "%s", tm);
p = Getattr(p, "tmap:argout:next");
} else {
p = nextSibling(p);
}
}
Setattr(n, "wrap:name", wname);
/* Emit the function call */
String *actioncode = emit_action(n);
/* Return the function value */
if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
Replaceall(tm, "$source", "result");
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$result", "resultobj");
if (GetFlag(n, "feature:new")) {
Replaceall(tm, "$owner", "1");
} else {
Replaceall(tm, "$owner", "0");
}
Printf(f->code, "%s", tm);
if (have_argout)
Printf(f->code, "\nSWIG_APPEND_VALUE(resultobj);\n");
} else {
Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
}
emit_return_variable(n, d, f);
/* Insert the argumetn output code */
Printv(f->code, argout, NIL);
/* Output cleanup code */
Printv(f->code, cleanup, NIL);
/* Look to see if there is any newfree cleanup code */
if (GetFlag(n, "feature:new")) {
if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
Replaceall(tm, "$source", "result");
Printf(f->code, "%s\n", tm);
}
}
/* See if there is any return cleanup code */
if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
Replaceall(tm, "$source", "result");
Printf(f->code, "%s\n", tm);
}
if (have_argout) {
Printf(f->code, "C_kontinue(continuation,C_SCHEME_END_OF_LIST);\n");
} else {
if (exporting_constructor && clos && hide_primitive) {
/* Don't return a proxy, the wrapped CLOS class is the proxy */
Printf(f->code, "C_kontinue(continuation,resultobj);\n");
} else {
// make the continuation the proxy creation function, if one exists
Printv(f->code, "{\n",
"C_word func;\n",
"SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
"if (C_swig_is_closurep(func))\n",
" ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
"else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL);
}
}
/* Error handling code */
#ifdef USE_FAIL
Printf(f->code, "fail:\n");
Printv(f->code, cleanup, NIL);
Printf(f->code, "swig_panic (\"failure in " "'$symname' SWIG function wrapper\");\n");
#endif
Printf(f->code, "}\n");
/* Substitute the cleanup code */
Replaceall(f->code, "$cleanup", cleanup);
/* Substitute the function name */
Replaceall(f->code, "$symname", iname);
Replaceall(f->code, "$result", "resultobj");
/* Dump the function out */
Printv(f_wrappers, "static ", declfunc, " C_noret;\n", NIL);
Wrapper_print(f, f_wrappers);
/* Now register the function with the interpreter. */
if (!Getattr(n, "sym:overloaded")) {
if (exporting_destructor && !no_collection) {
Printf(f_init, "((swig_chicken_clientdata *)(SWIGTYPE%s->clientdata))->destroy = (swig_chicken_destructor) %s;\n", swigtype_ptr, wname);
} else {
addMethod(scmname, wname);
}
/* Only export if we are not in a class, or if in a class memberfunction */
if (!in_class || member_name) {
String *method_def;
String *clos_name;
if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
if (!any_specialized_arg) {
method_def = NewString("");
Printv(method_def, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")", NIL);
} else {
method_def = buildClosFunctionCall(function_arg_types, clos_name, chickenPrimitiveName(scmname));
}
Printv(clos_methods, method_def, "\n", NIL);
Delete(clos_name);
Delete(method_def);
}
if (have_constructor && !has_constructor_args && any_specialized_arg) {
has_constructor_args = 1;
constructor_arg_types = Copy(function_arg_types);
}
} else {
/* add function_arg_types to overload hash */
List *flist = Getattr(overload_parameter_lists, scmname);
if (!flist) {
flist = NewList();
Setattr(overload_parameter_lists, scmname, flist);
}
Append(flist, Copy(function_arg_types));
if (!Getattr(n, "sym:nextSibling")) {
dispatchFunction(n);
}
}
Delete(wname);
Delete(get_pointers);
Delete(cleanup);
Delete(declfunc);
Delete(mangle);
Delete(function_arg_types);
DelWrapper(f);
return SWIG_OK;
}
int CHICKEN::variableWrapper(Node *n) {
char *name = GetChar(n, "name");
char *iname = GetChar(n, "sym:name");
SwigType *t = Getattr(n, "type");
ParmList *l = Getattr(n, "parms");
String *wname = NewString("");
String *mangle = NewString("");
String *tm;
String *tm2 = NewString("");
String *argnum = NewString("0");
String *arg = NewString("argv[0]");
Wrapper *f;
String *overname = 0;
String *scmname;
scmname = NewString(iname);
Replaceall(scmname, "_", "-");
Printf(mangle, "\"%s\"", SwigType_manglestr(t));
if (Getattr(n, "sym:overloaded")) {
overname = Getattr(n, "sym:overname");
} else {
if (!addSymbol(iname, n))
return SWIG_ERROR;
}
f = NewWrapper();
/* Attach the standard typemaps */
emit_attach_parmmaps(l, f);
Setattr(n, "wrap:parms", l);
// evaluation function names
Append(wname, Swig_name_wrapper(iname));
if (overname) {
Append(wname, overname);
}
Setattr(n, "wrap:name", wname);
// Check for interrupts
Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) {
Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL);
Printv(f->def, "static " "void ", wname, "(C_word argc, C_word closure, " "C_word continuation, C_word value) {\n", NIL);
Wrapper_add_local(f, "resultobj", "C_word resultobj");
Printf(f->code, "if (argc!=2 && argc!=3) C_bad_argc(argc,2);\n");
/* Check for a setting of the variable value */
if (!GetFlag(n, "feature:immutable")) {
Printf(f->code, "if (argc > 2) {\n");
if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
Replaceall(tm, "$source", "value");
Replaceall(tm, "$target", name);
Replaceall(tm, "$input", "value");
/* Printv(f->code, tm, "\n",NIL); */
emit_action_code(n, f->code, tm);
} else {
Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
}
Printf(f->code, "}\n");
}
String *varname;
if (SwigType_istemplate((char *) name)) {
varname = SwigType_namestr((char *) name);
} else {
varname = name;
}
// Now return the value of the variable - regardless
// of evaluating or setting.
if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
Replaceall(tm, "$source", varname);
Replaceall(tm, "$varname", varname);
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$result", "resultobj");
/* Printf(f->code, "%s\n", tm); */
emit_action_code(n, f->code, tm);
} else {
Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
}
Printv(f->code, "{\n",
"C_word func;\n",
"SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
"if (C_swig_is_closurep(func))\n",
" ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
"else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL);
/* Error handling code */
#ifdef USE_FAIL
Printf(f->code, "fail:\n");
Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name);
#endif
Printf(f->code, "}\n");
Wrapper_print(f, f_wrappers);
/* Now register the variable with the interpreter. */
addMethod(scmname, wname);
if (!in_class || member_name) {
String *clos_name;
if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
Node *class_node = classLookup(t);
String *clos_code = Getattr(n, "tmap:varin:closcode");
if (class_node && clos_code && !GetFlag(n, "feature:immutable")) {
Replaceall(clos_code, "$input", "(car lst)");
Printv(clos_methods, "(define (", clos_name, " . lst) (if (null? lst) (", chickenPrimitiveName(scmname), ") (",
chickenPrimitiveName(scmname), " ", clos_code, ")))\n", NIL);
} else {
/* Simply re-export the procedure */
if (GetFlag(n, "feature:immutable") && GetFlag(n, "feature:constasvar")) {
Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL);
Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL);
} else {
Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL);
}
}
Delete(clos_name);
}
} else {
Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
}
Delete(wname);
Delete(argnum);
Delete(arg);
Delete(tm2);
Delete(mangle);
DelWrapper(f);
return SWIG_OK;
}
/* ------------------------------------------------------------
* constantWrapper()
* ------------------------------------------------------------ */
int CHICKEN::constantWrapper(Node *n) {
char *name = GetChar(n, "name");
char *iname = GetChar(n, "sym:name");
SwigType *t = Getattr(n, "type");
ParmList *l = Getattr(n, "parms");
String *value = Getattr(n, "value");
String *proc_name = NewString("");
String *wname = NewString("");
String *mangle = NewString("");
String *tm;
String *tm2 = NewString("");
String *source = NewString("");
String *argnum = NewString("0");
String *arg = NewString("argv[0]");
Wrapper *f;
String *overname = 0;
String *scmname;
String *rvalue;
SwigType *nctype;
scmname = NewString(iname);
Replaceall(scmname, "_", "-");
Printf(source, "swig_const_%s", iname);
Replaceall(source, "::", "__");
Printf(mangle, "\"%s\"", SwigType_manglestr(t));
if (Getattr(n, "sym:overloaded")) {
overname = Getattr(n, "sym:overname");
} else {
if (!addSymbol(iname, n))
return SWIG_ERROR;
}
Append(wname, Swig_name_wrapper(iname));
if (overname) {
Append(wname, overname);
}
nctype = NewString(t);
if (SwigType_isconst(nctype)) {
Delete(SwigType_pop(nctype));
}
bool is_enum_item = (Cmp(nodeType(n), "enumitem") == 0);
if (SwigType_type(nctype) == T_STRING) {
rvalue = NewStringf("\"%s\"", value);
} else if (SwigType_type(nctype) == T_CHAR && !is_enum_item) {
rvalue = NewStringf("\'%s\'", value);
} else {
rvalue = NewString(value);
}
/* Special hook for member pointer */
if (SwigType_type(t) == T_MPOINTER) {
Printf(f_header, "static %s = %s;\n", SwigType_str(t, source), rvalue);
} else {
if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
Replaceall(tm, "$source", rvalue);
Replaceall(tm, "$target", source);
Replaceall(tm, "$result", source);
Replaceall(tm, "$value", rvalue);
Printf(f_header, "%s\n", tm);
} else {
Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
return SWIG_NOWRAP;
}
}
f = NewWrapper();
/* Attach the standard typemaps */
emit_attach_parmmaps(l, f);
Setattr(n, "wrap:parms", l);
// evaluation function names
// Check for interrupts
Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) {
Setattr(n, "wrap:name", wname);
Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word) C_noret;\n", NIL);
Printv(f->def, "static ", "void ", wname, "(C_word argc, C_word closure, " "C_word continuation) {\n", NIL);
Wrapper_add_local(f, "resultobj", "C_word resultobj");
Printf(f->code, "if (argc!=2) C_bad_argc(argc,2);\n");
// Return the value of the variable
if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
Replaceall(tm, "$source", source);
Replaceall(tm, "$varname", source);
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$result", "resultobj");
/* Printf(f->code, "%s\n", tm); */
emit_action_code(n, f->code, tm);
} else {
Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
}
Printv(f->code, "{\n",
"C_word func;\n",
"SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
"if (C_swig_is_closurep(func))\n",
" ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
"else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL);
/* Error handling code */
#ifdef USE_FAIL
Printf(f->code, "fail:\n");
Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name);
#endif
Printf(f->code, "}\n");
Wrapper_print(f, f_wrappers);
/* Now register the variable with the interpreter. */
addMethod(scmname, wname);
if (!in_class || member_name) {
String *clos_name;
if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
if (GetFlag(n, "feature:constasvar")) {
Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL);
Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL);
} else {
Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL);
}
Delete(clos_name);
}
} else {
Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
}
Delete(wname);
Delete(nctype);
Delete(proc_name);
Delete(argnum);
Delete(arg);
Delete(tm2);
Delete(mangle);
Delete(source);
Delete(rvalue);
DelWrapper(f);
return SWIG_OK;
}
int CHICKEN::classHandler(Node *n) {
/* Create new strings for building up a wrapper function */
have_constructor = 0;
constructor_dispatch = 0;
constructor_name = 0;
c_class_name = NewString(Getattr(n, "sym:name"));
class_name = NewString("");
short_class_name = NewString("");
Printv(class_name, "<", c_class_name, ">", NIL);
Printv(short_class_name, c_class_name, NIL);
Replaceall(class_name, "_", "-");
Replaceall(short_class_name, "_", "-");
if (!addSymbol(class_name, n))
return SWIG_ERROR;
/* Handle inheritance */
String *base_class = NewString("");
List *baselist = Getattr(n, "bases");
if (baselist && Len(baselist)) {
Iterator base = First(baselist);
while (base.item) {
if (!Getattr(base.item, "feature:ignore"))
Printv(base_class, "<", Getattr(base.item, "sym:name"), "> ", NIL);
base = Next(base);
}
}
Replaceall(base_class, "_", "-");
String *scmmod = NewString(module);
Replaceall(scmmod, "_", "-");
Printv(clos_class_defines, "(define ", class_name, "\n", " (make <swig-metaclass-", scmmod, "> 'name \"", short_class_name, "\"\n", NIL);
Delete(scmmod);
if (Len(base_class)) {
Printv(clos_class_defines, " 'direct-supers (list ", base_class, ")\n", NIL);
} else {
Printv(clos_class_defines, " 'direct-supers (list <object>)\n", NIL);
}
Printf(clos_class_defines, " 'direct-slots (list 'swig-this\n");
String *mangled_classname = Swig_name_mangle(Getattr(n, "sym:name"));
SwigType *ct = NewStringf("p.%s", Getattr(n, "name"));
swigtype_ptr = SwigType_manglestr(ct);
Printf(f_runtime, "static swig_chicken_clientdata _swig_chicken_clientdata%s = { 0 };\n", mangled_classname);
Printv(f_init, "SWIG_TypeClientData(SWIGTYPE", swigtype_ptr, ", (void *) &_swig_chicken_clientdata", mangled_classname, ");\n", NIL);
SwigType_remember(ct);
/* Emit all of the members */
in_class = 1;
Language::classHandler(n);
in_class = 0;
Printf(clos_class_defines, ")))\n\n");
if (have_constructor) {
Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", " (swig-initialize obj initargs ", NIL);
if (constructor_arg_types) {
String *initfunc_name = NewStringf("%s@@SWIG@initmethod", class_name);
String *func_call = buildClosFunctionCall(constructor_arg_types, initfunc_name, chickenPrimitiveName(constructor_name));
Printf(clos_methods, "%s)\n)\n", initfunc_name);
Printf(clos_methods, "(declare (hide %s))\n", initfunc_name);
Printf(clos_methods, "%s\n", func_call);
Delete(func_call);
Delete(initfunc_name);
Delete(constructor_arg_types);
constructor_arg_types = 0;
} else if (constructor_dispatch) {
Printf(clos_methods, "%s)\n)\n", constructor_dispatch);
Delete(constructor_dispatch);
constructor_dispatch = 0;
} else {
Printf(clos_methods, "%s)\n)\n", chickenPrimitiveName(constructor_name));
}
Delete(constructor_name);
constructor_name = 0;
} else {
Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", " (swig-initialize obj initargs (lambda x #f)))\n", NIL);
}
/* export class initialization function */
if (clos) {
String *funcname = NewString(mangled_classname);
Printf(funcname, "_swig_chicken_setclosclass");
String *closfuncname = NewString(funcname);
Replaceall(closfuncname, "_", "-");
Printv(f_wrappers, "static void ", funcname, "(C_word,C_word,C_word,C_word) C_noret;\n",
"static void ", funcname, "(C_word argc, C_word closure, C_word continuation, C_word cl) {\n",
" C_trace(\"", funcname, "\");\n",
" if (argc!=3) C_bad_argc(argc,3);\n",
" swig_chicken_clientdata *cdata = (swig_chicken_clientdata *) SWIGTYPE", swigtype_ptr, "->clientdata;\n",
" cdata->gc_proxy_create = CHICKEN_new_gc_root();\n",
" CHICKEN_gc_root_set(cdata->gc_proxy_create, cl);\n", " C_kontinue(continuation, C_SCHEME_UNDEFINED);\n", "}\n", NIL);
addMethod(closfuncname, funcname);
Printv(clos_methods, "(", chickenPrimitiveName(closfuncname), " (lambda (x lst) (if lst ",
"(cons (make ", class_name, " 'swig-this x) lst) ", "(make ", class_name, " 'swig-this x))))\n\n", NIL);
Delete(closfuncname);
Delete(funcname);
}
Delete(mangled_classname);
Delete(swigtype_ptr);
swigtype_ptr = 0;
Delete(class_name);
Delete(short_class_name);
Delete(c_class_name);
class_name = 0;
short_class_name = 0;
c_class_name = 0;
return SWIG_OK;
}
int CHICKEN::memberfunctionHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
member_name = chickenNameMapping(proc, short_class_name);
Language::memberfunctionHandler(n);
Delete(member_name);
member_name = NULL;
Delete(proc);
return SWIG_OK;
}
int CHICKEN::staticmemberfunctionHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
member_name = NewStringf("%s-%s", short_class_name, proc);
Language::staticmemberfunctionHandler(n);
Delete(member_name);
member_name = NULL;
Delete(proc);
return SWIG_OK;
}
int CHICKEN::membervariableHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
//String *pb = SwigType_typedef_resolve_all(SwigType_base(Getattr(n, "type")));
Language::membervariableHandler(n);
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
//Node *class_node = Swig_symbol_clookup(pb, Getattr(n, "sym:symtab"));
Node *class_node = classLookup(Getattr(n, "type"));
//String *getfunc = NewStringf("%s-%s-get", short_class_name, proc);
//String *setfunc = NewStringf("%s-%s-set", short_class_name, proc);
String *getfunc = Swig_name_get(NSPACE_TODO, Swig_name_member(NSPACE_TODO, c_class_name, iname));
Replaceall(getfunc, "_", "-");
String *setfunc = Swig_name_set(NSPACE_TODO, Swig_name_member(NSPACE_TODO, c_class_name, iname));
Replaceall(setfunc, "_", "-");
Printv(clos_class_defines, " (list '", proc, " ':swig-virtual ':swig-get ", chickenPrimitiveName(getfunc), NIL);
if (!GetFlag(n, "feature:immutable")) {
if (class_node) {
Printv(clos_class_defines, " ':swig-set (lambda (x y) (", chickenPrimitiveName(setfunc), " x (slot-ref y 'swig-this))))\n", NIL);
} else {
Printv(clos_class_defines, " ':swig-set ", chickenPrimitiveName(setfunc), ")\n", NIL);
}
} else {
Printf(clos_class_defines, ")\n");
}
Delete(proc);
Delete(setfunc);
Delete(getfunc);
return SWIG_OK;
}
int CHICKEN::staticmembervariableHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
member_name = NewStringf("%s-%s", short_class_name, proc);
Language::staticmembervariableHandler(n);
Delete(member_name);
member_name = NULL;
Delete(proc);
return SWIG_OK;
}
int CHICKEN::constructorHandler(Node *n) {
have_constructor = 1;
has_constructor_args = 0;
exporting_constructor = true;
Language::constructorHandler(n);
exporting_constructor = false;
has_constructor_args = 1;
String *iname = Getattr(n, "sym:name");
constructor_name = Swig_name_construct(NSPACE_TODO, iname);
Replaceall(constructor_name, "_", "-");
return SWIG_OK;
}
int CHICKEN::destructorHandler(Node *n) {
if (no_collection)
member_name = NewStringf("delete-%s", short_class_name);
exporting_destructor = true;
Language::destructorHandler(n);
exporting_destructor = false;
if (no_collection) {
Delete(member_name);
member_name = NULL;
}
return SWIG_OK;
}
int CHICKEN::importDirective(Node *n) {
String *modname = Getattr(n, "module");
if (modname && clos_uses) {
// Find the module node for this imported module. It should be the
// first child but search just in case.
Node *mod = firstChild(n);
while (mod && Strcmp(nodeType(mod), "module") != 0)
mod = nextSibling(mod);
if (mod) {
String *name = Getattr(mod, "name");
if (name) {
Printf(closprefix, "(declare (uses %s))\n", name);
}
}
}
return Language::importDirective(n);
}
String *CHICKEN::buildClosFunctionCall(List *types, const_String_or_char_ptr closname, const_String_or_char_ptr funcname) {
String *method_signature = NewString("");
String *func_args = NewString("");
String *func_call = NewString("");
Iterator arg_type;
int arg_count = 0;
int optional_arguments = 0;
for (arg_type = First(types); arg_type.item; arg_type = Next(arg_type)) {
if (Strcmp(arg_type.item, "^^##optional$$") == 0) {
optional_arguments = 1;
} else {
Printf(method_signature, " (arg%i %s)", arg_count, arg_type.item);
arg_type = Next(arg_type);
if (!arg_type.item)
break;
String *arg = NewStringf("arg%i", arg_count);
String *access_arg = Copy(arg_type.item);
Replaceall(access_arg, "$input", arg);
Printf(func_args, " %s", access_arg);
Delete(arg);
Delete(access_arg);
}
arg_count++;
}
if (optional_arguments) {
Printf(func_call, "(define-method (%s %s . args) (apply %s %s args))", closname, method_signature, funcname, func_args);
} else {
Printf(func_call, "(define-method (%s %s) (%s %s))", closname, method_signature, funcname, func_args);
}
Delete(method_signature);
Delete(func_args);
return func_call;
}
extern "C" {
/* compares based on non-primitive names */
static int compareTypeListsHelper(const DOH *a, const DOH *b, int opt_equal) {
List *la = (List *) a;
List *lb = (List *) b;
Iterator ia = First(la);
Iterator ib = First(lb);
while (ia.item && ib.item) {
int ret = Strcmp(ia.item, ib.item);
if (ret)
return ret;
ia = Next(Next(ia));
ib = Next(Next(ib));
} if (opt_equal && ia.item && Strcmp(ia.item, "^^##optional$$") == 0)
return 0;
if (ia.item)
return -1;
if (opt_equal && ib.item && Strcmp(ib.item, "^^##optional$$") == 0)
return 0;
if (ib.item)
return 1;
return 0;
}
static int compareTypeLists(const DOH *a, const DOH *b) {
return compareTypeListsHelper(a, b, 0);
}
}
void CHICKEN::dispatchFunction(Node *n) {
/* Last node in overloaded chain */
int maxargs;
String *tmp = NewString("");
String *dispatch = Swig_overload_dispatch(n, "%s (2+$numargs,closure," "continuation$commaargs);", &maxargs);
/* Generate a dispatch wrapper for all overloaded functions */
Wrapper *f = NewWrapper();
String *iname = Getattr(n, "sym:name");
String *wname = NewString("");
String *scmname = NewString(iname);
Replaceall(scmname, "_", "-");
Append(wname, Swig_name_wrapper(iname));
Printv(f->def, "static void real_", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL);
Printv(f->def, "static void real_", wname, "(C_word oldargc, C_word closure, C_word continuation, C_word args) {", NIL);
Wrapper_add_local(f, "argc", "int argc");
Printf(tmp, "C_word argv[%d]", maxargs + 1);
Wrapper_add_local(f, "argv", tmp);
Wrapper_add_local(f, "ii", "int ii");
Wrapper_add_local(f, "t", "C_word t = args");
Printf(f->code, "if (!C_swig_is_list (args)) {\n");
Printf(f->code, " swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, " "\"Argument #1 must be a list of overloaded arguments\");\n");
Printf(f->code, "}\n");
Printf(f->code, "argc = C_unfix (C_i_length (args));\n");
Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++, t = C_block_item (t, 1)) {\n", maxargs);
Printf(f->code, "argv[ii] = C_block_item (t, 0);\n");
Printf(f->code, "}\n");
Printv(f->code, dispatch, "\n", NIL);
Printf(f->code, "swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE," "\"No matching function for overloaded '%s'\");\n", iname);
Printv(f->code, "}\n", NIL);
Wrapper_print(f, f_wrappers);
addMethod(scmname, wname);
DelWrapper(f);
f = NewWrapper();
/* varargs */
Printv(f->def, "void ", wname, "(C_word, C_word, C_word, ...) C_noret;\n", NIL);
Printv(f->def, "void ", wname, "(C_word c, C_word t0, C_word t1, ...) {", NIL);
Printv(f->code,
"C_word t2;\n",
"va_list v;\n",
"C_word *a, c2 = c;\n",
"C_save_rest (t1, c2, 2);\n", "a = C_alloc((c-2)*3);\n", "t2 = C_restore_rest (a, C_rest_count (0));\n", "real_", wname, " (3, t0, t1, t2);\n", NIL);
Printv(f->code, "}\n", NIL);
Wrapper_print(f, f_wrappers);
/* Now deal with overloaded function when exporting clos */
if (clos) {
List *flist = Getattr(overload_parameter_lists, scmname);
if (flist) {
Delattr(overload_parameter_lists, scmname);
SortList(flist, compareTypeLists);
String *clos_name;
if (have_constructor && !has_constructor_args) {
has_constructor_args = 1;
constructor_dispatch = NewStringf("%s@SWIG@new@dispatch", short_class_name);
clos_name = Copy(constructor_dispatch);
Printf(clos_methods, "(declare (hide %s))\n", clos_name);
} else if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
Iterator f;
List *prev = 0;
int all_primitive = 1;
/* first check for duplicates and an empty call */
String *newlist = NewList();
for (f = First(flist); f.item; f = Next(f)) {
/* check if cur is a duplicate of prev */
if (prev && compareTypeListsHelper(f.item, prev, 1) == 0) {
Delete(f.item);
} else {
Append(newlist, f.item);
prev = f.item;
Iterator j;
for (j = First(f.item); j.item; j = Next(j)) {
if (Strcmp(j.item, "^^##optional$$") != 0 && Strcmp(j.item, "<top>") != 0)
all_primitive = 0;
}
}
}
Delete(flist);
flist = newlist;
if (all_primitive) {
Printf(clos_methods, "(define %s %s)\n", clos_name, chickenPrimitiveName(scmname));
} else {
for (f = First(flist); f.item; f = Next(f)) {
/* now export clos code for argument */
String *func_call = buildClosFunctionCall(f.item, clos_name, chickenPrimitiveName(scmname));
Printf(clos_methods, "%s\n", func_call);
Delete(f.item);
Delete(func_call);
}
}
Delete(clos_name);
Delete(flist);
}
}
DelWrapper(f);
Delete(dispatch);
Delete(tmp);
Delete(wname);
}
int CHICKEN::isPointer(SwigType *t) {
return SwigType_ispointer(SwigType_typedef_resolve_all(t));
}
void CHICKEN::addMethod(String *scheme_name, String *function) {
String *sym = NewString("");
if (clos) {
Append(sym, "primitive:");
}
Append(sym, scheme_name);
/* add symbol to Chicken internal symbol table */
if (hide_primitive) {
Printv(f_init, "{\n",
" C_word *p0 = a;\n", " *(a++)=C_CLOSURE_TYPE|1;\n", " *(a++)=(C_word)", function, ";\n", " C_mutate(return_vec++, (C_word)p0);\n", "}\n", NIL);
} else {
Printf(f_sym_size, "+C_SIZEOF_INTERNED_SYMBOL(%d)", Len(sym));
Printf(f_init, "sym = C_intern (&a, %d, \"%s\");\n", Len(sym), sym);
Printv(f_init, "C_mutate ((C_word*)sym+1, (*a=C_CLOSURE_TYPE|1, a[1]=(C_word)", function, ", tmp=(C_word)a, a+=2, tmp));\n", NIL);
}
if (hide_primitive) {
Setattr(primitive_names, scheme_name, NewStringf("(vector-ref swig-init-return %i)", num_methods));
} else {
Setattr(primitive_names, scheme_name, Copy(sym));
}
num_methods++;
Delete(sym);
}
String *CHICKEN::chickenPrimitiveName(String *name) {
String *value = Getattr(primitive_names, name);
if (value)
return value;
else {
Swig_error(input_file, line_number, "Internal Error: attempting to reference non-existant primitive name %s\n", name);
return NewString("#f");
}
}
int CHICKEN::validIdentifier(String *s) {
char *c = Char(s);
/* Check whether we have an R5RS identifier. */
/* <identifier> --> <initial> <subsequent>* | <peculiar identifier> */
/* <initial> --> <letter> | <special initial> */
if (!(isalpha(*c) || (*c == '!') || (*c == '$') || (*c == '%')
|| (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
|| (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
|| (*c == '^') || (*c == '_') || (*c == '~'))) {
/* <peculiar identifier> --> + | - | ... */
if ((strcmp(c, "+") == 0)
|| strcmp(c, "-") == 0 || strcmp(c, "...") == 0)
return 1;
else
return 0;
}
/* <subsequent> --> <initial> | <digit> | <special subsequent> */
while (*c) {
if (!(isalnum(*c) || (*c == '!') || (*c == '$') || (*c == '%')
|| (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
|| (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
|| (*c == '^') || (*c == '_') || (*c == '~') || (*c == '+')
|| (*c == '-') || (*c == '.') || (*c == '@')))
return 0;
c++;
}
return 1;
}
/* ------------------------------------------------------------
* closNameMapping()
* Maps the identifier from C++ to the CLOS based on command
* line parameters and such.
* If class_name = "" that means the mapping is for a function or
* variable not attached to any class.
* ------------------------------------------------------------ */
String *CHICKEN::chickenNameMapping(String *name, const_String_or_char_ptr class_name) {
String *n = NewString("");
if (Strcmp(class_name, "") == 0) {
// not part of a class, so no class name to prefix
if (clossymnameprefix) {
Printf(n, "%s%s", clossymnameprefix, name);
} else {
Printf(n, "%s", name);
}
} else {
if (useclassprefix) {
Printf(n, "%s-%s", class_name, name);
} else {
if (clossymnameprefix) {
Printf(n, "%s%s", clossymnameprefix, name);
} else {
Printf(n, "%s", name);
}
}
}
return n;
}
String *CHICKEN::runtimeCode() {
String *s = Swig_include_sys("chickenrun.swg");
if (!s) {
Printf(stderr, "*** Unable to open 'chickenrun.swg'\n");
s = NewString("");
}
return s;
}
String *CHICKEN::defaultExternalRuntimeFilename() {
return NewString("swigchickenrun.h");
}
| 30.494163
| 152
| 0.624304
|
vidkidz
|
80d88d4fa9985eeb6a8132df0ff0bd361615a33b
| 1,966
|
hpp
|
C++
|
include/solaire/parallel/thread_pool_executor.hpp
|
SolaireLibrary/solaire_parallel
|
eed82815215e1eb60b7ca29e19720f6707966383
|
[
"Apache-2.0"
] | null | null | null |
include/solaire/parallel/thread_pool_executor.hpp
|
SolaireLibrary/solaire_parallel
|
eed82815215e1eb60b7ca29e19720f6707966383
|
[
"Apache-2.0"
] | null | null | null |
include/solaire/parallel/thread_pool_executor.hpp
|
SolaireLibrary/solaire_parallel
|
eed82815215e1eb60b7ca29e19720f6707966383
|
[
"Apache-2.0"
] | null | null | null |
#ifndef SOLAIRE_PARALEL_THREAD_POOL_EXECUTOR_HPP
#define SOLAIRE_PARALEL_THREAD_POOL_EXECUTOR_HPP
//Copyright 2016 Adam G. Smith
//
//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 <vector>
#include "solaire/parallel/task_executor.hpp"
namespace solaire {
class thread_pool_executor : public task_executor {
private:
std::thread* const mWorkerThreads;
std::vector<std::function<void()>> mTasks;
std::mutex mTasksLock;
std::condition_variable mTaskAdded;
const uint32_t mThreadCount;
bool mExit;
protected:
// inherited from task_executor
void _schedule(std::function<void()> aTask) override {
mTasksLock.lock();
mTasks.push_back(aTask);
mTasksLock.unlock();
mTaskAdded.notify_one();
}
public:
thread_pool_executor(uint32_t aThreadCount) :
mWorkerThreads(new std::thread[aThreadCount]),
mThreadCount(aThreadCount),
mExit(false)
{
const auto threadFn = [this]() {
while(! mExit) {
std::unique_lock<std::mutex> lock(mTasksLock);
mTaskAdded.wait(lock);
if(! mTasks.empty()) {
std::function<void()> task = mTasks.back();
mTasks.pop_back();
lock.unlock();
task();
}
}
};
for(uint32_t i = 0; i < aThreadCount; ++i) mWorkerThreads[i] = std::thread(threadFn);
}
~thread_pool_executor() {
mExit = true;
mTaskAdded.notify_all();
for (uint32_t i = 0; i < mThreadCount; ++i) mWorkerThreads[i].join();
delete[] mWorkerThreads;
}
};
}
#endif
| 26.931507
| 88
| 0.706002
|
SolaireLibrary
|
80d950eacccf88a798578ce38845f2308be757aa
| 757
|
hpp
|
C++
|
src/include/duckdb/planner/operator/logical_copy_to_file.hpp
|
RelationalAI-oss/duckdb
|
a4908ae17de3ac62d42633ada03077b8c3ead7a5
|
[
"MIT"
] | 2
|
2020-01-07T17:19:02.000Z
|
2020-01-09T22:04:04.000Z
|
src/include/duckdb/planner/operator/logical_copy_to_file.hpp
|
RelationalAI-oss/duckdb
|
a4908ae17de3ac62d42633ada03077b8c3ead7a5
|
[
"MIT"
] | null | null | null |
src/include/duckdb/planner/operator/logical_copy_to_file.hpp
|
RelationalAI-oss/duckdb
|
a4908ae17de3ac62d42633ada03077b8c3ead7a5
|
[
"MIT"
] | null | null | null |
//===----------------------------------------------------------------------===//
// DuckDB
//
// planner/operator/logical_copy_to_file.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/parser/parsed_data/copy_info.hpp"
#include "duckdb/planner/logical_operator.hpp"
namespace duckdb {
class LogicalCopyToFile : public LogicalOperator {
public:
LogicalCopyToFile(unique_ptr<CopyInfo> info)
: LogicalOperator(LogicalOperatorType::COPY_TO_FILE), info(move(info)) {
}
unique_ptr<CopyInfo> info;
vector<string> names;
vector<SQLType> sql_types;
protected:
void ResolveTypes() override {
types.push_back(TypeId::BIGINT);
}
};
} // namespace duckdb
| 23.65625
| 80
| 0.569353
|
RelationalAI-oss
|
80dac28b65282292b53ef42d11aebcca5f92f82d
| 1,664
|
cpp
|
C++
|
implementations/ugene/src/corelibs/U2Lang/src/library/BaseThroughWorker.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
implementations/ugene/src/corelibs/U2Lang/src/library/BaseThroughWorker.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
implementations/ugene/src/corelibs/U2Lang/src/library/BaseThroughWorker.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "BaseThroughWorker.h"
#include <U2Core/U2OpStatusUtils.h>
namespace U2 {
namespace LocalWorkflow {
BaseThroughWorker::BaseThroughWorker(Actor *a, const QString &inPortId, const QString &outPortId)
: BaseOneOneWorker(a, /* autoTransitBus= */ true, inPortId, outPortId) {
}
void BaseThroughWorker::cleanup() {
}
Task *BaseThroughWorker::processNextInputMessage() {
const Message message = getMessageAndSetupScriptValues(input);
U2OpStatusImpl os;
Task *task = createTask(message, os);
if (os.hasError()) {
reportError(os.getError());
}
return task;
}
Task *BaseThroughWorker::onInputEnded() {
return NULL;
}
Message BaseThroughWorker::composeMessage(const QVariantMap &data) {
return Message(output->getBusType(), data);
}
} // namespace LocalWorkflow
} // namespace U2
| 29.714286
| 97
| 0.736178
|
r-barnes
|
80db0115de030b7e18548330d48487d3542a06e7
| 3,336
|
cpp
|
C++
|
vnext/Desktop.UnitTests/WebSocketMocks.cpp
|
harinikmsft/react-native-windows
|
c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21
|
[
"MIT"
] | null | null | null |
vnext/Desktop.UnitTests/WebSocketMocks.cpp
|
harinikmsft/react-native-windows
|
c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21
|
[
"MIT"
] | null | null | null |
vnext/Desktop.UnitTests/WebSocketMocks.cpp
|
harinikmsft/react-native-windows
|
c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21
|
[
"MIT"
] | null | null | null |
#include "WebSocketMocks.h"
using std::exception;
using std::function;
using std::string;
namespace Microsoft::React::Test {
MockWebSocketResource::~MockWebSocketResource() {}
#pragma region IWebSocketResource overrides
void MockWebSocketResource::Connect(const Protocols &protocols, const Options &options) noexcept /*override*/
{
if (Mocks.Connect)
return Mocks.Connect(protocols, options);
}
void MockWebSocketResource::Ping() noexcept /*override*/
{
if (Mocks.Connect)
return Mocks.Ping();
}
void MockWebSocketResource::Send(const string &message) noexcept /*override*/
{
if (Mocks.Send)
return Mocks.Send(message);
}
void MockWebSocketResource::SendBinary(const string &message) noexcept /*override*/
{
if (Mocks.SendBinary)
return Mocks.SendBinary(message);
}
void MockWebSocketResource::Close(CloseCode code, const string &reason) noexcept /*override*/
{
if (Mocks.Close)
return Mocks.Close(code, reason);
}
IWebSocketResource::ReadyState MockWebSocketResource::GetReadyState() const noexcept /*override*/
{
if (Mocks.GetReadyState)
return Mocks.GetReadyState();
return ReadyState::Connecting;
}
void MockWebSocketResource::SetOnConnect(function<void()> &&handler) noexcept /*override*/
{
if (Mocks.SetOnConnect)
return SetOnConnect(std::move(handler));
m_connectHandler = std::move(handler);
}
void MockWebSocketResource::SetOnPing(function<void()> &&handler) noexcept /*override*/
{
if (Mocks.SetOnPing)
return Mocks.SetOnPing(std::move(handler));
m_pingHandler = std::move(handler);
}
void MockWebSocketResource::SetOnSend(function<void(size_t)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnSend)
return Mocks.SetOnSend(std::move(handler));
m_writeHandler = std::move(handler);
}
void MockWebSocketResource::SetOnMessage(function<void(size_t, const string &)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnMessage)
return Mocks.SetOnMessage(std::move(handler));
m_readHandler = std::move(handler);
}
void MockWebSocketResource::SetOnClose(function<void(CloseCode, const string &)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnClose)
return Mocks.SetOnClose(std::move(handler));
m_closeHandler = std::move(handler);
}
void MockWebSocketResource::SetOnError(function<void(Error &&)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnError)
return Mocks.SetOnError(std::move(handler));
m_errorHandler = std::move(handler);
}
#pragma endregion IWebSocketResource overrides
void MockWebSocketResource::OnConnect() {
if (m_connectHandler)
m_connectHandler();
}
void MockWebSocketResource::OnPing() {
if (m_pingHandler)
m_pingHandler();
}
void MockWebSocketResource::OnSend(size_t size) {
if (m_writeHandler)
m_writeHandler(size);
}
void MockWebSocketResource::OnMessage(size_t size, const string &message) {
if (m_readHandler)
m_readHandler(size, message);
}
void MockWebSocketResource::OnClose(CloseCode code, const string &reason) {
if (m_closeHandler)
m_closeHandler(code, reason);
}
void MockWebSocketResource::OnError(Error &&error) {
if (m_errorHandler)
m_errorHandler(std::move(error));
}
} // namespace Microsoft::React::Test
| 25.272727
| 114
| 0.711331
|
harinikmsft
|
80dbdafa854a5fc9ea6377dadef58a78acdda782
| 1,299
|
cpp
|
C++
|
level_zero/tools/source/sysman/engine/linux/os_engine_imp.cpp
|
8tab/compute-runtime
|
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
|
[
"MIT"
] | null | null | null |
level_zero/tools/source/sysman/engine/linux/os_engine_imp.cpp
|
8tab/compute-runtime
|
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
|
[
"MIT"
] | null | null | null |
level_zero/tools/source/sysman/engine/linux/os_engine_imp.cpp
|
8tab/compute-runtime
|
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/tools/source/sysman/engine/linux/os_engine_imp.h"
namespace L0 {
const std::string LinuxEngineImp::computeEngineGroupFile("engine/rcs0/name");
const std::string LinuxEngineImp::computeEngineGroupName("rcs0");
ze_result_t LinuxEngineImp::getActiveTime(uint64_t &activeTime) {
return ZE_RESULT_ERROR_UNSUPPORTED_FEATURE;
}
ze_result_t LinuxEngineImp::getEngineGroup(zet_engine_group_t &engineGroup) {
std::string strVal;
ze_result_t result = pSysfsAccess->read(computeEngineGroupFile, strVal);
if (ZE_RESULT_SUCCESS != result) {
return result;
}
if (strVal.compare(computeEngineGroupName) == 0) {
engineGroup = ZET_ENGINE_GROUP_COMPUTE_ALL;
} else {
engineGroup = ZET_ENGINE_GROUP_ALL;
return ZE_RESULT_ERROR_UNKNOWN;
}
return result;
}
LinuxEngineImp::LinuxEngineImp(OsSysman *pOsSysman) {
LinuxSysmanImp *pLinuxSysmanImp = static_cast<LinuxSysmanImp *>(pOsSysman);
pSysfsAccess = &pLinuxSysmanImp->getSysfsAccess();
}
OsEngine *OsEngine::create(OsSysman *pOsSysman) {
LinuxEngineImp *pLinuxEngineImp = new LinuxEngineImp(pOsSysman);
return static_cast<OsEngine *>(pLinuxEngineImp);
}
} // namespace L0
| 29.522727
| 79
| 0.744419
|
8tab
|
80def142bb58b6c555024ff734b0fbd06536ef52
| 484
|
cpp
|
C++
|
test/lib/BookmarkSerializer_test.cpp
|
alepez/bmrk
|
04db2646b42662b976b4f4a1a5fb414ca73df163
|
[
"MIT"
] | null | null | null |
test/lib/BookmarkSerializer_test.cpp
|
alepez/bmrk
|
04db2646b42662b976b4f4a1a5fb414ca73df163
|
[
"MIT"
] | null | null | null |
test/lib/BookmarkSerializer_test.cpp
|
alepez/bmrk
|
04db2646b42662b976b4f4a1a5fb414ca73df163
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <BookmarkSerializer.hpp>
#include "helpers.hpp"
namespace bmrk {
struct BookmarkSerializerTest: public testing::Test {
BookmarkSerializer bs;
};
TEST_F(BookmarkSerializerTest, CanSerialize) {
auto bookmark = createMockBookmark(
"http://pezzato.net", "one", Tags({"foo", "bar"}), "two");
std::stringstream stream;
bs.serialize(&stream, bookmark);
ASSERT_EQ("http://pezzato.net\none\nfoo,bar\ntwo\n", stream.str());
}
} /* bmrk */
| 22
| 69
| 0.700413
|
alepez
|
80e113e820b3058dd2e1b49d6c010ebe45526857
| 7,582
|
cc
|
C++
|
src/net/third_party/quiche/src/http2/adapter/test_utils.cc
|
kvmb/naiveproxy
|
8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d
|
[
"BSD-3-Clause"
] | 3
|
2020-05-31T16:20:21.000Z
|
2021-09-05T20:39:50.000Z
|
src/net/third_party/quiche/src/http2/adapter/test_utils.cc
|
LImboing/naiveproxy
|
8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d
|
[
"BSD-3-Clause"
] | 11
|
2019-10-15T23:03:57.000Z
|
2020-06-14T16:10:12.000Z
|
src/net/third_party/quiche/src/http2/adapter/test_utils.cc
|
LImboing/naiveproxy
|
8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d
|
[
"BSD-3-Clause"
] | 7
|
2019-07-04T14:23:54.000Z
|
2020-04-27T08:52:51.000Z
|
#include "http2/adapter/test_utils.h"
#include <ostream>
#include "absl/strings/str_format.h"
#include "common/quiche_endian.h"
#include "spdy/core/hpack/hpack_encoder.h"
#include "spdy/core/spdy_frame_reader.h"
namespace http2 {
namespace adapter {
namespace test {
TestDataFrameSource::TestDataFrameSource(Http2VisitorInterface& visitor,
bool has_fin)
: visitor_(visitor), has_fin_(has_fin) {}
void TestDataFrameSource::AppendPayload(absl::string_view payload) {
QUICHE_CHECK(!end_data_);
if (!payload.empty()) {
payload_fragments_.push_back(std::string(payload));
current_fragment_ = payload_fragments_.front();
}
}
void TestDataFrameSource::EndData() { end_data_ = true; }
std::pair<int64_t, bool> TestDataFrameSource::SelectPayloadLength(
size_t max_length) {
// The stream is done if there's no more data, or if |max_length| is at least
// as large as the remaining data.
const bool end_data = end_data_ && (current_fragment_.empty() ||
(payload_fragments_.size() == 1 &&
max_length >= current_fragment_.size()));
const int64_t length = std::min(max_length, current_fragment_.size());
return {length, end_data};
}
bool TestDataFrameSource::Send(absl::string_view frame_header,
size_t payload_length) {
QUICHE_LOG_IF(DFATAL, payload_length > current_fragment_.size())
<< "payload_length: " << payload_length
<< " current_fragment_size: " << current_fragment_.size();
const std::string concatenated =
absl::StrCat(frame_header, current_fragment_.substr(0, payload_length));
const int64_t result = visitor_.OnReadyToSend(concatenated);
if (result < 0) {
// Write encountered error.
visitor_.OnConnectionError();
current_fragment_ = {};
payload_fragments_.clear();
return false;
} else if (result == 0) {
// Write blocked.
return false;
} else if (static_cast<const size_t>(result) < concatenated.size()) {
// Probably need to handle this better within this test class.
QUICHE_LOG(DFATAL)
<< "DATA frame not fully flushed. Connection will be corrupt!";
visitor_.OnConnectionError();
current_fragment_ = {};
payload_fragments_.clear();
return false;
}
if (payload_length > 0) {
current_fragment_.remove_prefix(payload_length);
}
if (current_fragment_.empty() && !payload_fragments_.empty()) {
payload_fragments_.erase(payload_fragments_.begin());
if (!payload_fragments_.empty()) {
current_fragment_ = payload_fragments_.front();
}
}
return true;
}
std::string EncodeHeaders(const spdy::SpdyHeaderBlock& entries) {
spdy::HpackEncoder encoder;
encoder.DisableCompression();
return encoder.EncodeHeaderBlock(entries);
}
TestMetadataSource::TestMetadataSource(const spdy::SpdyHeaderBlock& entries)
: encoded_entries_(EncodeHeaders(entries)) {
remaining_ = encoded_entries_;
}
std::pair<int64_t, bool> TestMetadataSource::Pack(uint8_t* dest,
size_t dest_len) {
const size_t copied = std::min(dest_len, remaining_.size());
std::memcpy(dest, remaining_.data(), copied);
remaining_.remove_prefix(copied);
return std::make_pair(copied, remaining_.empty());
}
namespace {
using TypeAndOptionalLength =
std::pair<spdy::SpdyFrameType, absl::optional<size_t>>;
std::ostream& operator<<(
std::ostream& os,
const std::vector<TypeAndOptionalLength>& types_and_lengths) {
for (const auto& type_and_length : types_and_lengths) {
os << "(" << spdy::FrameTypeToString(type_and_length.first) << ", "
<< (type_and_length.second ? absl::StrCat(type_and_length.second.value())
: "<unspecified>")
<< ") ";
}
return os;
}
std::string FrameTypeToString(uint8_t frame_type) {
if (spdy::IsDefinedFrameType(frame_type)) {
return spdy::FrameTypeToString(spdy::ParseFrameType(frame_type));
} else {
return absl::StrFormat("0x%x", static_cast<int>(frame_type));
}
}
// Custom gMock matcher, used to implement EqualsFrames().
class SpdyControlFrameMatcher
: public testing::MatcherInterface<absl::string_view> {
public:
explicit SpdyControlFrameMatcher(
std::vector<TypeAndOptionalLength> types_and_lengths)
: expected_types_and_lengths_(std::move(types_and_lengths)) {}
bool MatchAndExplain(absl::string_view s,
testing::MatchResultListener* listener) const override {
spdy::SpdyFrameReader reader(s.data(), s.size());
for (TypeAndOptionalLength expected : expected_types_and_lengths_) {
if (!MatchAndExplainOneFrame(expected.first, expected.second, &reader,
listener)) {
return false;
}
}
if (!reader.IsDoneReading()) {
size_t bytes_remaining = s.size() - reader.GetBytesConsumed();
*listener << "; " << bytes_remaining << " bytes left to read!";
return false;
}
return true;
}
bool MatchAndExplainOneFrame(spdy::SpdyFrameType expected_type,
absl::optional<size_t> expected_length,
spdy::SpdyFrameReader* reader,
testing::MatchResultListener* listener) const {
uint32_t payload_length;
if (!reader->ReadUInt24(&payload_length)) {
*listener << "; unable to read length field for expected_type "
<< FrameTypeToString(expected_type) << ". data too short!";
return false;
}
if (expected_length && payload_length != expected_length.value()) {
*listener << "; actual length: " << payload_length
<< " but expected length: " << expected_length.value();
return false;
}
uint8_t raw_type;
if (!reader->ReadUInt8(&raw_type)) {
*listener << "; unable to read type field for expected_type "
<< FrameTypeToString(expected_type) << ". data too short!";
return false;
}
if (raw_type != static_cast<uint8_t>(expected_type)) {
*listener << "; actual type: " << FrameTypeToString(raw_type)
<< " but expected type: " << FrameTypeToString(expected_type);
return false;
}
// Seek past flags (1B), stream ID (4B), and payload. Reach the next frame.
reader->Seek(5 + payload_length);
return true;
}
void DescribeTo(std::ostream* os) const override {
*os << "Data contains frames of types in sequence "
<< expected_types_and_lengths_;
}
void DescribeNegationTo(std::ostream* os) const override {
*os << "Data does not contain frames of types in sequence "
<< expected_types_and_lengths_;
}
private:
const std::vector<TypeAndOptionalLength> expected_types_and_lengths_;
};
} // namespace
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<std::pair<spdy::SpdyFrameType, absl::optional<size_t>>>
types_and_lengths) {
return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths)));
}
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<spdy::SpdyFrameType> types) {
std::vector<std::pair<spdy::SpdyFrameType, absl::optional<size_t>>>
types_and_lengths;
types_and_lengths.reserve(types.size());
for (spdy::SpdyFrameType type : types) {
types_and_lengths.push_back({type, absl::nullopt});
}
return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths)));
}
} // namespace test
} // namespace adapter
} // namespace http2
| 34.779817
| 80
| 0.667106
|
kvmb
|
80e2abd0223a3786643b9a2322a3e8e55291ed23
| 9,383
|
cpp
|
C++
|
drv/sd/sd_spi.cpp
|
yhsb2k/omef
|
7425b62dd4b5d0af4e320816293f69d16d39f57a
|
[
"MIT"
] | null | null | null |
drv/sd/sd_spi.cpp
|
yhsb2k/omef
|
7425b62dd4b5d0af4e320816293f69d16d39f57a
|
[
"MIT"
] | null | null | null |
drv/sd/sd_spi.cpp
|
yhsb2k/omef
|
7425b62dd4b5d0af4e320816293f69d16d39f57a
|
[
"MIT"
] | null | null | null |
#include <stddef.h>
#include <cstring>
#include <assert.h>
#include "sd_spi.hpp"
#include "FreeRTOS.h"
#include "task.h"
using namespace drv;
using namespace hal;
#define WAIT_RESPONSE_CNT 10
#define TRANSMITTER_BIT 6
#define END_BIT 0
#define DATA_TOKEN_CMD17_18_24 0xFE
#define DATA_TOKEN_CMD25 0xFC
#define STOP_TOKEN_CMD25 0xFD
#define ERR_TOKEN_MASK 0x1F /* 7, 6, 5 bits are not used */
#define ERR_TOKEN_ERR (1 << 0)
#define ERR_TOKEN_CC_ERR (1 << 1)
#define ERR_TOKEN_ECC_FAIL (1 << 2)
#define ERR_TOKEN_OUT_OF_RANGE_ERR (1 << 3)
#define ERR_TOKEN_CARD_LOCKED (1 << 4)
#define DATA_RESP_MASK 0x1F /* 7, 6, 5 bits are not used */
#define DATA_RESP_START_BIT (1 << 0) /* Should be 1 */
#define DATA_RESP_END_BIT (1 << 4) /* Should be 0 */
#define DATA_RESP_ACCEPTED 0x05 /* Data accepted */
#define DATA_RESP_CRC_ERR 0x0B /* Data rejected due to a CRC erro */
#define DATA_RESP_WRITE_ERR 0x0D /* Data rejected due to a write error */
#define R1_START_BIT 0x80
#define CRC7_CID_CSD_MASK 0xFE
/* crc7 table (crc8 table shifted left by 1 bit ) */
static const uint8_t crc7_table[256] =
{
0x00, 0x12, 0x24, 0x36, 0x48, 0x5A, 0x6C, 0x7E,
0x90, 0x82, 0xB4, 0xA6, 0xD8, 0xCA, 0xFC, 0xEE,
0x32, 0x20, 0x16, 0x04, 0x7A, 0x68, 0x5E, 0x4C,
0xA2, 0xB0, 0x86, 0x94, 0xEA, 0xF8, 0xCE, 0xDC,
0x64, 0x76, 0x40, 0x52, 0x2C, 0x3E, 0x08, 0x1A,
0xF4, 0xE6, 0xD0, 0xC2, 0xBC, 0xAE, 0x98, 0x8A,
0x56, 0x44, 0x72, 0x60, 0x1E, 0x0C, 0x3A, 0x28,
0xC6, 0xD4, 0xE2, 0xF0, 0x8E, 0x9C, 0xAA, 0xB8,
0xC8, 0xDA, 0xEC, 0xFE, 0x80, 0x92, 0xA4, 0xB6,
0x58, 0x4A, 0x7C, 0x6E, 0x10, 0x02, 0x34, 0x26,
0xFA, 0xE8, 0xDE, 0xCC, 0xB2, 0xA0, 0x96, 0x84,
0x6A, 0x78, 0x4E, 0x58, 0x22, 0x30, 0x06, 0x14,
0xAC, 0xBE, 0x88, 0x9A, 0xE4, 0xF6, 0xC0, 0xD2,
0x3C, 0x2E, 0x18, 0x0A, 0x74, 0x66, 0x50, 0x42,
0x9E, 0x8C, 0xBA, 0xA8, 0xD6, 0xC4, 0xF2, 0xE0,
0x0E, 0x1C, 0x2A, 0x38, 0x46, 0x54, 0x62, 0x70,
0x82, 0x90, 0xA6, 0xB4, 0xCA, 0xD8, 0xEE, 0xFC,
0x12, 0x00, 0x36, 0x24, 0x5A, 0x48, 0x7E, 0x6C,
0xB0, 0xA2, 0x94, 0x86, 0xF8, 0xEA, 0xDC, 0xCE,
0x20, 0x32, 0x04, 0x16, 0x68, 0x7A, 0x4C, 0x5E,
0xE6, 0xF4, 0xC2, 0xD0, 0xAE, 0xBC, 0x8A, 0x98,
0x76, 0x64, 0x52, 0x40, 0x3E, 0x2C, 0x1A, 0x08,
0xD4, 0xC6, 0xF0, 0xE2, 0x9C, 0x8E, 0xB8, 0xAA,
0x44, 0x56, 0x60, 0x72, 0x0C, 0x1E, 0x28, 0x3A,
0x4A, 0x58, 0x6E, 0x7C, 0x02, 0x10, 0x26, 0x34,
0xDA, 0xC8, 0xFE, 0xEC, 0x92, 0x80, 0xB6, 0xA4,
0x78, 0x6A, 0x5C, 0x4E, 0x30, 0x22, 0x14, 0x06,
0xE8, 0xFA, 0xCC, 0xDE, 0xA0, 0xB2, 0x84, 0x96,
0x2E, 0x3C, 0x0A, 0x18, 0x66, 0x74, 0x42, 0x50,
0xBE, 0xAC, 0x9A, 0x88, 0xF6, 0xE4, 0xD2, 0xC0,
0x1C, 0x0E, 0x38, 0x2A, 0x54, 0x46, 0x70, 0x62,
0x8C, 0x9C, 0xA8, 0xBA, 0xC4, 0xD6, 0xE0, 0xF2
};
static const uint16_t crc16_ccitt_table[256] =
{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};
static uint8_t calc_crc7(uint8_t *buff, uint8_t size);
static uint16_t calc_crc16(uint8_t *buff, uint16_t size);
sd_spi::sd_spi(hal::spi &spi, hal::gpio &cs, hal::gpio *cd):
sd(cd),
_spi(spi),
_cs(cs)
{
assert(_spi.cpol() == spi::CPOL_0);
assert(_spi.cpha() == spi::CPHA_0);
assert(_spi.bit_order() == spi::BIT_ORDER_MSB);
assert(_cs.mode() == gpio::mode::DO && cs.get());
}
sd_spi::~sd_spi()
{
}
void sd_spi::select(bool is_selected)
{
_cs.set(is_selected ? 0 : 1);
}
int8_t sd_spi::init_sd()
{
/* Send 80 pulses without cs */
uint8_t init_buff[8];
memset(init_buff, 0xFF, sizeof(init_buff));
if(_spi.write(init_buff, sizeof(init_buff)))
return RES_SPI_ERR;
return RES_OK;
}
void sd_spi::set_speed(uint32_t speed)
{
_spi.baud(speed);
}
int8_t sd_spi::send_cmd(cmd_t cmd, uint32_t arg, resp_t resp_type, uint8_t *resp)
{
int8_t res;
if(cmd != CMD12_STOP_TRANSMISSION)
{
res = wait_ready();
if(res)
return res;
}
uint8_t cmd_buff[6];
cmd_buff[0] = (cmd | (1 << TRANSMITTER_BIT)) & ~R1_START_BIT;
cmd_buff[1] = arg >> 24;
cmd_buff[2] = arg >> 16;
cmd_buff[3] = arg >> 8;
cmd_buff[4] = arg;
cmd_buff[5] = calc_crc7(cmd_buff, sizeof(cmd_buff) - 1);
if(_spi.write(cmd_buff, sizeof(cmd_buff)))
return RES_SPI_ERR;
uint8_t retry_cnt = WAIT_RESPONSE_CNT;
while(retry_cnt--)
{
resp[0] = 0xFF;
if(_spi.read(resp, 1))
return RES_SPI_ERR;
if(!(resp[0] & R1_START_BIT))
break;
}
if(!retry_cnt)
return RES_NO_RESPONSE;
switch(resp_type)
{
case R1:
break;
case R2:
res = read_data(&resp[1], 16);
if(res)
return res;
// Check the CSD or CID CRC7 (last byte):
// Raw CID CRC7 always has LSB set to 1,
//so fix it with CRC7_CID_CSD_MASK
if(calc_crc7(&resp[1], 15) != (resp[16] & CRC7_CID_CSD_MASK))
return RES_CRC_ERR;
break;
case R3:
case R6:
case R7:
memset(&resp[1], 0xFF, 4);
if(_spi.read(&resp[1], 4))
return RES_SPI_ERR;
}
return RES_OK;
}
int8_t sd_spi::read_data(void *data, uint16_t size)
{
uint8_t data_token;
uint8_t wait_cnt = 10;
while(wait_cnt--)
{
data_token = 0xFF;
if(_spi.read(&data_token, 1))
return RES_SPI_ERR;
if(data_token == DATA_TOKEN_CMD17_18_24)
break;
/* Check for error token */
if(!(data_token & ~ERR_TOKEN_MASK))
{
if(data_token & ERR_TOKEN_CARD_LOCKED)
return RES_LOCKED;
else if(data_token & ERR_TOKEN_OUT_OF_RANGE_ERR)
return RES_PARAM_ERR;
else if(data_token & ERR_TOKEN_ECC_FAIL)
return RES_READ_ERR;
else if(data_token & ERR_TOKEN_CC_ERR)
return RES_READ_ERR;
else if(data_token & ERR_TOKEN_ERR)
return RES_READ_ERR;
else
return RES_READ_ERR;
}
vTaskDelay(1);
}
if(!wait_cnt)
return RES_NO_RESPONSE;
memset(data, 0xFF, size);
if(_spi.read(data, size))
return RES_SPI_ERR;
uint8_t crc16[2] = {0xFF, 0xFF};
if(_spi.read(crc16, sizeof(crc16)))
return RES_SPI_ERR;
if(calc_crc16((uint8_t *)data, size) != ((crc16[0] << 8) | crc16[1]))
return RES_CRC_ERR;
return RES_OK;
}
int8_t sd_spi::write_data(void *data, uint16_t size)
{
if(_spi.write(DATA_TOKEN_CMD17_18_24))
return RES_SPI_ERR;
if(_spi.write(data, size))
return RES_SPI_ERR;
uint16_t crc16_tmp = calc_crc16((uint8_t *)data, size);
uint8_t crc16[2] = {(uint8_t)crc16_tmp, (uint8_t)(crc16_tmp << 8)};
if(_spi.write(crc16, sizeof(crc16)))
return RES_SPI_ERR;
/* Check data response */
uint8_t data_resp;
data_resp = 0xFF;
if(_spi.read(&data_resp, sizeof(data_resp)))
return RES_SPI_ERR;
if(!(data_resp & DATA_RESP_START_BIT) || (data_resp & DATA_RESP_END_BIT))
{
/* Data response is not valid */
return RES_WRITE_ERR;
}
switch(data_resp & DATA_RESP_MASK)
{
case DATA_RESP_ACCEPTED: break;
case DATA_RESP_CRC_ERR: return RES_CRC_ERR;
case DATA_RESP_WRITE_ERR:
default: return RES_WRITE_ERR;
}
return wait_ready();
}
int8_t sd_spi::wait_ready()
{
uint8_t busy_flag = 0;
uint16_t wait_cnt = 500;
while(wait_cnt--)
{
busy_flag = 0xFF;
if(_spi.read(&busy_flag, 1))
return RES_SPI_ERR;
if(busy_flag == 0xFF)
break;
vTaskDelay(1);
};
return wait_cnt ? RES_OK : RES_NO_RESPONSE;
}
static uint8_t calc_crc7(uint8_t *buff, uint8_t size)
{
uint8_t crc = 0;
while(size--)
crc = crc7_table[crc ^ *buff++];
return crc;
}
static uint16_t calc_crc16(uint8_t *buff, uint16_t size)
{
uint16_t crc = 0;
while(size--)
crc = (crc << 8) ^ crc16_ccitt_table[(crc >> 8) ^ *buff++];
return crc;
}
| 27.925595
| 81
| 0.685175
|
yhsb2k
|
80e393e0915fb4f27ac5d70395ba2130857a7d8e
| 261
|
cpp
|
C++
|
c++/factorial.cpp
|
ujwal475/Data-Structures-And-Algorithms
|
eab5d4b4011effac409cccde486280d8f8cebd32
|
[
"MIT"
] | 26
|
2021-05-26T04:20:09.000Z
|
2022-03-06T15:26:56.000Z
|
c++/factorial.cpp
|
ujwal475/Data-Structures-And-Algorithms
|
eab5d4b4011effac409cccde486280d8f8cebd32
|
[
"MIT"
] | 47
|
2021-10-06T07:22:48.000Z
|
2021-10-21T10:57:15.000Z
|
c++/factorial.cpp
|
ujwal475/Data-Structures-And-Algorithms
|
eab5d4b4011effac409cccde486280d8f8cebd32
|
[
"MIT"
] | 61
|
2021-10-06T07:33:59.000Z
|
2021-11-27T15:54:25.000Z
|
#include <iostream>
using namespace std;
int fact(int n){
int i=n;
while(n>1){
i = i*(n-1);
--n;
}
return i;
}
int main(){
int n;
cout << "Please enter a number:";
cin >> n;
cout << fact(n) << endl;
return 0;
}
| 13.05
| 37
| 0.475096
|
ujwal475
|
80e3ea2d47c9b4227e4937d7cdcf9a6c8886b16c
| 9,278
|
cxx
|
C++
|
panda/src/putil/typedWritable_ext.cxx
|
kestred/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | 3
|
2018-03-09T12:07:29.000Z
|
2021-02-25T06:50:25.000Z
|
panda/src/putil/typedWritable_ext.cxx
|
Sinkay/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | null | null | null |
panda/src/putil/typedWritable_ext.cxx
|
Sinkay/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | null | null | null |
// Filename: typedWritable_ext.cxx
// Created by: rdb (10Dec13)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "typedWritable_ext.h"
#ifdef HAVE_PYTHON
#ifndef CPPPARSER
extern Dtool_PyTypedObject Dtool_BamWriter;
#endif // CPPPARSER
////////////////////////////////////////////////////////////////////
// Function: TypedWritable::__reduce__
// Access: Published
// Description: This special Python method is implement to provide
// support for the pickle module.
//
// This hooks into the native pickle and cPickle
// modules, but it cannot properly handle
// self-referential BAM objects.
////////////////////////////////////////////////////////////////////
PyObject *Extension<TypedWritable>::
__reduce__(PyObject *self) const {
return __reduce_persist__(self, NULL);
}
////////////////////////////////////////////////////////////////////
// Function: TypedWritable::__reduce_persist__
// Access: Published
// Description: This special Python method is implement to provide
// support for the pickle module.
//
// This is similar to __reduce__, but it provides
// additional support for the missing persistent-state
// object needed to properly support self-referential
// BAM objects written to the pickle stream. This hooks
// into the pickle and cPickle modules implemented in
// direct/src/stdpy.
////////////////////////////////////////////////////////////////////
PyObject *Extension<TypedWritable>::
__reduce_persist__(PyObject *self, PyObject *pickler) const {
// We should return at least a 2-tuple, (Class, (args)): the
// necessary class object whose constructor we should call
// (e.g. this), and the arguments necessary to reconstruct this
// object.
// Check that we have a decode_from_bam_stream python method. If not,
// we can't use this interface.
PyObject *method = PyObject_GetAttrString(self, "decode_from_bam_stream");
if (method == NULL) {
ostringstream stream;
stream << "Cannot pickle objects of type " << _this->get_type() << "\n";
string message = stream.str();
PyErr_SetString(PyExc_TypeError, message.c_str());
return NULL;
}
Py_DECREF(method);
BamWriter *writer = NULL;
if (pickler != NULL) {
PyObject *py_writer = PyObject_GetAttrString(pickler, "bamWriter");
if (py_writer == NULL) {
// It's OK if there's no bamWriter.
PyErr_Clear();
} else {
DTOOL_Call_ExtractThisPointerForType(py_writer, &Dtool_BamWriter, (void **)&writer);
Py_DECREF(py_writer);
}
}
// First, streamify the object, if possible.
string bam_stream;
if (!_this->encode_to_bam_stream(bam_stream, writer)) {
ostringstream stream;
stream << "Could not bamify object of type " << _this->get_type() << "\n";
string message = stream.str();
PyErr_SetString(PyExc_TypeError, message.c_str());
return NULL;
}
// Start by getting this class object.
PyObject *this_class = PyObject_Type(self);
if (this_class == NULL) {
return NULL;
}
PyObject *func;
if (writer != NULL) {
// The modified pickle support: call the "persistent" version of
// this function, which receives the unpickler itself as an
// additional parameter.
func = find_global_decode(this_class, "py_decode_TypedWritable_from_bam_stream_persist");
if (func == NULL) {
PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_TypedWritable_from_bam_stream_persist()");
Py_DECREF(this_class);
return NULL;
}
} else {
// The traditional pickle support: call the non-persistent version
// of this function.
func = find_global_decode(this_class, "py_decode_TypedWritable_from_bam_stream");
if (func == NULL) {
PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_TypedWritable_from_bam_stream()");
Py_DECREF(this_class);
return NULL;
}
}
PyObject *result = Py_BuildValue("(O(Os#))", func, this_class, bam_stream.data(), (Py_ssize_t) bam_stream.size());
Py_DECREF(func);
Py_DECREF(this_class);
return result;
}
////////////////////////////////////////////////////////////////////
// Function: TypedWritable::find_global_decode
// Access: Public, Static
// Description: This is a support function for __reduce__(). It
// searches for the global function
// py_decode_TypedWritable_from_bam_stream() in this
// class's module, or in the module for any base class.
// (It's really looking for the libpanda module, but we
// can't be sure what name that module was loaded under,
// so we search upwards this way.)
//
// Returns: new reference on success, or NULL on failure.
////////////////////////////////////////////////////////////////////
PyObject *Extension<TypedWritable>::
find_global_decode(PyObject *this_class, const char *func_name) {
PyObject *module_name = PyObject_GetAttrString(this_class, "__module__");
if (module_name != NULL) {
// borrowed reference
PyObject *sys_modules = PyImport_GetModuleDict();
if (sys_modules != NULL) {
// borrowed reference
PyObject *module = PyDict_GetItem(sys_modules, module_name);
if (module != NULL) {
PyObject *func = PyObject_GetAttrString(module, (char *)func_name);
if (func != NULL) {
Py_DECREF(module_name);
return func;
}
}
}
}
Py_DECREF(module_name);
PyObject *bases = PyObject_GetAttrString(this_class, "__bases__");
if (bases != NULL) {
if (PySequence_Check(bases)) {
Py_ssize_t size = PySequence_Size(bases);
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject *base = PySequence_GetItem(bases, i);
if (base != NULL) {
PyObject *func = find_global_decode(base, func_name);
Py_DECREF(base);
if (func != NULL) {
Py_DECREF(bases);
return func;
}
}
}
}
Py_DECREF(bases);
}
return NULL;
}
////////////////////////////////////////////////////////////////////
// Function: py_decode_TypedWritable_from_bam_stream
// Access: Published
// Description: This wrapper is defined as a global function to suit
// pickle's needs.
//
// This hooks into the native pickle and cPickle
// modules, but it cannot properly handle
// self-referential BAM objects.
////////////////////////////////////////////////////////////////////
PyObject *
py_decode_TypedWritable_from_bam_stream(PyObject *this_class, const string &data) {
return py_decode_TypedWritable_from_bam_stream_persist(NULL, this_class, data);
}
////////////////////////////////////////////////////////////////////
// Function: py_decode_TypedWritable_from_bam_stream_persist
// Access: Published
// Description: This wrapper is defined as a global function to suit
// pickle's needs.
//
// This is similar to
// py_decode_TypedWritable_from_bam_stream, but it
// provides additional support for the missing
// persistent-state object needed to properly support
// self-referential BAM objects written to the pickle
// stream. This hooks into the pickle and cPickle
// modules implemented in direct/src/stdpy.
////////////////////////////////////////////////////////////////////
PyObject *
py_decode_TypedWritable_from_bam_stream_persist(PyObject *pickler, PyObject *this_class, const string &data) {
PyObject *py_reader = NULL;
if (pickler != NULL) {
py_reader = PyObject_GetAttrString(pickler, "bamReader");
if (py_reader == NULL) {
// It's OK if there's no bamReader.
PyErr_Clear();
}
}
// We need the function PandaNode::decode_from_bam_stream or
// TypedWritableReferenceCount::decode_from_bam_stream, which
// invokes the BamReader to reconstruct this object. Since we use
// the specific object's class as the pointer, we get the particular
// instance of decode_from_bam_stream appropriate to this class.
PyObject *func = PyObject_GetAttrString(this_class, "decode_from_bam_stream");
if (func == NULL) {
return NULL;
}
PyObject *result;
if (py_reader != NULL){
result = PyObject_CallFunction(func, (char *)"(s#O)", data.data(), (Py_ssize_t) data.size(), py_reader);
Py_DECREF(py_reader);
} else {
result = PyObject_CallFunction(func, (char *)"(s#)", data.data(), (Py_ssize_t) data.size());
}
if (result == NULL) {
return NULL;
}
if (result == Py_None) {
Py_DECREF(result);
PyErr_SetString(PyExc_ValueError, "Could not unpack bam stream");
return NULL;
}
return result;
}
#endif
| 36.101167
| 116
| 0.604656
|
kestred
|
80e4db6830eb49c5da5e145f6b0ede663193c0df
| 1,688
|
cpp
|
C++
|
tests/graph/traversal/discovered_flag.cpp
|
AlCash07/ACTL
|
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
|
[
"BSL-1.0"
] | 17
|
2018-08-22T06:48:20.000Z
|
2022-02-22T21:20:09.000Z
|
tests/graph/traversal/discovered_flag.cpp
|
AlCash07/ACTL
|
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
|
[
"BSL-1.0"
] | null | null | null |
tests/graph/traversal/discovered_flag.cpp
|
AlCash07/ACTL
|
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
|
[
"BSL-1.0"
] | null | null | null |
// Copyright 2018 Oleksandr Bacherikov.
//
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include <actl/graph/default_map.hpp>
#include <actl/graph/traversal/breadth_first_search.hpp>
#include <actl/graph/traversal/depth_first_search.hpp>
#include <actl/graph/traversal/discovered_flag.hpp>
#include "graph/sample_graphs.hpp"
#include "map/logging_map.hpp"
#include "test.hpp"
using Log = std::vector<std::pair<int, bool>>;
TEST_CASE("discovered_flag bfs")
{
auto graph = sample_undirected_graph();
Log log;
auto map = logging_map{
make_default_vertex_map<bool>(graph), std::back_inserter(log)};
breadth_first_search{discovered_flag{map}}(graph, 0);
CHECK(
Log{
{0, false},
{1, false},
{2, false},
{3, false},
{4, false},
{5, false},
{0, true},
{1, true},
{3, true},
{2, true},
{4, true},
{5, true},
} == log);
}
TEST_CASE("discovered_flag dfs")
{
auto graph = sample_undirected_graph();
Log log;
auto map = logging_map{
make_default_vertex_map<bool>(graph), std::back_inserter(log)};
depth_first_search{discovered_flag{map}}(graph, 0);
CHECK(
Log{
{0, false},
{1, false},
{2, false},
{3, false},
{4, false},
{5, false},
{0, true},
{1, true},
{2, true},
{3, true},
{4, true},
{5, true},
} == log);
}
| 26.375
| 71
| 0.543839
|
AlCash07
|
80e670f7c00b65cb090fa7cd8b7eb8eed5df787c
| 33,813
|
cpp
|
C++
|
indires_macro_actions/src/Indires_macro_actions.cpp
|
Tutorgaming/indires_navigation
|
830097ac0a3e3a64da9026518419939b509bbe71
|
[
"BSD-3-Clause"
] | 90
|
2019-07-19T13:44:35.000Z
|
2022-02-17T21:39:15.000Z
|
indires_macro_actions/src/Indires_macro_actions.cpp
|
Tutorgaming/indires_navigation
|
830097ac0a3e3a64da9026518419939b509bbe71
|
[
"BSD-3-Clause"
] | 13
|
2019-12-02T07:32:18.000Z
|
2021-08-10T09:38:44.000Z
|
indires_macro_actions/src/Indires_macro_actions.cpp
|
Tutorgaming/indires_navigation
|
830097ac0a3e3a64da9026518419939b509bbe71
|
[
"BSD-3-Clause"
] | 26
|
2019-05-27T14:43:43.000Z
|
2022-02-17T21:39:19.000Z
|
#include <indires_macro_actions/Indires_macro_actions.h>
/*
Status can take this values:
uint8 PENDING = 0 # The goal has yet to be processed by the action server
uint8 ACTIVE = 1 # The goal is currently being processed by the action server
uint8 PREEMPTED = 2 # The goal received a cancel request after it started
executing
# and has since completed its execution (Terminal State)
uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server
(Terminal State)
uint8 ABORTED = 4 # The goal was aborted during execution by the action server
due
# to some failure (Terminal State)
uint8 REJECTED = 5 # The goal was rejected by the action server without being
processed,
# because the goal was unattainable or invalid (Terminal
State)
uint8 PREEMPTING = 6 # The goal received a cancel request after it started
executing
# and has not yet completed execution
uint8 RECALLING = 7 # The goal received a cancel request before it started
executing,
# but the action server has not yet confirmed that the goal
is canceled
uint8 RECALLED = 8 # The goal received a cancel request before it started
executing
# and was successfully cancelled (Terminal State)
uint8 LOST = 9 # An action client can determine that a goal is LOST. This
should not be
# sent over the wire by an action server
*/
// namespace macroactions {
Indires_macro_actions::Indires_macro_actions(tf2_ros::Buffer* tf)
{
tf_ = tf;
// UpoNav_ = nav;
ros::NodeHandle n("~");
// Dynamic reconfigure
// dsrv_ = new
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>(n);
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>::CallbackType
// cb = boost::bind(&Upo_navigation_macro_actions::reconfigureCB, this, _1, _2);
// dsrv_->setCallback(cb);
n.param<double>("secs_to_check_block", secs_to_check_block_, 5.0); // seconds
n.param<double>("block_dist", block_dist_, 0.4); // meters
// n.param<double>("secs_to_wait", secs_to_wait_, 8.0); //seconds
n.param<double>("control_frequency", control_frequency_, 15.0);
std::string odom_topic = "";
n.param<std::string>("odom_topic", odom_topic, "odom");
manual_control_ = false;
// Dynamic reconfigure
// dsrv_ = new
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>(n);
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>::CallbackType
// cb = boost::bind(&Upo_navigation_macro_actions::reconfigureCB, this, _1, _2);
// dsrv_->setCallback(cb);
ros::NodeHandle nh;
rrtgoal_sub_ = nh.subscribe<geometry_msgs::PoseStamped>(
"/rrt_goal", 1, &Indires_macro_actions::rrtGoalCallback, this);
pose_sub_ = nh.subscribe<nav_msgs::Odometry>(
odom_topic.c_str(), 1, &Indires_macro_actions::robotPoseCallback, this);
// Services for walking side by side
// start_client_ = nh.serviceClient<teresa_wsbs::start>("/wsbs/start");
// stop_client_ = nh.serviceClient<teresa_wsbs::stop>("/wsbs/stop");
// wsbs_status_sub_ = nh.subscribe<std_msgs::UInt8>("/wsbs/status", 1,
// &Upo_navigation_macro_actions::wsbsCallback, this);
moveBaseClient_ =
new moveBaseClient("move_base", true); // true-> do not need ros::spin()
ROS_INFO("Waiting for action server to start...");
moveBaseClient_->waitForServer();
ROS_INFO("Action server connected!");
// Initialize action servers
NWActionServer_ = new NWActionServer(
nh1_, "NavigateWaypoint",
boost::bind(&Indires_macro_actions::navigateWaypointCB, this, _1), false);
NHActionServer_ = new NHActionServer(
nh2_, "NavigateHome", boost::bind(&Indires_macro_actions::navigateHomeCB, this, _1), false);
ExActionServer_ = new ExActionServer(
nh3_, "Exploration", boost::bind(&Indires_macro_actions::explorationCB, this, _1), false);
TOActionServer_ =
new TOActionServer(nh4_, "Teleoperation",
boost::bind(&Indires_macro_actions::teleoperationCB, this, _1), false);
NWActionServer_->start();
NHActionServer_->start();
ExActionServer_->start();
TOActionServer_->start();
// ros::NodeHandle nodeh("~/RRT_ros_wrapper");
// nodeh.getParam("full_path_stddev", initial_stddev_);
}
Indires_macro_actions::~Indires_macro_actions()
{
if (NWActionServer_)
delete NWActionServer_;
if (NHActionServer_)
delete NHActionServer_;
if (ExActionServer_)
delete ExActionServer_;
if (TOActionServer_)
delete TOActionServer_;
// if(UpoNav_)
// delete UpoNav_;
// if(dsrv_)
// delete dsrv_;
}
/*
void
Upo_navigation_macro_actions::reconfigureCB(upo_navigation_macro_actions::NavigationMacroActionsConfig
&config, uint32_t level){
boost::recursive_mutex::scoped_lock l(configuration_mutex_);
control_frequency_ = config.control_frequency;
secs_to_check_block_ = config.secs_to_check_block;
block_dist_ = config.block_dist;
secs_to_wait_ = config.secs_to_wait;
social_approaching_type_ = config.social_approaching_type;
secs_to_yield_ = config.secs_to_yield;
//use_leds_ = config.use_leds;
//leds_number_ = config.leds_number;
}*/
/*
//Receive feedback messages from upo_navigation
void Upo_navigation_macro_actions::feedbackReceived(const
move_base_msgs::MoveBaseActionFeedback::ConstPtr& msg) {
pose_mutex_.lock();
robot_pose_ = msg->feedback.base_position;
pose_mutex_.unlock();
if((unsigned int)(std::string(robot_pose_.header.frame_id).size()) < 3)
robot_pose_.header.frame_id = "map";
}
//Receive status messages from upo_navigation
void Upo_navigation_macro_actions::statusReceived(const
actionlib_msgs::GoalStatusArray::ConstPtr& msg)
{
unsigned int actions = msg->status_list.size();
if(actions != 0)
{
status_mutex_.lock();
nav_status_ = msg->status_list.at(0).status;
nav_text_ = msg->status_list.at(0).text;
goal_id_ = msg->status_list.at(0).goal_id.id;
status_mutex_.unlock();
} else {
status_mutex_.lock();
nav_status_ = -1;
nav_text_ = " ";
goal_id_ = " ";
status_mutex_.unlock();
}
}
//This topic publishes only when the action finishes (because of reaching the goal or
cancelation)
void Upo_navigation_macro_actions::resultReceived(const
move_base_msgs::MoveBaseActionResult::ConstPtr& msg)
{
action_end_ = true;
}*/
/*
MoveBase server:
-----------------
Action Subscribed topics:
move_base/goal [move_base_msgs::MoveBaseActionGoal]
move_base/cancel [actionlib_msgs::GoalID]
Action Published topcis:
move_base/feedback [move_base_msgs::MoveBaseActionFeedback]
move_base/status [actionlib_msgs::GoalStatusArray]
move_base/result [move_base_msgs::MoveBaseAcionResult]
*/
void Indires_macro_actions::navigateWaypointCB(
const indires_macro_actions::NavigateWaypointGoal::ConstPtr& goal)
{
printf("¡¡¡¡¡¡¡MacroAction navigatetoWaypoint --> started!!!!!!\n");
// printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->target_pose.pose.position.x,
// goal->target_pose.pose.position.y, goal->target_pose.header.frame_id.c_str());
// UpoNav_->stopRRTPlanning();
move_base_msgs::MoveBaseGoal g;
g.target_pose = goal->target_pose;
moveBaseClient_->sendGoal(g);
// moveBaseClient_->waitForResult();
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
// moveBaseClient_->cancelAllGoals()
// moveBaseClient_->cancelGoal()
// moveBaseClient_->getResult()
if (moveBaseClient_->getState() == actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_INFO("Success!!!");
} /*else {
ROS_INFO("Failed!");
}*/
/*bool ok = UpoNav_->executeNavigation(goal->target_pose);
if(!ok)
{
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
//UpoNav_->stopRRTPlanning();
return;
}*/
ros::Rate r(control_frequency_);
// int pursue_status = 0;
bool exit = false;
ros::Time time_init = ros::Time::now();
bool first = true;
nav_msgs::Odometry pose_init;
// ros::WallTime startt;
while (nh1_.ok())
{
// startt = ros::WallTime::now();
if (NWActionServer_->isPreemptRequested())
{
if (NWActionServer_->isNewGoalAvailable())
{
indires_macro_actions::NavigateWaypointGoal new_goal =
*NWActionServer_->acceptNewGoal();
g.target_pose = new_goal.target_pose;
moveBaseClient_->sendGoal(g);
/*bool ok = UpoNav_->executeNavigation(new_goal.target_pose);
if(!ok) {
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
UpoNav_->stopRRTPlanning();
if(use_leds_)
setLedColor(WHITE);
return;
}*/
first = true;
}
else
{
// if we've been preempted explicitly we need to shut things down
// UpoNav_->resetState();
// Cancel?????
// notify the ActionServer that we've successfully preempted
nwresult_.result = "Preempted";
nwresult_.value = 1;
ROS_DEBUG_NAMED("indires_macro_actions", "indires_navigation preempting the current goal");
NWActionServer_->setPreempted(nwresult_, "Navigation preempted");
// we'll actually return from execute after preempting
return;
}
}
pose_mutex_.lock();
nav_msgs::Odometry new_pose = odom_pose_;
pose_mutex_.unlock();
// pursue_status = UpoNav_->pathFollow(new_pose);
// Posible states:
// PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
if (first)
{
pose_init = new_pose;
time_init = ros::Time::now();
first = false;
}
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
// Goal reached
ROS_INFO("Setting SUCCEEDED state");
nwresult_.result = "Navigation succeeded";
nwresult_.value = 0;
NWActionServer_->setSucceeded(nwresult_, "Goal Reached");
nwfeedback_.text = "Succeeded";
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::ACTIVE)
{
// Goal not reached, continue navigating
nwfeedback_.text = "Navigating";
}
else if (state == actionlib::SimpleClientGoalState::ABORTED)
{
// Aborted
nwfeedback_.text = "Aborted";
ROS_INFO("Setting ABORTED state");
nwresult_.result = "Aborted";
nwresult_.value = 3;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PENDING)
{
nwfeedback_.text = "Pending";
// ROS_INFO("Setting ABORTED state");
// nwresult_.result = "";
// nwresult_.value = 3;
// NWActionServer_->setAborted(nwresult_, "Navigation aborted");
// exit = true;
}
else if (state == actionlib::SimpleClientGoalState::RECALLED)
{
nwfeedback_.text = "Recalled";
}
else if (state == actionlib::SimpleClientGoalState::REJECTED)
{
// Rejected
nwfeedback_.text = "Rejected";
ROS_INFO("Setting ABORTED (rejected) state");
nwresult_.result = "Rejected";
nwresult_.value = 3;
NWActionServer_->setAborted(nwresult_, "Navigation aborted(rejected)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::LOST)
{
// Rejected
nwfeedback_.text = "Lost";
ROS_INFO("Setting ABORTED (lost) state");
nwresult_.result = "Lost";
nwresult_.value = 3;
NWActionServer_->setAborted(nwresult_, "Navigation aborted(lost)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PREEMPTED)
{
nwfeedback_.text = "Preempted";
}
// push the feedback out
geometry_msgs::PoseStamped aux;
aux.header = new_pose.header;
aux.pose.position = new_pose.pose.pose.position;
aux.pose.orientation = new_pose.pose.pose.orientation;
nwfeedback_.base_position = aux;
NWActionServer_->publishFeedback(nwfeedback_);
if (exit)
{
// UpoNav_->stopRRTPlanning();
return;
}
// check the blocked situation.
double time = (ros::Time::now() - time_init).toSec();
// printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(),
// time_init.toSec(), time);
if (time > secs_to_check_block_)
{
double xinit = pose_init.pose.pose.position.x;
double yinit = pose_init.pose.pose.position.y;
double hinit = tf::getYaw(pose_init.pose.pose.orientation);
double xnow = new_pose.pose.pose.position.x;
double ynow = new_pose.pose.pose.position.y;
double hnow = tf::getYaw(new_pose.pose.pose.orientation);
double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2));
double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit));
// printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff);
if (dist <= block_dist_ && yaw_diff < 0.79)
{ // 0.79 = 45º
ROS_INFO("Setting ABORTED state because of blocked situation");
nwresult_.result = "Aborted. Blocked situation";
nwresult_.value = 5;
NWActionServer_->setAborted(nwresult_, "Navigation aborted. blocked");
nwfeedback_.text = "Blocked";
NWActionServer_->publishFeedback(nwfeedback_);
// UpoNav_->stopRRTPlanning();
return;
}
else
{
pose_init = new_pose;
time_init = ros::Time::now();
}
}
// ros::WallDuration dur = ros::WallTime::now() - startt;
// printf("Loop time: %.4f secs\n", dur.toSec());
r.sleep();
}
ROS_INFO("Setting ABORTED state");
nwresult_.result = "Aborted. System is shuting down";
nwresult_.value = 6;
NWActionServer_->setAborted(nwresult_, "Navigation aborted because the node has been killed");
}
void Indires_macro_actions::navigateHomeCB(const indires_macro_actions::NavigateHomeGoal::ConstPtr& goal)
{
printf("¡¡¡¡¡¡¡MacroAction NavigateHome --> started!!!!!!\n");
// printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->home_pose.pose.position.x,
// goal->home_pose.pose.position.y, goal->home_pose.header.frame_id.c_str());
// UpoNav_->stopRRTPlanning();
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
// Put the goal to map origin???
move_base_msgs::MoveBaseGoal g;
g.target_pose = goal->home_pose;
moveBaseClient_->sendGoal(g);
ros::Rate r(control_frequency_);
// int pursue_status = 0;
bool exit = false;
ros::Time time_init = ros::Time::now();
bool first = true;
nav_msgs::Odometry pose_init;
while (nh2_.ok())
{
// startt = ros::WallTime::now();
if (NHActionServer_->isPreemptRequested())
{
if (NHActionServer_->isNewGoalAvailable())
{
indires_macro_actions::NavigateHomeGoal new_goal = *NHActionServer_->acceptNewGoal();
g.target_pose = new_goal.home_pose;
moveBaseClient_->sendGoal(g);
first = true;
}
else
{
// if we've been preempted explicitly we need to shut things down
// UpoNav_->resetState();
// notify the ActionServer that we've successfully preempted
ROS_DEBUG_NAMED("indires_macro_actions", "indires_navigation preempting the current goal");
nhresult_.result = "Preempted";
nhresult_.value = 1;
NHActionServer_->setPreempted(nhresult_, "Navigation preempted");
// we'll actually return from execute after preempting
return;
}
}
pose_mutex_.lock();
nav_msgs::Odometry new_pose = odom_pose_;
pose_mutex_.unlock();
// pursue_status = UpoNav_->pathFollow(new_pose);
// Posible states:
// PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
if (first)
{
pose_init = new_pose;
time_init = ros::Time::now();
first = false;
}
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
// Goal reached
ROS_INFO("Setting SUCCEEDED state");
nhresult_.result = "Navigation succeeded";
nhresult_.value = 0;
NHActionServer_->setSucceeded(nhresult_, "Goal Reached");
nhfeedback_.text = "Succeeded";
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::ACTIVE)
{
// Goal not reached, continue navigating
nhfeedback_.text = "Navigating";
}
else if (state == actionlib::SimpleClientGoalState::ABORTED)
{
// Aborted
nhfeedback_.text = "Aborted";
ROS_INFO("Setting ABORTED state");
nhresult_.result = "Aborted";
nhresult_.value = 3;
NHActionServer_->setAborted(nhresult_, "Navigation aborted");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PENDING)
{
nhfeedback_.text = "Pending";
// ROS_INFO("Setting ABORTED state");
// nwresult_.result = "";
// nwresult_.value = 3;
// NWActionServer_->setAborted(nwresult_, "Navigation aborted");
// exit = true;
}
else if (state == actionlib::SimpleClientGoalState::RECALLED)
{
nhfeedback_.text = "Recalled";
}
else if (state == actionlib::SimpleClientGoalState::REJECTED)
{
// Rejected
nhfeedback_.text = "Rejected";
ROS_INFO("Setting ABORTED (rejected) state");
nhresult_.result = "Rejected";
nhresult_.value = 3;
NHActionServer_->setAborted(nhresult_, "Navigation aborted(rejected)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::LOST)
{
// Rejected
nhfeedback_.text = "Lost";
ROS_INFO("Setting ABORTED (lost) state");
nhresult_.result = "Lost";
nhresult_.value = 3;
NHActionServer_->setAborted(nhresult_, "Navigation aborted(lost)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PREEMPTED)
{
nhfeedback_.text = "Preempted";
}
// push the feedback out
geometry_msgs::PoseStamped aux;
aux.header = new_pose.header;
aux.pose.position = new_pose.pose.pose.position;
aux.pose.orientation = new_pose.pose.pose.orientation;
nhfeedback_.base_position = aux;
NHActionServer_->publishFeedback(nhfeedback_);
if (exit)
{
// UpoNav_->stopRRTPlanning();
return;
}
// check the blocked situation.
double time = (ros::Time::now() - time_init).toSec();
// printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(),
// time_init.toSec(), time);
if (time > secs_to_check_block_)
{
double xinit = pose_init.pose.pose.position.x;
double yinit = pose_init.pose.pose.position.y;
double hinit = tf::getYaw(pose_init.pose.pose.orientation);
double xnow = new_pose.pose.pose.position.x;
double ynow = new_pose.pose.pose.position.y;
double hnow = tf::getYaw(new_pose.pose.pose.orientation);
double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2));
double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit));
// printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff);
if (dist <= block_dist_ && yaw_diff < 0.79)
{ // 0.79 = 45º
ROS_INFO("Setting ABORTED state because of blocked situation");
nhresult_.result = "Aborted. Blocked situation";
nhresult_.value = 5;
NHActionServer_->setAborted(nhresult_, "Navigation aborted. blocked");
nhfeedback_.text = "Blocked";
NHActionServer_->publishFeedback(nhfeedback_);
// UpoNav_->stopRRTPlanning();
return;
}
else
{
pose_init = new_pose;
time_init = ros::Time::now();
}
}
// ros::WallDuration dur = ros::WallTime::now() - startt;
// printf("Loop time: %.4f secs\n", dur.toSec());
r.sleep();
}
ROS_INFO("Setting ABORTED state");
nhresult_.result = "Aborted. system is shuting down";
nhresult_.value = 6;
NHActionServer_->setAborted(nhresult_, "Navigation aborted because the node has been killed");
}
void Indires_macro_actions::explorationCB(const indires_macro_actions::ExplorationGoal::ConstPtr& goal)
{
printf("¡¡¡¡¡¡¡MacroAction Exploration --> started!!!!!!\n");
// printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->target_pose.pose.position.x,
// goal->target_pose.pose.position.y, goal->target_pose.header.frame_id.c_str());
// UpoNav_->stopRRTPlanning();
move_base_msgs::MoveBaseGoal g;
g.target_pose = goal->empty;
g.target_pose.header.frame_id = "";
g.target_pose.pose.orientation.x = 0.0;
g.target_pose.pose.orientation.y = 0.0;
g.target_pose.pose.orientation.z = 0.0;
g.target_pose.pose.orientation.w = 1.0;
moveBaseClient_->sendGoal(g);
// moveBaseClient_->waitForResult();
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
// moveBaseClient_->cancelAllGoals()
// moveBaseClient_->cancelGoal()
// moveBaseClient_->getResult()
if (moveBaseClient_->getState() == actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_INFO("Success!!!");
} /*else {
ROS_INFO("Failed!");
}*/
/*bool ok = UpoNav_->executeNavigation(goal->target_pose);
if(!ok)
{
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
//UpoNav_->stopRRTPlanning();
return;
}*/
ros::Rate r(control_frequency_);
// int pursue_status = 0;
bool exit = false;
ros::Time time_init = ros::Time::now();
bool first = true;
nav_msgs::Odometry pose_init;
// ros::WallTime startt;
while (nh3_.ok())
{
// startt = ros::WallTime::now();
if (ExActionServer_->isPreemptRequested())
{
if (ExActionServer_->isNewGoalAvailable())
{
indires_macro_actions::ExplorationGoal new_goal = *ExActionServer_->acceptNewGoal();
g.target_pose = new_goal.empty;
moveBaseClient_->sendGoal(g);
/*bool ok = UpoNav_->executeNavigation(new_goal.target_pose);
if(!ok) {
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
UpoNav_->stopRRTPlanning();
if(use_leds_)
setLedColor(WHITE);
return;
}*/
first = true;
}
else
{
// if we've been preempted explicitly we need to shut things down
// UpoNav_->resetState();
// Cancel?????
// notify the ActionServer that we've successfully preempted
exresult_.result = "Preempted";
exresult_.value = 1;
ROS_DEBUG_NAMED("indires_macro_actions", "indires_exploration preempting the current goal");
ExActionServer_->setPreempted(exresult_, "Exploration preempted");
// we'll actually return from execute after preempting
return;
}
}
pose_mutex_.lock();
nav_msgs::Odometry new_pose = odom_pose_;
pose_mutex_.unlock();
// pursue_status = UpoNav_->pathFollow(new_pose);
// Posible states:
// PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST
state = moveBaseClient_->getState();
if (first)
{
pose_init = new_pose;
time_init = ros::Time::now();
first = false;
}
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
// Goal reached
// WE MUST TO CONTINUE THE EXPLORATION
ROS_INFO("Goal reached. Exploration continues...");
// exresult_.result = "Exploration succeeded";
// exresult_.value = 0;
// ExActionServer_->setSucceeded(exresult_, "Goal Reached");
// exfeedback_.text = "Succeeded";
// exit = true;
exfeedback_.text = "goal reached. Exploration continues";
moveBaseClient_->sendGoal(g);
}
else if (state == actionlib::SimpleClientGoalState::ACTIVE)
{
// Goal not reached, continue navigating
exfeedback_.text = "Navigating";
}
else if (state == actionlib::SimpleClientGoalState::ABORTED)
{
// Aborted
exfeedback_.text = "Aborted";
ROS_INFO("Setting ABORTED state");
exresult_.result = "Aborted";
exresult_.value = 3;
ExActionServer_->setAborted(exresult_, "Exploration aborted");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PENDING)
{
exfeedback_.text = "Pending";
// ROS_INFO("Setting ABORTED state");
// nwresult_.result = "";
// nwresult_.value = 3;
// NWActionServer_->setAborted(nwresult_, "Navigation aborted");
// exit = true;
}
else if (state == actionlib::SimpleClientGoalState::RECALLED)
{
exfeedback_.text = "Recalled";
}
else if (state == actionlib::SimpleClientGoalState::REJECTED)
{
// Rejected
exfeedback_.text = "Rejected";
ROS_INFO("Setting ABORTED (rejected) state");
exresult_.result = "Rejected";
exresult_.value = 3;
ExActionServer_->setAborted(exresult_, "Exploration aborted(rejected)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::LOST)
{
// Rejected
exfeedback_.text = "Lost";
ROS_INFO("Setting ABORTED (lost) state");
exresult_.result = "Lost";
exresult_.value = 3;
ExActionServer_->setAborted(exresult_, "Exploration aborted(lost)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PREEMPTED)
{
nwfeedback_.text = "Preempted";
}
// push the feedback out
geometry_msgs::PoseStamped aux;
aux.header = new_pose.header;
aux.pose.position = new_pose.pose.pose.position;
aux.pose.orientation = new_pose.pose.pose.orientation;
exfeedback_.base_position = aux;
ExActionServer_->publishFeedback(exfeedback_);
if (exit)
{
// UpoNav_->stopRRTPlanning();
return;
}
// check the blocked situation.
double time = (ros::Time::now() - time_init).toSec();
// printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(),
// time_init.toSec(), time);
if (time > secs_to_check_block_)
{
double xinit = pose_init.pose.pose.position.x;
double yinit = pose_init.pose.pose.position.y;
double hinit = tf::getYaw(pose_init.pose.pose.orientation);
double xnow = new_pose.pose.pose.position.x;
double ynow = new_pose.pose.pose.position.y;
double hnow = tf::getYaw(new_pose.pose.pose.orientation);
double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2));
double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit));
// printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff);
if (dist <= block_dist_ && yaw_diff < 0.79)
{ // 0.79 = 45º
ROS_INFO("Setting ABORTED state because of blocked situation");
exresult_.result = "Aborted. Blocked situation";
exresult_.value = 5;
ExActionServer_->setAborted(exresult_, "Exploration aborted. blocked");
exfeedback_.text = "Blocked";
ExActionServer_->publishFeedback(exfeedback_);
// UpoNav_->stopRRTPlanning();
return;
}
else
{
pose_init = new_pose;
time_init = ros::Time::now();
}
}
// ros::WallDuration dur = ros::WallTime::now() - startt;
// printf("Loop time: %.4f secs\n", dur.toSec());
r.sleep();
}
ROS_INFO("Setting ABORTED state");
exresult_.result = "Aborted. System is shuting down";
exresult_.value = 6;
ExActionServer_->setAborted(exresult_, "Exploration aborted because the node has been killed");
}
/*
bool Indires_macro_actions::reconfigureParameters(std::string node, std::string
param_name, std::string value, const datatype type)
{
//printf("RECONFIGURE PARAMETERS METHOD\n");
dynamic_reconfigure::ReconfigureRequest srv_req;
dynamic_reconfigure::ReconfigureResponse srv_resp;
dynamic_reconfigure::IntParameter param1;
dynamic_reconfigure::BoolParameter param2;
dynamic_reconfigure::DoubleParameter param3;
dynamic_reconfigure::StrParameter param4;
dynamic_reconfigure::Config conf;
switch(type)
{
case INT_TYPE:
param1.name = param_name.c_str();
param1.value = stoi(value);
conf.ints.push_back(param1);
break;
case DOUBLE_TYPE:
param3.name = param_name.c_str();
//printf("type double. Value: %s\n", param3.name.c_str());
param3.value = stod(value);
//printf("conversion to double: %.3f\n", param3.value);
conf.doubles.push_back(param3);
break;
case BOOL_TYPE:
param2.name = param_name.c_str();
param2.value = stoi(value);
conf.bools.push_back(param2);
break;
case STRING_TYPE:
param4.name = param_name.c_str();
param4.value = value;
conf.strs.push_back(param4);
break;
default:
ROS_ERROR("indires_macro_actions. ReconfigureParameters. datatype not valid!");
}
srv_req.config = conf;
std::string service = node + "/set_parameters";
if (!ros::service::call(service, srv_req, srv_resp)) {
ROS_ERROR("Could not call the service %s reconfigure the param %s to %s",
service.c_str(), param_name.c_str(), value.c_str());
return false;
}
return true;
}
*/
void Indires_macro_actions::teleoperationCB(const indires_macro_actions::TeleoperationGoal::ConstPtr& goal)
{
if (!manual_control_)
{
printf("¡¡¡¡¡¡¡MacroAction AssistedSteering --> started!!!!!!\n");
manual_control_ = true;
moveBaseClient_->cancelAllGoals();
// UpoNav_->stopRRTPlanning();
// stop the current wsbs if it is running
// teresa_wsbs::stop stop_srv;
// stop_client_.call(stop_srv);
}
ros::Time time_init;
time_init = ros::Time::now();
bool exit = false;
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
ros::Rate r(30.0);
while (nh4_.ok())
{
if (TOActionServer_->isPreemptRequested())
{
if (TOActionServer_->isNewGoalAvailable())
{
// if we're active and a new goal is available, we'll accept it, but we won't shut
// anything down
// ROS_INFO("Accepting new goal");
indires_macro_actions::TeleoperationGoal new_goal = *TOActionServer_->acceptNewGoal();
time_init = ros::Time::now();
}
else
{
TOActionServer_->setPreempted(toresult_, "Teleoperation preempted");
return;
}
}
tofeedback_.text = "Robot manually controlled";
// Check the time without receiving commands from the interface
double time = (ros::Time::now() - time_init).toSec();
if (time > 5.0)
{
tofeedback_.text = "Teleoperation finished";
toresult_.result = "Teleoperation Succeeded";
toresult_.value = 0;
TOActionServer_->setSucceeded(toresult_, "Teleoperation succeeded");
exit = true;
}
TOActionServer_->publishFeedback(tofeedback_);
if (exit)
{
manual_control_ = false;
return;
}
r.sleep();
}
manual_control_ = false;
ROS_INFO("Setting ABORTED state");
TOActionServer_->setAborted(toresult_, "Teleoperation aborted because the node has been killed");
}
// void Upo_navigation_macro_actions::poseCallback(const
// geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg)
void Indires_macro_actions::robotPoseCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
pose_mutex_.lock();
odom_pose_ = *msg;
// robot_global_pose_.y = msg->pose.pose.position.y;
// robot_global_pose_.theta = tf::getYaw(msg->pose.pose.orientation);
pose_mutex_.unlock();
}
void Indires_macro_actions::rrtGoalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
/*geometry_msgs::PoseStamped out;
out = transformPoseTo(*msg, "map");
geometry_msgs::Pose2D p;
p.x = out.pose.position.x;
p.y = out.pose.position.y;
p.theta = 0.0;
*/
goal_mutex_.lock();
rrtgoal_ = *msg;
goal_mutex_.unlock();
}
geometry_msgs::PoseStamped Indires_macro_actions::transformPoseTo(geometry_msgs::PoseStamped pose_in,
std::string frame_out)
{
geometry_msgs::PoseStamped in = pose_in;
in.header.stamp = ros::Time();
geometry_msgs::PoseStamped pose_out;
try
{
pose_out = tf_->transform(in, frame_out.c_str());
}
catch (tf2::TransformException ex)
{
ROS_WARN("Macro-Action class. TransformException in method transformPoseTo: %s", ex.what());
pose_out.header = in.header;
pose_out.header.stamp = ros::Time::now();
pose_out.pose.position.x = 0.0;
pose_out.pose.position.y = 0.0;
pose_out.pose.position.z = 0.0;
pose_out.pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
}
return pose_out;
}
// This method removes the initial slash from the frame names
// in order to compare the string names easily
void Indires_macro_actions::fixFrame(std::string& cad)
{
if (cad[0] == '/')
{
cad.erase(0, 1);
}
}
float Indires_macro_actions::normalizeAngle(float val, float min, float max)
{
float norm = 0.0;
if (val >= min)
norm = min + fmod((val - min), (max - min));
else
norm = max - fmod((min - val), (max - min));
return norm;
}
| 30.683303
| 107
| 0.658001
|
Tutorgaming
|
80e6d38c87acd8605315d45b0d400b2a3bd80526
| 49,223
|
cpp
|
C++
|
agent/agent.cpp
|
MatthewPowley/cppagent
|
fccb7794723ba71025dfd1ea633332422f99a3dd
|
[
"Apache-2.0"
] | null | null | null |
agent/agent.cpp
|
MatthewPowley/cppagent
|
fccb7794723ba71025dfd1ea633332422f99a3dd
|
[
"Apache-2.0"
] | null | null | null |
agent/agent.cpp
|
MatthewPowley/cppagent
|
fccb7794723ba71025dfd1ea633332422f99a3dd
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright Copyright 2012, System Insights, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "agent.hpp"
#include "dlib/logger.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <stdexcept>
#include <dlib/tokenizer.h>
#include <dlib/misc_api.h>
#include <dlib/array.h>
#include <dlib/dir_nav.h>
#include <dlib/config_reader.h>
#include <dlib/queue.h>
#include <functional>
using namespace std;
static const string sUnavailable("UNAVAILABLE");
static const string sConditionUnavailable("UNAVAILABLE|||");
static const string sAvailable("AVAILABLE");
static dlib::logger sLogger("agent");
/* Agent public methods */
Agent::Agent(const string& configXmlPath, int aBufferSize, int aMaxAssets, int aCheckpointFreq)
: mPutEnabled(false), mLogStreamData(false)
{
mMimeTypes["xsl"] = "text/xsl";
mMimeTypes["xml"] = "text/xml";
mMimeTypes["css"] = "text/css";
mMimeTypes["xsd"] = "text/xml";
mMimeTypes["jpg"] = "image/jpeg";
mMimeTypes["jpeg"] = "image/jpeg";
mMimeTypes["png"] = "image/png";
mMimeTypes["ico"] = "image/x-icon";
try
{
// Load the configuration for the Agent
mXmlParser = new XmlParser();
mDevices = mXmlParser->parseFile(configXmlPath);
std::vector<Device *>::iterator device;
std::set<std::string> uuids;
for (device = mDevices.begin(); device != mDevices.end(); ++device)
{
if (uuids.count((*device)->getUuid()) > 0)
throw runtime_error("Duplicate UUID: " + (*device)->getUuid());
uuids.insert((*device)->getUuid());
(*device)->resolveReferences();
}
}
catch (runtime_error & e)
{
sLogger << LFATAL << "Error loading xml configuration: " + configXmlPath;
sLogger << LFATAL << "Error detail: " << e.what();
cerr << e.what() << endl;
throw e;
}
catch (exception &f)
{
sLogger << LFATAL << "Error loading xml configuration: " + configXmlPath;
sLogger << LFATAL << "Error detail: " << f.what();
cerr << f.what() << endl;
throw f;
}
// Grab data from configuration
string time = getCurrentTime(GMT_UV_SEC);
// Unique id number for agent instance
mInstanceId = getCurrentTimeInSec();
// Sequence number and sliding buffer for data
mSequence = 1;
mSlidingBufferSize = 1 << aBufferSize;
mSlidingBuffer = new sliding_buffer_kernel_1<ComponentEventPtr>();
mSlidingBuffer->set_size(aBufferSize);
mCheckpointFreq = aCheckpointFreq;
mCheckpointCount = (mSlidingBufferSize / aCheckpointFreq) + 1;
// Asset sliding buffer
mMaxAssets = aMaxAssets;
// Create the checkpoints at a regular frequency
mCheckpoints = new Checkpoint[mCheckpointCount];
// Mutex used for synchronized access to sliding buffer and sequence number
mSequenceLock = new dlib::mutex;
mAssetLock = new dlib::mutex;
// Add the devices to the device map and create availability and
// asset changed events if they don't exist
std::vector<Device *>::iterator device;
for (device = mDevices.begin(); device != mDevices.end(); ++device)
{
mDeviceMap[(*device)->getName()] = *device;
// Make sure we have two device level data items:
// 1. Availability
// 2. AssetChanged
if ((*device)->getAvailability() == NULL)
{
// Create availability data item and add it to the device.
std::map<string,string> attrs;
attrs["type"] = "AVAILABILITY";
attrs["id"] = (*device)->getId() + "_avail";
attrs["category"] = "EVENT";
DataItem *di = new DataItem(attrs);
di->setComponent(*(*device));
(*device)->addDataItem(*di);
(*device)->addDeviceDataItem(*di);
(*device)->mAvailabilityAdded = true;
}
int major, minor;
char c;
stringstream ss(XmlPrinter::getSchemaVersion());
ss >> major >> c >> minor;
if ((*device)->getAssetChanged() == NULL && (major > 1 || (major == 1 && minor >= 2)))
{
// Create asset change data item and add it to the device.
std::map<string,string> attrs;
attrs["type"] = "ASSET_CHANGED";
attrs["id"] = (*device)->getId() + "_asset_chg";
attrs["category"] = "EVENT";
DataItem *di = new DataItem(attrs);
di->setComponent(*(*device));
(*device)->addDataItem(*di);
(*device)->addDeviceDataItem(*di);
}
if ((*device)->getAssetRemoved() == NULL && (major > 1 || (major == 1 && minor >= 3)))
{
// Create asset removed data item and add it to the device.
std::map<string,string> attrs;
attrs["type"] = "ASSET_REMOVED";
attrs["id"] = (*device)->getId() + "_asset_rem";
attrs["category"] = "EVENT";
DataItem *di = new DataItem(attrs);
di->setComponent(*(*device));
(*device)->addDataItem(*di);
(*device)->addDeviceDataItem(*di);
}
}
// Reload the document for path resolution
mXmlParser->loadDocument(XmlPrinter::printProbe(mInstanceId, mSlidingBufferSize,
mMaxAssets,
mAssets.size(),
mSequence, mDevices));
/* Initialize the id mapping for the devices and set all data items to UNAVAILABLE */
for (device = mDevices.begin(); device != mDevices.end(); ++device)
{
const std::map<string, DataItem*> &items = (*device)->getDeviceDataItems();
std::map<string, DataItem *>::const_iterator item;
for (item = items.begin(); item != items.end(); ++item)
{
// Check for single valued constrained data items.
DataItem *d = item->second;
const string *value = &sUnavailable;
if (d->isCondition()) {
value = &sConditionUnavailable;
} else if (d->hasConstantValue()) {
value = &(d->getConstrainedValues()[0]);
}
addToBuffer(d, *value, time);
if (mDataItemMap.count(d->getId()) == 0)
mDataItemMap[d->getId()] = d;
else {
sLogger << LFATAL << "Duplicate DataItem id " << d->getId() <<
" for device: " << (*device)->getName() << " and data item name: " <<
d->getName();
exit(1);
}
}
}
}
Device *Agent::findDeviceByUUIDorName(const std::string& aId)
{
Device *device = NULL;
std::vector<Device *>::iterator it;
for (it = mDevices.begin(); device == NULL && it != mDevices.end(); it++)
{
if ((*it)->getUuid() == aId || (*it)->getName() == aId)
device = *it;
}
return device;
}
Agent::~Agent()
{
delete mSlidingBuffer;
delete mSequenceLock;
delete mAssetLock;
delete mXmlParser;
delete[] mCheckpoints;
}
void Agent::start()
{
try {
// Start all the adapters
std::vector<Adapter*>::iterator iter;
for (iter = mAdapters.begin(); iter != mAdapters.end(); iter++) {
(*iter)->start();
}
// Start the server. This blocks until the server stops.
server_http::start();
}
catch (dlib::socket_error &e) {
sLogger << LFATAL << "Cannot start server: " << e.what();
exit(1);
}
}
void Agent::clear()
{
// Stop all adapter threads...
std::vector<Adapter *>::iterator iter;
sLogger << LINFO << "Shutting down adapters";
// Deletes adapter and waits for it to exit.
for (iter = mAdapters.begin(); iter != mAdapters.end(); iter++) {
(*iter)->stop();
}
sLogger << LINFO << "Shutting down server";
server::http_1a::clear();
sLogger << LINFO << "Shutting completed";
for (iter = mAdapters.begin(); iter != mAdapters.end(); iter++) {
delete (*iter);
}
mAdapters.clear();
}
// Register a file
void Agent::registerFile(const string &aUri, const string &aPath)
{
try {
directory dir(aPath);
queue<file>::kernel_1a files;
dir.get_files(files);
files.reset();
string baseUri = aUri;
if (*baseUri.rbegin() != '/') baseUri.append(1, '/');
while (files.move_next()) {
file &file = files.element();
string name = file.name();
string uri = baseUri + name;
mFileMap.insert(pair<string,string>(uri, file.full_name()));
// Check if the file name maps to a standard MTConnect schema file.
if (name.find("MTConnect") == 0 && name.substr(name.length() - 4, 4) == ".xsd" &&
XmlPrinter::getSchemaVersion() == name.substr(name.length() - 7, 3)) {
string version = name.substr(name.length() - 7, 3);
if (name.substr(9, 5) == "Error") {
string urn = "urn:mtconnect.org:MTConnectError:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addErrorNamespace(urn, uri, "m");
} else if (name.substr(9, 7) == "Devices") {
string urn = "urn:mtconnect.org:MTConnectDevices:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addDevicesNamespace(urn, uri, "m");
} else if (name.substr(9, 6) == "Assets") {
string urn = "urn:mtconnect.org:MTConnectAssets:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addAssetsNamespace(urn, uri, "m");
} else if (name.substr(9, 7) == "Streams") {
string urn = "urn:mtconnect.org:MTConnectStreams:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addStreamsNamespace(urn, uri, "m");
}
}
}
}
catch (directory::dir_not_found e) {
sLogger << LDEBUG << "registerFile: Path " << aPath << " is not a directory: "
<< e.what() << ", trying as a file";
try {
file file(aPath);
mFileMap.insert(pair<string,string>(aUri, aPath));
} catch (file::file_not_found e) {
sLogger << LERROR << "Cannot register file: " << aPath << ": " << e.what();
}
}
}
// Methods for service
const string Agent::on_request (const incoming_things& incoming,
outgoing_things& outgoing)
{
string result;
outgoing.headers["Content-Type"] = "text/xml";
try
{
sLogger << LDEBUG << "Request: " << incoming.request_type << " " <<
incoming.path << " from " << incoming.foreign_ip << ":" << incoming.foreign_port;
if (mPutEnabled)
{
if ((incoming.request_type == "PUT" || incoming.request_type == "POST") &&
!mPutAllowedHosts.empty() && mPutAllowedHosts.count(incoming.foreign_ip) == 0)
{
return printError("UNSUPPORTED",
"HTTP PUT is not allowed from " + incoming.foreign_ip);
}
if (incoming.request_type != "GET" && incoming.request_type != "PUT" &&
incoming.request_type != "POST") {
return printError("UNSUPPORTED",
"Only the HTTP GET and PUT requests are supported");
}
}
else
{
if (incoming.request_type != "GET") {
return printError("UNSUPPORTED",
"Only the HTTP GET request is supported");
}
}
// Parse the URL path looking for '/'
string path = incoming.path;
size_t qm = path.find_last_of('?');
if (qm != string::npos)
path = path.substr(0, qm);
if (isFile(path)) {
return handleFile(path, outgoing);
}
string::size_type loc1 = path.find("/", 1);
string::size_type end = (path[path.length()-1] == '/') ?
path.length() - 1 : string::npos;
string first = path.substr(1, loc1-1);
string call, device;
if (first == "assets" || first == "asset")
{
string list;
if (loc1 != string::npos)
list = path.substr(loc1 + 1);
if (incoming.request_type == "GET")
result = handleAssets(*outgoing.out, incoming.queries, list);
else
result = storeAsset(*outgoing.out, incoming.queries, list, incoming.body);
}
else
{
// If a '/' was found
if (loc1 < end)
{
// Look for another '/'
string::size_type loc2 = path.find("/", loc1+1);
if (loc2 == end)
{
device = first;
call = path.substr(loc1+1, loc2-loc1-1);
}
else
{
// Path is too long
return printError("UNSUPPORTED", "The following path is invalid: " + path);
}
}
else
{
// Try to handle the call
call = first;
}
if (incoming.request_type == "GET")
result = handleCall(*outgoing.out, path, incoming.queries, call, device);
else
result = handlePut(*outgoing.out, path, incoming.queries, call, device);
}
}
catch (exception & e)
{
printError("SERVER_EXCEPTION",(string) e.what());
}
return result;
}
Adapter * Agent::addAdapter(const string& aDeviceName,
const string& aHost,
const unsigned int aPort,
bool aStart,
int aLegacyTimeout
)
{
Adapter *adapter = new Adapter(aDeviceName, aHost, aPort, aLegacyTimeout);
adapter->setAgent(*this);
mAdapters.push_back(adapter);
Device *dev = mDeviceMap[aDeviceName];
if (dev != NULL && dev->mAvailabilityAdded)
adapter->setAutoAvailable(true);
if (aStart)
adapter->start();
return adapter;
}
unsigned int Agent::addToBuffer(DataItem *dataItem,
const string& value,
string time
)
{
if (dataItem == NULL) return 0;
dlib::auto_mutex lock(*mSequenceLock);
uint64_t seqNum = mSequence++;
ComponentEvent *event = new ComponentEvent(*dataItem, seqNum,
time, value);
(*mSlidingBuffer)[seqNum] = event;
mLatest.addComponentEvent(event);
event->unrefer();
// Special case for the first event in the series to prime the first checkpoint.
if (seqNum == 1) {
mFirst.addComponentEvent(event);
}
// Checkpoint management
int index = mSlidingBuffer->get_element_id(seqNum);
if (mCheckpointCount > 0 && index % mCheckpointFreq == 0) {
// Copy the checkpoint from the current into the slot
mCheckpoints[index / mCheckpointFreq].copy(mLatest);
}
// See if the next sequence has an event. If the event exists it
// should be added to the first checkpoint.
if ((*mSlidingBuffer)[mSequence] != NULL)
{
// Keep the last checkpoint up to date with the last.
mFirst.addComponentEvent((*mSlidingBuffer)[mSequence]);
}
dataItem->signalObservers(seqNum);
return seqNum;
}
bool Agent::addAsset(Device *aDevice, const string &aId, const string &aAsset,
const string &aType, const string &aTime)
{
// Check to make sure the values are present
if (aType.empty() || aAsset.empty() || aId.empty()) {
sLogger << LWARN << "Asset '" << aId << "' missing required type, id, or body. Asset is rejected.";
return false;
}
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
AssetPtr ptr;
// Lock the asset addition to protect from multithreaded collisions. Releaes
// before we add the event so we don't cause a race condition.
{
dlib::auto_mutex lock(*mAssetLock);
try {
ptr = mXmlParser->parseAsset(aId, aType, aAsset);
}
catch (runtime_error &e) {
sLogger << LERROR << "addAsset: Error parsing asset: " << aAsset << "\n" << e.what();
return false;
}
if (ptr.getObject() == NULL)
{
sLogger << LERROR << "addAssete: Error parsing asset";
return false;
}
AssetPtr *old = &mAssetMap[aId];
if (!ptr->isRemoved())
{
if (old->getObject() != NULL)
mAssets.remove(old);
else
mAssetCounts[aType] += 1;
} else if (old->getObject() == NULL) {
sLogger << LWARN << "Cannot remove non-existent asset";
return false;
}
if (ptr.getObject() == NULL) {
sLogger << LWARN << "Asset could not be created";
return false;
} else {
ptr->setAssetId(aId);
ptr->setTimestamp(time);
ptr->setDeviceUuid(aDevice->getUuid());
}
// Check for overflow
if (mAssets.size() >= mMaxAssets)
{
AssetPtr oldref(*mAssets.front());
mAssetCounts[oldref->getType()] -= 1;
mAssets.pop_front();
mAssetMap.erase(oldref->getAssetId());
// Remove secondary keys
AssetKeys &keys = oldref->getKeys();
AssetKeys::iterator iter;
for (iter = keys.begin(); iter != keys.end(); iter++)
{
AssetIndex &index = mAssetIndices[iter->first];
index.erase(iter->second);
}
}
mAssetMap[aId] = ptr;
if (!ptr->isRemoved())
{
AssetPtr &newPtr = mAssetMap[aId];
mAssets.push_back(&newPtr);
}
// Add secondary keys
AssetKeys &keys = ptr->getKeys();
AssetKeys::iterator iter;
for (iter = keys.begin(); iter != keys.end(); iter++)
{
AssetIndex &index = mAssetIndices[iter->first];
index[iter->second] = ptr;
}
}
// Generate an asset chnaged event.
if (ptr->isRemoved())
addToBuffer(aDevice->getAssetRemoved(), aType + "|" + aId, time);
else
addToBuffer(aDevice->getAssetChanged(), aType + "|" + aId, time);
return true;
}
bool Agent::updateAsset(Device *aDevice, const std::string &aId, AssetChangeList &aList,
const string &aTime)
{
AssetPtr asset;
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
{
dlib::auto_mutex lock(*mAssetLock);
asset = mAssetMap[aId];
if (asset.getObject() == NULL)
return false;
if (asset->getType() != "CuttingTool" && asset->getType() != "CuttingToolArchitype")
return false;
CuttingToolPtr tool((CuttingTool*) asset.getObject());
try {
AssetChangeList::iterator iter;
for (iter = aList.begin(); iter != aList.end(); ++iter)
{
if (iter->first == "xml") {
mXmlParser->updateAsset(asset, asset->getType(), iter->second);
} else {
tool->updateValue(iter->first, iter->second);
}
}
}
catch (runtime_error &e) {
sLogger << LERROR << "updateAsset: Error parsing asset: " << asset << "\n" << e.what();
return false;
}
// Move it to the front of the queue
mAssets.remove(&asset);
mAssets.push_back(&asset);
tool->setTimestamp(time);
tool->setDeviceUuid(aDevice->getUuid());
tool->changed();
}
addToBuffer(aDevice->getAssetChanged(), asset->getType() + "|" + aId, time);
return true;
}
bool Agent::removeAsset(Device *aDevice, const std::string &aId, const string &aTime)
{
AssetPtr asset;
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
{
dlib::auto_mutex lock(*mAssetLock);
asset = mAssetMap[aId];
if (asset.getObject() == NULL)
return false;
asset->setRemoved(true);
asset->setTimestamp(time);
// Check if the asset changed id is the same as this asset.
ComponentEventPtr *ptr = mLatest.getEventPtr(aDevice->getAssetChanged()->getId());
if (ptr != NULL && (*ptr)->getValue() == aId)
{
addToBuffer(aDevice->getAssetChanged(), asset->getType() + "|UNAVAILABLE", time);
}
}
addToBuffer(aDevice->getAssetRemoved(), asset->getType() + "|" + aId, time);
return true;
}
bool Agent::removeAllAssets(Device *aDevice, const std::string &aType, const std::string &aTime)
{
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
{
dlib::auto_mutex lock(*mAssetLock);
ComponentEventPtr *ptr = mLatest.getEventPtr(aDevice->getAssetChanged()->getId());
string changedId;
if (ptr != NULL)
changedId = (*ptr)->getValue();
list<AssetPtr*>::reverse_iterator iter;
for (iter = mAssets.rbegin(); iter != mAssets.rend(); ++iter)
{
AssetPtr asset = (**iter);
if (aType == asset->getType() && !asset->isRemoved()) {
asset->setRemoved(true);
asset->setTimestamp(time);
addToBuffer(aDevice->getAssetRemoved(), asset->getType() + "|" + asset->getAssetId(), time);
if (changedId == asset->getAssetId())
addToBuffer(aDevice->getAssetChanged(), asset->getType() + "|UNAVAILABLE", time);
}
}
}
return true;
}
/* Add values for related data items UNAVAILABLE */
void Agent::disconnected(Adapter *anAdapter, std::vector<Device*> aDevices)
{
string time = getCurrentTime(GMT_UV_SEC);
sLogger << LDEBUG << "Disconnected from adapter, setting all values to UNAVAILABLE";
std::vector<Device*>::iterator iter;
for (iter = aDevices.begin(); iter != aDevices.end(); ++iter) {
const std::map<std::string, DataItem *> &dataItems = (*iter)->getDeviceDataItems();
std::map<std::string, DataItem*>::const_iterator dataItemAssoc;
for (dataItemAssoc = dataItems.begin(); dataItemAssoc != dataItems.end(); ++dataItemAssoc)
{
DataItem *dataItem = (*dataItemAssoc).second;
if (dataItem != NULL && (dataItem->getDataSource() == anAdapter ||
(anAdapter->isAutoAvailable() &&
dataItem->getDataSource() == NULL &&
dataItem->getType() == "AVAILABILITY")))
{
ComponentEventPtr *ptr = mLatest.getEventPtr(dataItem->getId());
if (ptr != NULL) {
const string *value = NULL;
if (dataItem->isCondition()) {
if ((*ptr)->getLevel() != ComponentEvent::UNAVAILABLE)
value = &sConditionUnavailable;
} else if (dataItem->hasConstraints()) {
std::vector<std::string> &values = dataItem->getConstrainedValues();
if (values.size() > 1 && (*ptr)->getValue() != sUnavailable)
value = &sUnavailable;
} else if ((*ptr)->getValue() != sUnavailable) {
value = &sUnavailable;
}
if (value != NULL && !anAdapter->isDuplicate(dataItem, *value, NAN))
addToBuffer(dataItem, *value, time);
}
} else if (dataItem == NULL) {
sLogger << LWARN << "No data Item for " << (*dataItemAssoc).first;
}
}
}
}
void Agent::connected(Adapter *anAdapter, std::vector<Device*> aDevices)
{
if (anAdapter->isAutoAvailable()) {
string time = getCurrentTime(GMT_UV_SEC);
std::vector<Device*>::iterator iter;
for (iter = aDevices.begin(); iter != aDevices.end(); ++iter) {
sLogger << LDEBUG << "Connected to adapter, setting all Availability data items to AVAILABLE";
if ((*iter)->getAvailability() != NULL)
{
sLogger << LDEBUG << "Adding availabilty event for " << (*iter)->getAvailability()->getId();
addToBuffer((*iter)->getAvailability(), sAvailable, time);
}
else
{
sLogger << LDEBUG << "Cannot find availability for " << (*iter)->getName();
}
}
}
}
/* Agent protected methods */
string Agent::handleCall(ostream& out,
const string& path,
const key_value_map& queries,
const string& call,
const string& device)
{
try {
string deviceName;
if (!device.empty())
{
deviceName = device;
}
if (call == "current")
{
const string path = queries[(string) "path"];
string result;
int freq = checkAndGetParam(queries, "frequency", NO_FREQ,
FASTEST_FREQ, false,SLOWEST_FREQ);
// Check for 1.2 conversion to interval
if (freq == NO_FREQ)
freq = checkAndGetParam(queries, "interval", NO_FREQ,
FASTEST_FREQ, false, SLOWEST_FREQ);
uint64_t at = checkAndGetParam64(queries, "at", NO_START, getFirstSequence(), true,
mSequence - 1);
int heartbeat = checkAndGetParam(queries, "heartbeat", 10000, 10, true, 600000);
if (freq != NO_FREQ && at != NO_START) {
return printError("INVALID_REQUEST", "You cannot specify both the at and frequency arguments to a current request");
}
return handleStream(out, devicesAndPath(path, deviceName), true,
freq, at, 0, heartbeat);
}
else if (call == "probe" || call.empty())
{
return handleProbe(deviceName);
}
else if (call == "sample")
{
string path = queries[(string) "path"];
string result;
int count = checkAndGetParam(queries, "count", DEFAULT_COUNT,
1, true, mSlidingBufferSize);
int freq = checkAndGetParam(queries, "frequency", NO_FREQ,
FASTEST_FREQ, false, SLOWEST_FREQ);
// Check for 1.2 conversion to interval
if (freq == NO_FREQ)
freq = checkAndGetParam(queries, "interval", NO_FREQ,
FASTEST_FREQ, false, SLOWEST_FREQ);
uint64 start = checkAndGetParam64(queries, "start", NO_START, getFirstSequence(),
true, mSequence);
if (start == NO_START) // If there was no data in queries
{
start = checkAndGetParam64(queries, "from", 1,
getFirstSequence(), true, mSequence);
}
int heartbeat = checkAndGetParam(queries, "heartbeat", 10000, 10, true, 600000);
return handleStream(out, devicesAndPath(path, deviceName), false,
freq, start, count, heartbeat);
}
else if ((mDeviceMap[call] != NULL) && device.empty())
{
return handleProbe(call);
}
else
{
return printError("UNSUPPORTED",
"The following path is invalid: " + path);
}
}
catch (ParameterError &aError)
{
return printError(aError.mCode, aError.mMessage);
}
}
/* Agent protected methods */
string Agent::handlePut(
ostream& out,
const string& path,
const key_value_map& queries,
const string& adapter,
const string& deviceName
)
{
string device = deviceName;
if (device.empty() && adapter.empty())
{
return printError("UNSUPPORTED",
"Device must be specified for PUT");
} else if (device.empty()) {
device = adapter;
}
Device *dev = mDeviceMap[device];
if (dev == NULL) {
string message = ((string) "Cannot find device: ") + device;
return printError("UNSUPPORTED", message);
}
// First check if this is an adapter put or a data put...
if (queries["_type"] == "command")
{
std::vector<Adapter*>::iterator adpt;
for (adpt = dev->mAdapters.begin(); adpt != dev->mAdapters.end(); adpt++) {
key_value_map::const_iterator kv;
for (kv = queries.begin(); kv != queries.end(); kv++) {
string command = kv->first + "=" + kv->second;
sLogger << LDEBUG << "Sending command '" << command << "' to " << device;
(*adpt)->sendCommand(command);
}
}
}
else
{
string time = queries["time"];
if (time.empty())
time = getCurrentTime(GMT_UV_SEC);
key_value_map::const_iterator kv;
for (kv = queries.begin(); kv != queries.end(); kv++) {
if (kv->first != "time")
{
DataItem *di = dev->getDeviceDataItem(kv->first);
if (di != NULL)
addToBuffer(di, kv->second, time);
else
sLogger << LWARN << "(" << device << ") Could not find data item: " << kv->first;
}
}
}
return "<success/>";
}
string Agent::handleProbe(const string& name)
{
std::vector<Device *> mDeviceList;
if (!name.empty())
{
Device * device = getDeviceByName(name);
if (device == NULL)
{
return printError("NO_DEVICE",
"Could not find the device '" + name + "'");
}
else
{
mDeviceList.push_back(device);
}
}
else
{
mDeviceList = mDevices;
}
return XmlPrinter::printProbe(mInstanceId, mSlidingBufferSize, mSequence,
mMaxAssets, mAssets.size(),
mDeviceList, &mAssetCounts);
}
string Agent::handleStream(
ostream& out,
const string& path,
bool current,
unsigned int frequency,
uint64_t start,
unsigned int count,
unsigned int aHb
)
{
std::set<string> filter;
try
{
mXmlParser->getDataItems(filter, path);
}
catch (exception& e)
{
return printError("INVALID_XPATH", e.what());
}
if (filter.empty())
{
return printError("INVALID_XPATH",
"The path could not be parsed. Invalid syntax: " + path);
}
// Check if there is a frequency to stream data or not
if (frequency != (unsigned) NO_FREQ)
{
streamData(out, filter, current, frequency, start, count, aHb);
return "";
}
else
{
uint64_t end;
bool endOfBuffer;
if (current)
return fetchCurrentData(filter, start);
else
return fetchSampleData(filter, start, count, end, endOfBuffer);
}
}
std::string Agent::handleAssets(std::ostream& aOut,
const key_value_map& aQueries,
const std::string& aList)
{
using namespace dlib;
std::vector<AssetPtr> assets;
if (!aList.empty())
{
auto_mutex lock(*mAssetLock);
istringstream str(aList);
tokenizer_kernel_1 tok;
tok.set_stream(str);
tok.set_identifier_token(tok.lowercase_letters() + tok.uppercase_letters() +
tok.numbers() + "_.@$%&^:+-_=",
tok.lowercase_letters() + tok.uppercase_letters() +
tok.numbers() + "_.@$%&^:+-_=");
int type;
string token;
for (tok.get_token(type, token); type != tok.END_OF_FILE; tok.get_token(type, token))
{
if (type == tok.IDENTIFIER)
{
AssetPtr ptr = mAssetMap[token];
if (ptr.getObject() == NULL)
return XmlPrinter::printError(mInstanceId, 0, 0, "ASSET_NOT_FOUND",
(string) "Could not find asset: " + token);
assets.push_back(ptr);
}
}
}
else
{
auto_mutex lock(*mAssetLock);
// Return all asssets, first check if there is a type attribute
string type = aQueries["type"];
bool removed = (aQueries.count("removed") > 0 && aQueries["removed"] == "true");
int count = checkAndGetParam(aQueries, "count", mAssets.size(),
1, false, NO_VALUE32);
list<AssetPtr*>::reverse_iterator iter;
for (iter = mAssets.rbegin(); iter != mAssets.rend() && count > 0; ++iter, --count)
{
if ((type.empty() || type == (**iter)->getType()) && (removed || !(**iter)->isRemoved())) {
assets.push_back(**iter);
}
}
}
return XmlPrinter::printAssets(mInstanceId, mMaxAssets, mAssets.size(), assets);
}
// Store an asset in the map by asset # and use the circular buffer as
// an LRU. Check if we're removing an existing asset and clean up the
// map, and then store this asset.
std::string Agent::storeAsset(std::ostream& aOut,
const key_value_map& aQueries,
const std::string& aId,
const std::string& aBody)
{
string name = aQueries["device"];
string type = aQueries["type"];
Device *device = NULL;
if (!name.empty()) device = mDeviceMap[name];
// If the device was not found or was not provided, use the default device.
if (device == NULL) device = mDevices[0];
if (addAsset(device, aId, aBody, type))
return "<success/>";
else
return "<failure/>";
}
string Agent::handleFile(const string &aUri, outgoing_things& aOutgoing)
{
// Get the mime type for the file.
bool unknown = true;
size_t last = aUri.find_last_of("./");
string contentType;
if (last != string::npos && aUri[last] == '.')
{
string ext = aUri.substr(last + 1);
if (mMimeTypes.count(ext) > 0)
{
contentType = mMimeTypes[ext];
unknown = false;
}
}
if (unknown)
contentType = "application/octet-stream";
// Check if the file is cached
RefCountedPtr<CachedFile> cachedFile;
std::map<string, RefCountedPtr<CachedFile> >::iterator cached = mFileCache.find(aUri);
if (cached != mFileCache.end())
cachedFile = cached->second;
else
{
std::map<string,string>::iterator file = mFileMap.find(aUri);
// Should never happen
if (file == mFileMap.end()) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
const char *path = file->second.c_str();
struct stat fs;
int res = stat(path, &fs);
if (res != 0) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
int fd = open(path, O_RDONLY | O_BINARY);
if (res < 0) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
cachedFile.setObject(new CachedFile(fs.st_size), true);
int bytes = read(fd, cachedFile->mBuffer, fs.st_size);
close(fd);
if (bytes < fs.st_size) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
// If this is a small file, cache it.
if (bytes <= SMALL_FILE) {
mFileCache.insert(pair<string, RefCountedPtr<CachedFile> >(aUri, cachedFile));
}
}
(*aOutgoing.out) << "HTTP/1.1 200 OK\r\n"
"Date: " << getCurrentTime(HUM_READ) << "\r\n"
"Server: MTConnectAgent\r\n"
"Connection: close\r\n"
"Content-Length: " << cachedFile->mSize << "\r\n"
"Expires: " << getCurrentTime(time(NULL) + 60 * 60 * 24, 0, HUM_READ) << "\r\n"
"Content-Type: " << contentType << "\r\n\r\n";
aOutgoing.out->write(cachedFile->mBuffer, cachedFile->mSize);
aOutgoing.out->setstate(ios::badbit);
return "";
}
void Agent::streamData(ostream& out,
std::set<string> &aFilter,
bool current,
unsigned int aInterval,
uint64_t start,
unsigned int count,
unsigned int aHeartbeat
)
{
// Create header
string boundary = md5(intToString(time(NULL)));
ofstream log;
if (mLogStreamData)
{
string filename = "Stream_" + getCurrentTime(LOCAL) + "_" +
int64ToString((uint64_t) dlib::get_thread_id()) + ".log";
log.open(filename.c_str());
}
out << "HTTP/1.1 200 OK\r\n"
"Date: " << getCurrentTime(HUM_READ) << "\r\n"
"Server: MTConnectAgent\r\n"
"Expires: -1\r\n"
"Connection: close\r\n"
"Cache-Control: private, max-age=0\r\n"
"Content-Type: multipart/x-mixed-replace;boundary=" << boundary << "\r\n"
"Transfer-Encoding: chunked\r\n\r\n";
// This object will automatically clean up all the observer from the
// signalers in an exception proof manor.
ChangeObserver observer;
// Add observers
std::set<string>::iterator iter;
for (iter = aFilter.begin(); iter != aFilter.end(); ++iter)
mDataItemMap[*iter]->addObserver(&observer);
uint64_t interMicros = aInterval * 1000;
uint64_t firstSeq = getFirstSequence();
if (start < firstSeq)
start = firstSeq;
try {
// Loop until the user closes the connection
timestamper ts;
while (out.good())
{
// Remember when we started this grab...
uint64_t last = ts.get_timestamp();
// Fetch sample data now resets the observer while holding the sequence
// mutex to make sure that a new event will be recorded in the observer
// when it returns.
string content;
uint64_t end;
bool endOfBuffer = true;
if (current) {
content = fetchCurrentData(aFilter, NO_START);
} else {
// Check if we're falling too far behind. If we are, generate an
// MTConnectError and return.
if (start < getFirstSequence()) {
sLogger << LWARN << "Client fell too far behind, disconnecting";
throw ParameterError("OUT_OF_RANGE", "Client can't keep up with event stream, disconnecting");
} else {
// end and endOfBuffer are set during the fetch sample data while the
// mutex is held. This removed the race to check if we are at the end of
// the bufffer and setting the next start to the last sequence number
// sent.
content = fetchSampleData(aFilter, start, count, end,
endOfBuffer, &observer);
}
if (mLogStreamData)
log << content << endl;
}
ostringstream str;
// Make sure we're terminated with a <cr><nl>
content.append("\r\n");
out.setf(ios::dec, ios::basefield);
str << "--" << boundary << "\r\n"
"Content-type: text/xml\r\n"
"Content-length: " << content.length() << "\r\n\r\n"
<< content;
string chunk = str.str();
out.setf(ios::hex, ios::basefield);
out << chunk.length() << "\r\n";
out << chunk << "\r\n";
out.flush();
// Wait for up to frequency ms for something to arrive... Don't wait if
// we are not at the end of the buffer. Just put the next set after aInterval
// has elapsed. Check also if in the intervening time between the last fetch
// and now. If so, we just spin through and wait the next interval.
// Even if we are at the end of the buffer, or within range. If we are filtering,
// we will need to make sure we are not spinning when there are no valid events
// to be reported. we will waste cycles spinning on the end of the buffer when
// we should be in a heartbeat wait as well.
if (!endOfBuffer) {
// If we're not at the end of the buffer, move to the end of the previous set and
// begin filtering from where we left off.
start = end;
// For replaying of events, we will stream as fast as we can with a 1ms sleep
// to allow other threads to run.
dlib::sleep(1);
} else {
uint64 delta;
if (!current) {
// Busy wait to make sure the signal was actually signaled. We have observed that
// a signal can occur in rare conditions where there are multiple threads listening
// on separate condition variables and this pops out too soon. This will make sure
// observer was actually signaled and instead of throwing an error will wait again
// for the remaining hartbeat interval.
delta = (ts.get_timestamp() - last) / 1000;
while (delta < aHeartbeat &&
observer.wait(aHeartbeat - delta) &&
!observer.wasSignaled()) {
delta = (ts.get_timestamp() - last) / 1000;
}
{
dlib::auto_mutex lock(*mSequenceLock);
// Make sure the observer was signaled!
if (!observer.wasSignaled()) {
// If nothing came out during the last wait, we may have still have advanced
// the sequence number. We should reset the start to something closer to the
// current sequence. If we lock the sequence lock, we can check if the observer
// was signaled between the time the wait timed out and the mutex was locked.
// Otherwise, nothing has arrived and we set to the next sequence number to
// the next sequence number to be allocated and continue.
start = mSequence;
} else {
// Get the sequence # signaled in the observer when the earliest event arrived.
// This will allow the next set of data to be pulled. Any later events will have
// greater sequence numbers, so this should not cause a problem. Also, signaled
// sequence numbers can only decrease, never increase.
start = observer.getSequence();
}
}
}
// Now wait the remainder if we triggered before the timer was up.
delta = ts.get_timestamp() - last;
if (delta < interMicros) {
// Sleep the remainder
dlib::sleep((interMicros - delta) / 1000);
}
}
}
}
catch (ParameterError &aError)
{
sLogger << LINFO << "Caught a parameter error.";
if (out.good()) {
ostringstream str;
string content = printError(aError.mCode, aError.mMessage);
str << "--" << boundary << "\r\n"
"Content-type: text/xml\r\n"
"Content-length: " << content.length() << "\r\n\r\n"
<< content;
string chunk = str.str();
out.setf(ios::hex, ios::basefield);
out << chunk.length() << "\r\n";
out << chunk << "\r\n";
out.flush();
}
}
catch (...)
{
sLogger << LWARN << "Error occurred during streaming data";
if (out.good()) {
ostringstream str;
string content = printError("INTERNAL_ERROR", "Unknown error occurred during streaming");
str << "--" << boundary << "\r\n"
"Content-type: text/xml\r\n"
"Content-length: " << content.length() << "\r\n\r\n"
<< content;
string chunk = str.str();
out.setf(ios::hex, ios::basefield);
out << chunk.length() << "\r\n";
out << chunk;
out.flush();
}
}
out.setstate(ios::badbit);
// Observer is auto removed from signalers
}
string Agent::fetchCurrentData(std::set<string> &aFilter, uint64_t at)
{
ComponentEventPtrArray events;
uint64_t firstSeq, seq;
{
dlib::auto_mutex lock(*mSequenceLock);
firstSeq = getFirstSequence();
seq = mSequence;
if (at == NO_START)
{
mLatest.getComponentEvents(events, &aFilter);
}
else
{
long pos = (long) mSlidingBuffer->get_element_id(at);
long first = (long) mSlidingBuffer->get_element_id(firstSeq);
long checkIndex = pos / mCheckpointFreq;
long closestCp = checkIndex * mCheckpointFreq;
unsigned long index;
Checkpoint *ref;
// Compute the closest checkpoint. If the checkpoint is after the
// first checkpoint and before the next incremental checkpoint,
// use first.
if (first > closestCp && pos >= first)
{
ref = &mFirst;
// The checkpoint is inclusive of the "first" event. So we add one
// so we don't duplicate effort.
index = first + 1;
}
else
{
index = closestCp + 1;
ref = &mCheckpoints[checkIndex];
}
Checkpoint check(*ref, &aFilter);
// Roll forward from the checkpoint.
for (; index <= (unsigned long) pos; index++) {
check.addComponentEvent(((*mSlidingBuffer)[(unsigned long)index]).getObject());
}
check.getComponentEvents(events);
}
}
string toReturn = XmlPrinter::printSample(mInstanceId, mSlidingBufferSize,
seq, firstSeq, mSequence - 1, events);
return toReturn;
}
string Agent::fetchSampleData(std::set<string> &aFilter,
uint64_t start, unsigned int count, uint64_t &end,
bool &endOfBuffer, ChangeObserver *aObserver)
{
ComponentEventPtrArray results;
uint64_t firstSeq;
{
dlib::auto_mutex lock(*mSequenceLock);
firstSeq = (mSequence > mSlidingBufferSize) ?
mSequence - mSlidingBufferSize : 1;
// START SHOULD BE BETWEEN 0 AND SEQUENCE NUMBER
start = (start <= firstSeq) ? firstSeq : start;
uint64_t i;
for (i = start; results.size() < count && i < mSequence; i++)
{
// Filter out according to if it exists in the list
const string &dataId = (*mSlidingBuffer)[i]->getDataItem()->getId();
if (aFilter.count(dataId) > 0)
{
ComponentEventPtr event = (*mSlidingBuffer)[i];
results.push_back(event);
}
}
end = i;
if (i >= mSequence)
endOfBuffer = true;
else
endOfBuffer = false;
if (aObserver != NULL) aObserver->reset();
}
return XmlPrinter::printSample(mInstanceId, mSlidingBufferSize, end,
firstSeq, mSequence - 1, results);
}
string Agent::printError(const string& errorCode, const string& text)
{
sLogger << LDEBUG << "Returning error " << errorCode << ": " << text;
return XmlPrinter::printError(mInstanceId, mSlidingBufferSize, mSequence,
errorCode, text);
}
string Agent::devicesAndPath(const string& path, const string& device)
{
string dataPath = "";
if (!device.empty())
{
string prefix = "//Devices/Device[@name=\"" + device + "\"]";
if (!path.empty())
{
istringstream toParse(path);
string token;
// Prefix path (i.e. "path1|path2" => "{prefix}path1|{prefix}path2")
while (getline(toParse, token, '|'))
{
dataPath += prefix + token + "|";
}
dataPath.erase(dataPath.length()-1);
}
else
{
dataPath = prefix;
}
}
else
{
dataPath = (!path.empty()) ? path : "//Devices/Device";
}
return dataPath;
}
int Agent::checkAndGetParam(const key_value_map& queries,
const string& param,
const int defaultValue,
const int minValue,
bool minError,
const int maxValue)
{
if (queries.count(param) == 0)
{
return defaultValue;
}
if (queries[param].empty())
{
throw ParameterError("QUERY_ERROR", "'" + param + "' cannot be empty.");
}
if (!isNonNegativeInteger(queries[param]))
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be a positive integer.");
}
long int value = strtol(queries[param].c_str(), NULL, 10);
if (minValue != NO_VALUE32 && value < minValue)
{
if (minError)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be greater than or equal to " + intToString(minValue) + ".");
}
return minValue;
}
if (maxValue != NO_VALUE32 && value > maxValue)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be less than or equal to " + intToString(maxValue) + ".");
}
return value;
}
uint64_t Agent::checkAndGetParam64(const key_value_map& queries,
const string& param,
const uint64_t defaultValue,
const uint64_t minValue,
bool minError,
const uint64_t maxValue)
{
if (queries.count(param) == 0)
{
return defaultValue;
}
if (queries[param].empty())
{
throw ParameterError("QUERY_ERROR", "'" + param + "' cannot be empty.");
}
if (!isNonNegativeInteger(queries[param]))
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be a positive integer.");
}
uint64_t value = strtoull(queries[param].c_str(), NULL, 10);
if (minValue != NO_VALUE64 && value < minValue)
{
if (minError)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be greater than or equal to " + int64ToString(minValue) + ".");
}
return minValue;
}
if (maxValue != NO_VALUE64 && value > maxValue)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be less than or equal to " + int64ToString(maxValue) + ".");
}
return value;
}
DataItem * Agent::getDataItemByName(const string& device, const string& name)
{
Device *dev = mDeviceMap[device];
return (dev) ? dev->getDeviceDataItem(name) : NULL;
}
void Agent::updateDom(Device *aDevice)
{
mXmlParser->updateDevice(aDevice);
}
| 31.232868
| 124
| 0.572639
|
MatthewPowley
|
80eadfcfb890ab9d53fee493019fbde5087937fb
| 14,756
|
cc
|
C++
|
google/cloud/bigtable/internal/logging_instance_admin_client_test.cc
|
utgarda/google-cloud-cpp
|
c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0
|
[
"Apache-2.0"
] | null | null | null |
google/cloud/bigtable/internal/logging_instance_admin_client_test.cc
|
utgarda/google-cloud-cpp
|
c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0
|
[
"Apache-2.0"
] | null | null | null |
google/cloud/bigtable/internal/logging_instance_admin_client_test.cc
|
utgarda/google-cloud-cpp
|
c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/bigtable/internal/logging_instance_admin_client.h"
#include "google/cloud/bigtable/instance_admin_client.h"
#include "google/cloud/bigtable/testing/mock_instance_admin_client.h"
#include "google/cloud/bigtable/testing/mock_response_reader.h"
#include "google/cloud/testing_util/assert_ok.h"
#include "google/cloud/testing_util/scoped_log.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace bigtable {
inline namespace BIGTABLE_CLIENT_NS {
namespace {
using ::testing::Contains;
using ::testing::HasSubstr;
using ::testing::Return;
using MockAsyncLongrunningOpReader =
::google::cloud::bigtable::testing::MockAsyncResponseReader<
google::longrunning::Operation>;
namespace btadmin = google::bigtable::admin::v2;
class LoggingInstanceAdminClientTest : public ::testing::Test {
protected:
static Status TransientError() {
return Status(StatusCode::kUnavailable, "try-again");
}
testing_util::ScopedLog log_;
};
TEST_F(LoggingInstanceAdminClientTest, ListInstances) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, ListInstances).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::ListInstancesRequest request;
btadmin::ListInstancesResponse response;
auto status = stub.ListInstances(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("ListInstances")));
}
TEST_F(LoggingInstanceAdminClientTest, CreateInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, CreateInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateInstanceRequest request;
google::longrunning::Operation response;
auto status = stub.CreateInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("CreateInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, UpdateInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, UpdateInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::PartialUpdateInstanceRequest request;
google::longrunning::Operation response;
auto status = stub.UpdateInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("UpdateInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, GetOperation) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetOperation).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::longrunning::GetOperationRequest request;
google::longrunning::Operation response;
auto status = stub.GetOperation(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetOperation")));
}
TEST_F(LoggingInstanceAdminClientTest, GetInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::GetInstanceRequest request;
btadmin::Instance response;
auto status = stub.GetInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, DeleteInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, DeleteInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::DeleteInstanceRequest request;
google::protobuf::Empty response;
auto status = stub.DeleteInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("DeleteInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, ListClusters) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, ListClusters).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::ListClustersRequest request;
btadmin::ListClustersResponse response;
auto status = stub.ListClusters(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("ListClusters")));
}
TEST_F(LoggingInstanceAdminClientTest, GetCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::GetClusterRequest request;
btadmin::Cluster response;
auto status = stub.GetCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, DeleteCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, DeleteCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::DeleteClusterRequest request;
google::protobuf::Empty response;
auto status = stub.DeleteCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("DeleteCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, CreateCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, CreateCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateClusterRequest request;
google::longrunning::Operation response;
auto status = stub.CreateCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("CreateCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, UpdateCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, UpdateCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::Cluster request;
google::longrunning::Operation response;
auto status = stub.UpdateCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("UpdateCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, CreateAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, CreateAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateAppProfileRequest request;
btadmin::AppProfile response;
auto status = stub.CreateAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("CreateAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, GetAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::GetAppProfileRequest request;
btadmin::AppProfile response;
auto status = stub.GetAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, ListAppProfiles) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, ListAppProfiles).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::ListAppProfilesRequest request;
btadmin::ListAppProfilesResponse response;
auto status = stub.ListAppProfiles(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("ListAppProfiles")));
}
TEST_F(LoggingInstanceAdminClientTest, UpdateAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, UpdateAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::UpdateAppProfileRequest request;
google::longrunning::Operation response;
auto status = stub.UpdateAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("UpdateAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, DeleteAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, DeleteAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::DeleteAppProfileRequest request;
google::protobuf::Empty response;
auto status = stub.DeleteAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("DeleteAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, GetIamPolicy) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetIamPolicy).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::iam::v1::GetIamPolicyRequest request;
google::iam::v1::Policy response;
auto status = stub.GetIamPolicy(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetIamPolicy")));
}
TEST_F(LoggingInstanceAdminClientTest, SetIamPolicy) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, SetIamPolicy).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::iam::v1::SetIamPolicyRequest request;
google::iam::v1::Policy response;
auto status = stub.SetIamPolicy(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("SetIamPolicy")));
}
TEST_F(LoggingInstanceAdminClientTest, TestIamPermissions) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, TestIamPermissions).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::iam::v1::TestIamPermissionsRequest request;
google::iam::v1::TestIamPermissionsResponse response;
auto status = stub.TestIamPermissions(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("TestIamPermissions")));
}
TEST_F(LoggingInstanceAdminClientTest, AsyncCreateInstance) {
auto reader = absl::make_unique<MockAsyncLongrunningOpReader>();
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, AsyncCreateInstance)
.WillOnce([&reader](grpc::ClientContext*,
btadmin::CreateInstanceRequest const&,
grpc::CompletionQueue*) {
return std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<
google::longrunning::Operation>>(reader.get());
});
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateInstanceRequest request;
grpc::CompletionQueue cq;
stub.AsyncCreateInstance(&context, request, &cq);
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("AsyncCreateInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, AsyncUpdateInstance) {
auto reader = absl::make_unique<MockAsyncLongrunningOpReader>();
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, AsyncUpdateInstance)
.WillOnce([&reader](grpc::ClientContext*,
btadmin::PartialUpdateInstanceRequest const&,
grpc::CompletionQueue*) {
return std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<
google::longrunning::Operation>>(reader.get());
});
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::PartialUpdateInstanceRequest request;
grpc::CompletionQueue cq;
stub.AsyncUpdateInstance(&context, request, &cq);
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("AsyncUpdateInstance")));
}
} // namespace
} // namespace BIGTABLE_CLIENT_NS
} // namespace bigtable
} // namespace cloud
} // namespace google
| 33.309255
| 79
| 0.756506
|
utgarda
|
80eb98790843ae825cc31caf05545e7d7fc50507
| 1,382
|
hpp
|
C++
|
src/frontmatter/frontmatter.hpp
|
foo-dogsquared/automate-md
|
c278c7ab93d34da198ce409556a8e2df287f4b17
|
[
"MIT"
] | 4
|
2018-09-29T17:00:16.000Z
|
2022-01-23T14:53:04.000Z
|
src/frontmatter/frontmatter.hpp
|
foo-dogsquared/automate-md
|
c278c7ab93d34da198ce409556a8e2df287f4b17
|
[
"MIT"
] | 5
|
2018-11-06T15:45:17.000Z
|
2018-12-11T13:39:31.000Z
|
src/frontmatter/frontmatter.hpp
|
foo-dogsquared/automate-md
|
c278c7ab93d34da198ce409556a8e2df287f4b17
|
[
"MIT"
] | null | null | null |
#include <map>
#include <regex>
#define MAX_ARR_LENGTH 16
#define MAX_DATE_LENGTH 26
#define MAX_TITLE_LENGTH 64
#define MAX_AUTHOR_LENGTH 32
typedef struct _frontmatter
{
std::map<std::string, std::string> list;
int categories_length;
int tags_length;
std::string type;
std::string __open_divider;
std::string __close_divider;
std::string __tab;
std::string __assigner;
std::string __space;
}
frontmatter;
static void init_fm_format_data(frontmatter &__fm) {
if (__fm.type == "YAML" || __fm.type == "yaml") {
__fm.__open_divider = "---";
__fm.__close_divider = "---";
__fm.__tab = "";
__fm.__assigner = ":";
__fm.__space = "";
}
else if (__fm.type == "TOML" || __fm.type == "toml") {
__fm.__open_divider = "+++";
__fm.__close_divider = "+++";
__fm.__tab = "";
__fm.__assigner = "=";
__fm.__space = " ";
}
else if (__fm.type == "JSON" || __fm.type == "json") {
__fm.__open_divider = "{";
__fm.__close_divider = "}";
__fm.__tab = "\t";
__fm.__assigner = ":";
__fm.__space = "";
}
}
static std::string detect_type(std::string __str) {
std::regex __YAML("---\\s*"), __TOML("\\+\\+\\+\\s*"), __JSON("\\{\\s*|\\}\\s*");
if (std::regex_match(__str, __YAML))
return "YAML";
else if (std::regex_match(__str, __TOML))
return "TOML";
else if (std::regex_match(__str, __JSON))
return "JSON";
else
return nullptr;
}
| 23.827586
| 82
| 0.631693
|
foo-dogsquared
|