hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
443815f88fead02b7458e81e0e3a88f1fbbe35b2 | 1,192 | hpp | C++ | examples/platformer/src/inc/game.hpp | YeyaSwizaw/teabag | 20a44414a6cf628426b17651f59d92c4455f312f | [
"Apache-2.0"
] | null | null | null | examples/platformer/src/inc/game.hpp | YeyaSwizaw/teabag | 20a44414a6cf628426b17651f59d92c4455f312f | [
"Apache-2.0"
] | null | null | null | examples/platformer/src/inc/game.hpp | YeyaSwizaw/teabag | 20a44414a6cf628426b17651f59d92c4455f312f | [
"Apache-2.0"
] | null | null | null | #ifndef PLATFORMER_GAME_HPP
#define PLATFORMER_GAME_HPP
#include "teabag/game.hpp"
#include "teabag/collision.hpp"
#include <string>
#include <functional>
#include <algorithm>
#include <iostream>
#include <unordered_set>
#include <SFML/Window.hpp>
class Game {
public:
void run();
private:
static const float BOUNCE_FACTOR;
static const float ACCEL;
static const float MAX_SPEED;
static const float JUMP_SPEED;
static const float GRAVITY;
static const float MAX_FALL;
void tick();
void playerCollision(teabag::Collision coll);
void key(sf::Keyboard::Key key, bool press);
void levelLoaded(std::string name);
void resetBoosts();
void resetBounces();
std::string current;
float xSpeed, ySpeed;
bool up, left, right, reset;
bool jumped;
sf::Clock clock;
int lvl, deaths, totalDeaths;
sf::Time time;
std::unordered_set<std::string> usedBoosts, usedBounces;
teabag::Game game;
};
const float Game::BOUNCE_FACTOR = 1.3;
const float Game::ACCEL = 0.5;
const float Game::MAX_SPEED = 3;
const float Game::JUMP_SPEED = 6.5;
const float Game::GRAVITY = 0.5;
const float Game::MAX_FALL = 5;
#endif
| 20.20339 | 60 | 0.69547 | YeyaSwizaw |
443b086d5d21c196e6f38d7d7a48694c08b79de9 | 1,058 | cpp | C++ | backup/2/exercism/c++/etl.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 21 | 2019-11-16T19:08:35.000Z | 2021-11-12T12:26:01.000Z | backup/2/exercism/c++/etl.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 1 | 2022-02-04T16:02:53.000Z | 2022-02-04T16:02:53.000Z | backup/2/exercism/c++/etl.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 4 | 2020-05-15T19:39:41.000Z | 2021-10-30T06:40:31.000Z | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/exercism/etl.html .
// etl.h
#include <iostream>
#include <map>
#include <vector>
class etl {
public:
static std::map<char, int>
transform(std::map<int, std::vector<char>> oldMapping);
};
// etl.cpp
#include "etl.h"
std::map<char, int>
etl::transform(std::map<int, std::vector<char>> oldMapping) {
std::map<char, int> newMapping;
for (auto pair : oldMapping) {
for (char ch : pair.second) {
newMapping[tolower(ch)] = pair.first;
}
}
return newMapping;
}
| 33.0625 | 345 | 0.690926 | yangyanzhan |
443b21178ff506e9f46bb077e21bb9b9b0a7de62 | 4,503 | cpp | C++ | dali-toolkit/public-api/controls/scrollable/item-view/item-layout.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2016-11-18T10:26:51.000Z | 2021-01-28T13:51:59.000Z | dali-toolkit/public-api/controls/scrollable/item-view/item-layout.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 13 | 2020-07-15T11:33:03.000Z | 2021-04-09T21:29:23.000Z | dali-toolkit/public-api/controls/scrollable/item-view/item-layout.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 10 | 2019-05-17T07:15:09.000Z | 2021-05-24T07:28:08.000Z | /*
* Copyright (c) 2020 Samsung Electronics 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.
*
*/
// CLASS HEADER
#include <dali-toolkit/public-api/controls/scrollable/item-view/item-layout.h>
// EXTERNAL INCLUDES
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/animation/time-period.h>
// INTERNAL INCLUDES
#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
#include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
namespace Dali
{
namespace Toolkit
{
struct ItemLayout::Impl
{
Vector3 mItemSize; ///< The size of an item in the layout
ControlOrientation::Type mOrientation; ///< the orientation of the layout.
Property::Map mProperties;
};
ItemLayout::ItemLayout()
: mImpl(new Impl)
{
mImpl->mOrientation = ControlOrientation::Up;
}
ItemLayout::~ItemLayout()
{
delete mImpl;
}
void ItemLayout::SetOrientation(ControlOrientation::Type orientation)
{
mImpl->mOrientation = orientation;
}
ControlOrientation::Type ItemLayout::GetOrientation() const
{
return mImpl->mOrientation;
}
void ItemLayout::GetItemSize(unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize) const
{
// If item-size has not been set then get the default size
if(mImpl->mItemSize == Vector3::ZERO)
{
GetDefaultItemSize(itemId, layoutSize, itemSize);
}
else
{
itemSize = mImpl->mItemSize;
}
}
void ItemLayout::SetItemSize(const Vector3& itemSize)
{
mImpl->mItemSize = itemSize;
}
float ItemLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize)
{
Vector3 itemPosition = GetItemPosition(itemID, currentLayoutPosition, layoutSize);
Vector3 itemSize;
GetItemSize(itemID, layoutSize, itemSize);
Vector3 onScreenArea = (layoutSize - itemSize) * 0.5f;
if(itemPosition.x < -onScreenArea.x || itemPosition.x > onScreenArea.x || itemPosition.y < -onScreenArea.y || itemPosition.y > onScreenArea.y)
{
// item not within viewable area
// safest thing to do here since we have no idea how the implementation will work is to return the scroll to position
return GetItemScrollToPosition(itemID);
}
return currentLayoutPosition;
}
int ItemLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
{
switch(direction)
{
case Control::KeyboardFocus::LEFT:
case Control::KeyboardFocus::UP:
{
itemID--;
if(itemID < 0)
{
itemID = loopEnabled ? maxItems - 1 : 0;
}
break;
}
case Control::KeyboardFocus::RIGHT:
case Control::KeyboardFocus::DOWN:
{
itemID++;
if(itemID >= maxItems)
{
itemID = loopEnabled ? 0 : maxItems - 1;
}
break;
}
default:
{
break;
}
}
return itemID;
}
float ItemLayout::GetFlickSpeedFactor() const
{
// By default, the speed factor while dragging and swiping is the same.
return GetScrollSpeedFactor();
}
void ItemLayout::SetLayoutProperties(const Property::Map& properties)
{
for(unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx)
{
KeyValuePair propertyPair(properties.GetKeyValue(idx));
if(propertyPair.first == DefaultItemLayoutProperty::ITEM_SIZE)
{
SetItemSize(propertyPair.second.Get<Vector3>());
}
else if(propertyPair.first == DefaultItemLayoutProperty::ORIENTATION)
{
//Up, Left, Down, Right
int orientationType = propertyPair.second.Get<int>();
if(orientationType <= ControlOrientation::Right && orientationType >= ControlOrientation::Up)
{
SetOrientation(ControlOrientation::Type(orientationType));
}
}
}
mImpl->mProperties = properties;
}
Property::Map ItemLayout::GetLayoutProperties()
{
return mImpl->mProperties;
}
} // namespace Toolkit
} // namespace Dali
| 27.457317 | 144 | 0.709527 | dalihub |
444397726e37aa87c9919626e01a4c0ca14e1dc1 | 2,794 | hpp | C++ | libs/core/src/molphene/vertex_attribs_buffer.hpp | janucaria/Molphene | e5374599512ff4400d04c7c16d79d3a111cc1911 | [
"MIT"
] | 3 | 2018-05-18T06:30:48.000Z | 2018-09-01T13:59:58.000Z | libs/core/src/molphene/vertex_attribs_buffer.hpp | janucaria/Molphene | e5374599512ff4400d04c7c16d79d3a111cc1911 | [
"MIT"
] | null | null | null | libs/core/src/molphene/vertex_attribs_buffer.hpp | janucaria/Molphene | e5374599512ff4400d04c7c16d79d3a111cc1911 | [
"MIT"
] | null | null | null | #ifndef MOLPHENE_VERTEX_ATTRIBS_BUFFER_HPP
#define MOLPHENE_VERTEX_ATTRIBS_BUFFER_HPP
#include "gl/buffer.hpp"
#include "gl/draw_instanced_arrays.hpp"
#include "opengl.hpp"
#include "shader_attrib_location.hpp"
#include "stdafx.hpp"
namespace molphene {
template<typename TDataType,
shader_attrib_location attrib_index,
GLuint VInstanceDivisor = 0,
GLboolean normalized = GL_FALSE,
GLenum usage = GL_STATIC_DRAW>
class VertexAttribsBuffer {
public:
using gl_array_buffer =
gl::buffer<TDataType, GL_ARRAY_BUFFER, GL_STATIC_DRAW>;
using data_type = typename gl_array_buffer::data_type;
static constexpr auto instance_divisor = VInstanceDivisor;
VertexAttribsBuffer() noexcept = default;
VertexAttribsBuffer(const VertexAttribsBuffer& rsh) = delete;
VertexAttribsBuffer(VertexAttribsBuffer&&) = delete;
auto operator=(const VertexAttribsBuffer& rsh)
-> VertexAttribsBuffer& = delete;
auto operator=(VertexAttribsBuffer&& rsh) -> VertexAttribsBuffer& = delete;
~VertexAttribsBuffer() noexcept = default;
void init(gsl::span<const data_type> arr) noexcept
{
buffer_.data(arr);
}
void size(GLsizeiptr size) noexcept
{
buffer_.reserved(size);
}
void data(GLintptr offset, GLsizeiptr size, const GLvoid* data) const noexcept
{
using SpanData = gsl::span<const data_type>;
buffer_.subdata(offset,
SpanData{static_cast<const data_type*>(data),
static_cast<typename SpanData::size_type>(size)});
}
void attrib_pointer() const noexcept
{
buffer_.bind();
if constexpr(gl_vertex_attrib<data_type>::is_matrix) {
using scalar_t = typename boost::qvm::mat_traits<data_type>::scalar_type;
for(auto index = 0, size = 4; index < size; ++index) {
const auto location = static_cast<GLuint>(attrib_index) + index;
glVertexAttribPointer(location,
gl_vertex_attrib<data_type>::size,
gl_vertex_attrib<data_type>::type,
normalized,
sizeof(data_type),
static_cast<scalar_t*>(nullptr) + size * index);
gl::vertex_attrib_divisor(location, instance_divisor);
}
} else {
const auto location = static_cast<GLuint>(attrib_index);
glVertexAttribPointer(location,
gl_vertex_attrib<data_type>::size,
gl_vertex_attrib<data_type>::type,
normalized,
0,
nullptr);
gl::vertex_attrib_divisor(location, instance_divisor);
}
}
private:
gl::buffer<TDataType> buffer_{};
};
} // namespace molphene
#endif
| 30.369565 | 80 | 0.644953 | janucaria |
444470330623a89a1b502288e6dcab1b0ae381b6 | 11,961 | cpp | C++ | Code/Engine/Core/World/Implementation/WorldData.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | Code/Engine/Core/World/Implementation/WorldData.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | Code/Engine/Core/World/Implementation/WorldData.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | #include <CorePCH.h>
#include <Core/World/SpatialSystem_RegularGrid.h>
#include <Core/World/World.h>
#include <Foundation/Time/DefaultTimeStepSmoothing.h>
namespace ezInternal
{
class DefaultCoordinateSystemProvider : public ezCoordinateSystemProvider
{
public:
DefaultCoordinateSystemProvider()
: ezCoordinateSystemProvider(nullptr)
{
}
virtual void GetCoordinateSystem(const ezVec3& vGlobalPosition, ezCoordinateSystem& out_CoordinateSystem) const override
{
out_CoordinateSystem.m_vForwardDir = ezVec3(1.0f, 0.0f, 0.0f);
out_CoordinateSystem.m_vRightDir = ezVec3(0.0f, 1.0f, 0.0f);
out_CoordinateSystem.m_vUpDir = ezVec3(0.0f, 0.0f, 1.0f);
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////
void WorldData::UpdateTask::Execute()
{
ezWorldModule::UpdateContext context;
context.m_uiFirstComponentIndex = m_uiStartIndex;
context.m_uiComponentCount = m_uiCount;
m_Function(context);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
WorldData::WorldData(ezWorldDesc& desc)
: m_sName(desc.m_sName)
, m_Allocator(desc.m_sName, ezFoundation::GetDefaultAllocator())
, m_AllocatorWrapper(&m_Allocator)
, m_BlockAllocator(desc.m_sName, &m_Allocator)
, m_StackAllocator(desc.m_sName, ezFoundation::GetAlignedAllocator())
, m_ObjectStorage(&m_BlockAllocator, &m_Allocator)
, m_MaxInitializationTimePerFrame(desc.m_MaxComponentInitializationTimePerFrame)
, m_Clock(desc.m_sName)
, m_WriteThreadID((ezThreadID)0)
, m_iWriteCounter(0)
, m_bSimulateWorld(true)
, m_bReportErrorWhenStaticObjectMoves(desc.m_bReportErrorWhenStaticObjectMoves)
, m_ReadMarker(*this)
, m_WriteMarker(*this)
, m_pUserData(nullptr)
{
m_AllocatorWrapper.Reset();
if (desc.m_uiRandomNumberGeneratorSeed == 0)
{
m_Random.InitializeFromCurrentTime();
}
else
{
m_Random.Initialize(desc.m_uiRandomNumberGeneratorSeed);
}
// insert dummy entry to save some checks
m_Objects.Insert(nullptr);
#if EZ_ENABLED(EZ_GAMEOBJECT_VELOCITY)
EZ_CHECK_AT_COMPILETIME(sizeof(ezGameObject::TransformationData) == 224);
#else
EZ_CHECK_AT_COMPILETIME(sizeof(ezGameObject::TransformationData) == 192);
#endif
EZ_CHECK_AT_COMPILETIME(sizeof(ezGameObject) == 168); /// \todo get game object size back to 128
EZ_CHECK_AT_COMPILETIME(sizeof(QueuedMsgMetaData) == 16);
EZ_CHECK_AT_COMPILETIME(sizeof(ezGameObjectId::m_WorldIndex) == sizeof(ezComponentId::m_WorldIndex));
EZ_CHECK_AT_COMPILETIME(sizeof(ezComponentId::m_TypeId) == sizeof(ezWorldModuleTypeId));
auto pDefaultInitBatch = EZ_NEW(&m_Allocator, InitBatch, &m_Allocator, "Default", true);
pDefaultInitBatch->m_bIsReady = true;
m_InitBatches.Insert(pDefaultInitBatch);
m_pDefaultInitBatch = pDefaultInitBatch;
m_pCurrentInitBatch = pDefaultInitBatch;
m_pSpatialSystem = std::move(desc.m_pSpatialSystem);
m_pCoordinateSystemProvider = desc.m_pCoordinateSystemProvider;
if (m_pSpatialSystem == nullptr && desc.m_bAutoCreateSpatialSystem)
{
m_pSpatialSystem = EZ_NEW(ezFoundation::GetAlignedAllocator(), ezSpatialSystem_RegularGrid);
}
if (m_pCoordinateSystemProvider == nullptr)
{
m_pCoordinateSystemProvider = EZ_NEW(&m_Allocator, DefaultCoordinateSystemProvider);
}
if (m_pTimeStepSmoothing == nullptr)
{
m_pTimeStepSmoothing = EZ_NEW(&m_Allocator, ezDefaultTimeStepSmoothing);
}
m_Clock.SetTimeStepSmoothing(m_pTimeStepSmoothing.Borrow());
}
WorldData::~WorldData()
{
EZ_ASSERT_DEV(m_Modules.IsEmpty(), "Modules should be cleaned up already.");
// delete all transformation data
for (ezUInt32 uiHierarchyIndex = 0; uiHierarchyIndex < HierarchyType::COUNT; ++uiHierarchyIndex)
{
Hierarchy& hierarchy = m_Hierarchies[uiHierarchyIndex];
for (ezUInt32 i = hierarchy.m_Data.GetCount(); i-- > 0;)
{
Hierarchy::DataBlockArray* blocks = hierarchy.m_Data[i];
for (ezUInt32 j = blocks->GetCount(); j-- > 0;)
{
m_BlockAllocator.DeallocateBlock((*blocks)[j]);
}
EZ_DELETE(&m_Allocator, blocks);
}
}
// delete task storage
for (ezUInt32 i = 0; i < m_UpdateTasks.GetCount(); ++i)
{
EZ_DELETE(&m_Allocator, m_UpdateTasks[i]);
}
// delete queued messages
for (ezUInt32 i = 0; i < ezObjectMsgQueueType::COUNT; ++i)
{
{
MessageQueue& queue = m_MessageQueues[i];
// The messages in this queue are allocated through a frame allocator and thus mustn't (and don't need to be) deallocated
queue.Clear();
}
{
MessageQueue& queue = m_TimedMessageQueues[i];
while (!queue.IsEmpty())
{
MessageQueue::Entry& entry = queue.Peek();
EZ_DELETE(&m_Allocator, entry.m_pMessage);
queue.Dequeue();
}
}
}
}
ezGameObject::TransformationData* WorldData::CreateTransformationData(bool bDynamic, ezUInt32 uiHierarchyLevel)
{
Hierarchy& hierarchy = m_Hierarchies[GetHierarchyType(bDynamic)];
while (uiHierarchyLevel >= hierarchy.m_Data.GetCount())
{
hierarchy.m_Data.PushBack(EZ_NEW(&m_Allocator, Hierarchy::DataBlockArray, &m_Allocator));
}
Hierarchy::DataBlockArray& blocks = *hierarchy.m_Data[uiHierarchyLevel];
Hierarchy::DataBlock* pBlock = nullptr;
if (!blocks.IsEmpty())
{
pBlock = &blocks.PeekBack();
}
if (pBlock == nullptr || pBlock->IsFull())
{
blocks.PushBack(m_BlockAllocator.AllocateBlock<ezGameObject::TransformationData>());
pBlock = &blocks.PeekBack();
}
return pBlock->ReserveBack();
}
void WorldData::DeleteTransformationData(bool bDynamic, ezUInt32 uiHierarchyLevel, ezGameObject::TransformationData* pData)
{
Hierarchy& hierarchy = m_Hierarchies[GetHierarchyType(bDynamic)];
Hierarchy::DataBlockArray& blocks = *hierarchy.m_Data[uiHierarchyLevel];
Hierarchy::DataBlock& lastBlock = blocks.PeekBack();
const ezGameObject::TransformationData* pLast = lastBlock.PopBack();
if (pData != pLast)
{
ezMemoryUtils::Copy(pData, pLast, 1);
pData->m_pObject->m_pTransformationData = pData;
// fix parent transform data for children as well
auto it = pData->m_pObject->GetChildren();
while (it.IsValid())
{
auto pTransformData = it->m_pTransformationData;
pTransformData->m_pParentData = pData;
it.Next();
}
}
if (lastBlock.IsEmpty())
{
m_BlockAllocator.DeallocateBlock(lastBlock);
blocks.PopBack();
}
}
void WorldData::TraverseBreadthFirst(VisitorFunc& func)
{
struct Helper
{
EZ_ALWAYS_INLINE static ezVisitorExecution::Enum Visit(ezGameObject::TransformationData* pData, void* pUserData)
{
return (*static_cast<VisitorFunc*>(pUserData))(pData->m_pObject);
}
};
const ezUInt32 uiMaxHierarchyLevel =
ezMath::Max(m_Hierarchies[HierarchyType::Static].m_Data.GetCount(), m_Hierarchies[HierarchyType::Dynamic].m_Data.GetCount());
for (ezUInt32 uiHierarchyLevel = 0; uiHierarchyLevel < uiMaxHierarchyLevel; ++uiHierarchyLevel)
{
for (ezUInt32 uiHierarchyIndex = 0; uiHierarchyIndex < HierarchyType::COUNT; ++uiHierarchyIndex)
{
Hierarchy& hierarchy = m_Hierarchies[uiHierarchyIndex];
if (uiHierarchyLevel < hierarchy.m_Data.GetCount())
{
ezVisitorExecution::Enum execution = TraverseHierarchyLevel<Helper>(*hierarchy.m_Data[uiHierarchyLevel], &func);
EZ_ASSERT_DEV(execution != ezVisitorExecution::Skip, "Skip is not supported when using breadth first traversal");
if (execution == ezVisitorExecution::Stop)
return;
}
}
}
}
void WorldData::TraverseDepthFirst(VisitorFunc& func)
{
struct Helper
{
EZ_ALWAYS_INLINE static ezVisitorExecution::Enum Visit(ezGameObject::TransformationData* pData, void* pUserData)
{
return WorldData::TraverseObjectDepthFirst(pData->m_pObject, *static_cast<VisitorFunc*>(pUserData));
}
};
for (ezUInt32 uiHierarchyIndex = 0; uiHierarchyIndex < HierarchyType::COUNT; ++uiHierarchyIndex)
{
Hierarchy& hierarchy = m_Hierarchies[uiHierarchyIndex];
if (!hierarchy.m_Data.IsEmpty())
{
if (TraverseHierarchyLevel<Helper>(*hierarchy.m_Data[0], &func) == ezVisitorExecution::Stop)
return;
}
}
}
// static
ezVisitorExecution::Enum WorldData::TraverseObjectDepthFirst(ezGameObject* pObject, VisitorFunc& func)
{
ezVisitorExecution::Enum execution = func(pObject);
if (execution == ezVisitorExecution::Stop)
return ezVisitorExecution::Stop;
if (execution != ezVisitorExecution::Skip) // skip all children
{
for (auto it = pObject->GetChildren(); it.IsValid(); ++it)
{
if (TraverseObjectDepthFirst(it, func) == ezVisitorExecution::Stop)
return ezVisitorExecution::Stop;
}
}
return ezVisitorExecution::Continue;
}
void WorldData::UpdateGlobalTransforms(float fInvDeltaSeconds)
{
struct UserData
{
ezSimdFloat m_fInvDt;
ezSpatialSystem* m_pSpatialSystem;
};
UserData userData;
userData.m_fInvDt = fInvDeltaSeconds;
userData.m_pSpatialSystem = m_pSpatialSystem.Borrow();
struct RootLevel
{
EZ_ALWAYS_INLINE static ezVisitorExecution::Enum Visit(ezGameObject::TransformationData* pData, void* pUserData)
{
WorldData::UpdateGlobalTransform(pData, static_cast<UserData*>(pUserData)->m_fInvDt);
return ezVisitorExecution::Continue;
}
};
struct WithParent
{
EZ_ALWAYS_INLINE static ezVisitorExecution::Enum Visit(ezGameObject::TransformationData* pData, void* pUserData)
{
WorldData::UpdateGlobalTransformWithParent(pData, static_cast<UserData*>(pUserData)->m_fInvDt);
return ezVisitorExecution::Continue;
}
};
struct RootLevelWithSpatialData
{
EZ_ALWAYS_INLINE static ezVisitorExecution::Enum Visit(ezGameObject::TransformationData* pData, void* pUserData)
{
WorldData::UpdateGlobalTransformAndSpatialData(pData, static_cast<UserData*>(pUserData)->m_fInvDt,
*static_cast<UserData*>(pUserData)->m_pSpatialSystem);
return ezVisitorExecution::Continue;
}
};
struct WithParentWithSpatialData
{
EZ_ALWAYS_INLINE static ezVisitorExecution::Enum Visit(ezGameObject::TransformationData* pData, void* pUserData)
{
WorldData::UpdateGlobalTransformWithParentAndSpatialData(pData, static_cast<UserData*>(pUserData)->m_fInvDt,
*static_cast<UserData*>(pUserData)->m_pSpatialSystem);
return ezVisitorExecution::Continue;
}
};
Hierarchy& hierarchy = m_Hierarchies[HierarchyType::Dynamic];
if (!hierarchy.m_Data.IsEmpty())
{
auto dataPtr = hierarchy.m_Data.GetData();
// If we have no spatial system, we perform multi-threaded update as we do not
// have to acquire a write lock in the process.
if (m_pSpatialSystem == nullptr)
{
TraverseHierarchyLevelMultiThreaded<RootLevel>(*dataPtr[0], &userData);
for (ezUInt32 i = 1; i < hierarchy.m_Data.GetCount(); ++i)
{
TraverseHierarchyLevelMultiThreaded<WithParent>(*dataPtr[i], &userData);
}
}
else
{
TraverseHierarchyLevel<RootLevelWithSpatialData>(*dataPtr[0], &userData);
for (ezUInt32 i = 1; i < hierarchy.m_Data.GetCount(); ++i)
{
TraverseHierarchyLevel<WithParentWithSpatialData>(*dataPtr[i], &userData);
}
}
}
}
} // namespace ezInternal
EZ_STATICLINK_FILE(Core, Core_World_Implementation_WorldData);
| 32.769863 | 131 | 0.679793 | fereeh |
4447bf1e425c808dae208796a759fb1b5a0ea9e8 | 19,077 | cpp | C++ | Code/ModelData/modelDataBaseExtend.cpp | jiaguobing/FastCAE | 2348ab87e83fe5c704e4c998cf391229c25ac5d5 | [
"BSD-3-Clause"
] | 2 | 2020-02-21T01:04:35.000Z | 2020-02-21T03:35:37.000Z | Code/ModelData/modelDataBaseExtend.cpp | jiaguobing/FastCAE | 2348ab87e83fe5c704e4c998cf391229c25ac5d5 | [
"BSD-3-Clause"
] | 1 | 2020-03-06T04:49:42.000Z | 2020-03-06T04:49:42.000Z | Code/ModelData/modelDataBaseExtend.cpp | baojunli/FastCAE | a3f99f6402da564df87fcef30674ce5f44379962 | [
"BSD-3-Clause"
] | 1 | 2021-11-21T13:03:26.000Z | 2021-11-21T13:03:26.000Z | #include "modelDataBaseExtend.h"
#include "BCBase/BCBase.h"
#include <QDomElement>
#include <assert.h>
#include "simulationSettingBase.h"
#include "solverSettingBase.h"
#include "ConfigOptions/ConfigOptions.h"
#include "ConfigOptions/DataConfig.h"
#include "ConfigOptions/PostCurve.h"
#include "ConfigOptions/PostConfig.h"
#include "ConfigOptions/PostConfigInfo.h"
#include "ConfigOptions/ObserverConfig.h"
#include "ConfigOptions/ParameterObserver.h"
#include "DataProperty/PropertyBase.h"
#include "DataProperty/PropertyString.h"
#include "DataProperty/ParameterInt.h"
#include "DataProperty/ParameterBool.h"
#include "DataProperty/ParameterDouble.h"
#include "DataProperty/ParameterSelectable.h"
#include "DataProperty/ParameterString.h"
#include "DataProperty/ParameterPath.h"
#include "DataProperty/ParameterTable.h"
#include <QDebug>
namespace ModelData
{
ModelDataBaseExtend::ModelDataBaseExtend(ProjectTreeType type)
: ModelDataBase(type)
{
ConfigOption::DataConfig* dataconfig = ConfigOption::ConfigOption::getInstance()->getDataConfig();
QList<ConfigOption::PostCurve*> monitorCurves = dataconfig->getMonitorCurves(_treeType);
_monitorFiles = dataconfig->getMonitorFile(_treeType);
for (int i = 0; i < monitorCurves.size(); ++i)
{
ConfigOption::PostCurve* p = new ConfigOption::PostCurve;
p->copy(monitorCurves.at(i));
_monitorCurves.append(p);
}
}
ModelDataBaseExtend::~ModelDataBaseExtend()
{
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* d = datalist.at(i);
delete d;
}
_configData.clear();
for (int i = 0; i < _observerList.size(); ++i)
{
auto obs = _observerList.at(i);
delete obs;
}
_observerList.clear();
}
void ModelDataBaseExtend::appendReport(QString report)
{
_reportList.append(report);
}
int ModelDataBaseExtend::getReportCount()
{
return _reportList.size();
}
void ModelDataBaseExtend::removeReportAt(int index)
{
assert(index >= 0 && index < _reportList.size());
_reportList.removeAt(index);
}
QString ModelDataBaseExtend::getReportAt(int index)
{
assert(index >= 0 && index < _reportList.size());
return _reportList.at(index);
}
QDomElement& ModelDataBaseExtend::writeToProjectFile(QDomDocument* doc, QDomElement* e)
{
QDomElement element = ModelDataBase::writeToProjectFile(doc, e);
QDomElement materialele = doc->createElement("Material");
QList<int> setidlist = _setMaterial.keys();
for (int i = 0; i < setidlist.size(); ++i)
{
int setid = setidlist.at(i);
int materialid = _setMaterial.value(setid);
QDomElement mc = doc->createElement("MaterialInfo");
QDomAttr setattr = doc->createAttribute("SetID");
QDomAttr materialattr = doc->createAttribute("MaterialID");
setattr.setValue(QString::number(setid));
materialattr.setValue(QString::number(materialid));
mc.setAttributeNode(setattr);
mc.setAttributeNode(materialattr);
materialele.appendChild(mc);
}
element.appendChild(materialele);
QDomElement configele = doc->createElement("ConfigData");
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* d = datalist.at(i);
const int id = _configData.key(d);
QDomElement dataele = doc->createElement("Data");
dataele.setAttribute("ID", id);
// QString name = d->getName();
// dataele.setAttribute("TreeNode", name);
d->writeParameters(doc, &dataele);
configele.appendChild(dataele);
}
element.appendChild(configele);
QDomElement ele = doc->createElement("Report");
for (int i = 0; i < _reportList.size(); ++i)
{
QDomElement textele = doc->createElement("Path");
QString text = _reportList.at(i);
QDomText textdom = doc->createTextNode(text);
textele.appendChild(textdom);
ele.appendChild(textele);
}
element.appendChild(ele);
return element;
}
void ModelDataBaseExtend::writeToProjectFile1(QDomDocument* doc, QDomElement* e)
{
ModelDataBase::writeToProjectFile1(doc, e);
QDomElement materialele = doc->createElement("Material");
QList<int> setidlist = _setMaterial.keys();
for (int i = 0; i < setidlist.size(); ++i)
{
int setid = setidlist.at(i);
int materialid = _setMaterial.value(setid);
QDomElement mc = doc->createElement("MaterialInfo");
QDomAttr setattr = doc->createAttribute("SetID");
QDomAttr materialattr = doc->createAttribute("MaterialID");
setattr.setValue(QString::number(setid));
materialattr.setValue(QString::number(materialid));
mc.setAttributeNode(setattr);
mc.setAttributeNode(materialattr);
materialele.appendChild(mc);
}
e->appendChild(materialele);
QDomElement configele = doc->createElement("ConfigData");
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* d = datalist.at(i);
const int id = _configData.key(d);
QDomElement dataele = doc->createElement("Data");
dataele.setAttribute("ID", id);
d->writeParameters(doc, &dataele);
configele.appendChild(dataele);
}
e->appendChild(configele);
QDomElement ele = doc->createElement("Report");
for (int i = 0; i < _reportList.size(); ++i)
{
QDomElement textele = doc->createElement("Path");
QString text = _reportList.at(i);
QDomText textdom = doc->createTextNode(text);
textele.appendChild(textdom);
ele.appendChild(textele);
}
e->appendChild(ele);
}
void ModelDataBaseExtend::readDataFromProjectFile(QDomElement* e)
{
ModelDataBase::readDataFromProjectFile(e);
QDomNodeList materialList = e->elementsByTagName("MaterialInfo");
for (int i = 0; i < materialList.size(); ++i)
{
QDomElement ele = materialList.at(i).toElement();
QString ssetid = ele.attribute("SetID");
QString smaterialID = ele.attribute("MaterialID");
int setid = ssetid.toInt();
int maid = smaterialID.toInt();
this->setMaterial(setid, maid);
}
QDomNodeList configdata = e->elementsByTagName("ConfigData");
if (configdata.size() == 1)
{
QDomElement cele = configdata.at(0).toElement();
QDomNodeList datalist = cele.elementsByTagName("Data");
for (int i = 0; i < datalist.size(); ++i)
{
QDomElement ele = datalist.at(i).toElement();
QString sid = ele.attribute("ID");
// QString sname = ele.attribute("TreeNode");
const int id = sid.toInt();
DataProperty::DataBase* d = new DataProperty::DataBase;
d->setModuleType(DataProperty::Module_Model);
d->setID(_id);
// d->setName(sname);
d->readParameters(&ele);
if (_configData.contains(id))
{
DataProperty::DataBase* dd = _configData.value(id);
if (dd != nullptr) delete dd;
}
_configData[id] = d;
}
}
QDomNodeList reportNodelist = e->elementsByTagName("Report");
if (reportNodelist.size() == 1)
{
QDomElement element = reportNodelist.at(0).toElement();
QDomNodeList pathlist = element.elementsByTagName("Path");
const int n = pathlist.size();
for (int i = 0; i < n; ++i)
{
QDomElement ele = pathlist.at(i).toElement();
QString p = ele.text();
_reportList.append(p);
}
}
this->registerObserver();
}
void ModelDataBaseExtend::writeToSolverXML(QDomDocument* doc, QDomElement* e)
{
this->writeToProjectFile(doc, e);
}
void ModelDataBaseExtend::setMaterial(int setID, int materialID) {
if ((!_componentIDList.contains(setID)) || materialID <= 0) return;
_setMaterial[setID] = materialID;
}
int ModelDataBaseExtend::getMaterialID(int setid)
{
int m = -1;
if (_setMaterial.contains(setid))
{
m = _setMaterial.value(setid);
}
return m;
}
bool ModelDataBaseExtend::isMaterialSetted(int setid)
{
bool s = false;
if (_setMaterial.contains(setid))
{
if (_setMaterial.value(setid) >= 0)
s = true;
}
return s;
}
void ModelDataBaseExtend::removeMaterial(int setid)
{
if (_setMaterial.contains(setid))
{
_setMaterial.remove(setid);
}
}
void ModelDataBaseExtend::setMeshSetList(QList<int> ids)
{
QList<int> old = _componentIDList;
QList<int> removeid;
for (auto id : old)
if (!ids.contains(id)) removeid.append(id);
for (int id : removeid)
{
if (_setMaterial.contains(id))
_setMaterial.remove(id);
for (auto bc : _bcList)
{
if (bc->getMeshSetID() == id)
{
_bcList.removeOne(bc);
delete bc;
break;
}
}
}
ModelDataBase::setMeshSetList(ids);
}
void ModelDataBaseExtend::removeMeshSetAt(int index)
{
assert(index >= 0 && index < _componentIDList.size());
int id = _componentIDList.at(index);
if (isMaterialSetted(id))
{
removeMaterial(id);
}
ModelDataBase::removeMeshSetAt(index);
}
void ModelDataBaseExtend::copyFormConfig()
{
ConfigOption::DataConfig* dataconfig = ConfigOption::ConfigOption::getInstance()->getDataConfig();
QHash<int, DataProperty::DataBase*> configList = dataconfig->getConfigData(_treeType);
QList<int> ids = configList.keys();
for (int i = 0; i < ids.size(); ++i)
{
const int id = ids.at(i);
DataProperty::DataBase* d = configList.value(id);
DataProperty::DataBase* newdata = new DataProperty::DataBase;
newdata->setModuleType(DataProperty::Module_Model);
newdata->copy(d);
newdata->setID(_id);
_configData[id] = newdata;
}
_monitorFiles = dataconfig->getMonitorFile(_treeType);
// _monitorCurves = dataconfig->getMonitorCurves(_treeType);
ModelDataBase::copyFormConfig();
this->registerObserver();
}
QList<ConfigOption::PostCurve*> ModelDataBaseExtend::getMonitorCurves()
{
return _monitorCurves;
}
ConfigOption::PostCurve* ModelDataBaseExtend::getMonitorCurveAt(const int index)
{
assert(index >= 0 && index < _monitorCurves.size());
return _monitorCurves.at(index);
}
void ModelDataBaseExtend::appendConfigData(int dataID, DataProperty::DataBase* data)
{
if (data == nullptr) return;
if (_configData.contains(dataID))
{
DataProperty::DataBase* d = _configData.value(dataID);
delete d;
_configData.remove(dataID);
}
_configData[dataID] = data;
}
DataProperty::DataBase* ModelDataBaseExtend::getConfigData(int dataID)
{
return _configData.value(dataID);
}
int ModelDataBaseExtend::getConfigDataCount()
{
return _configData.count();
}
// QString ModelDataBaseExtend::getMonitorList()
// {
// return _monitor;
// }
QStringList ModelDataBaseExtend::getMonitorFile()
{
return _monitorFiles;
}
QStringList ModelDataBaseExtend::getAbsoluteMonitorFile()
{
QStringList s;
QString path = this->getPath();
for (int i = 0; i < _monitorFiles.size(); ++i)
{
QString ss = path + "/MonitorFiles/" + _monitorFiles.at(i);
s.append(ss);
}
return s;
}
QStringList ModelDataBaseExtend::getMonitorVariables(QString f)
{
QStringList v;
for (int i = 0; i < _monitorCurves.size(); ++i)
{
ConfigOption::PostCurve* c = _monitorCurves.at(i);
QString file = c->getFile();
if (!f.endsWith(file)) continue;
QString x = c->getXVariable();
QString y = c->getYVariable();
if (!v.contains(x)) v.append(x);
if (!v.contains(y)) v.append(y);
}
return v;
}
QStringList ModelDataBaseExtend::getPost2DFiles()
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
QStringList s;
if (info != nullptr)
s = info->getPost2DFile();
return s;
}
QStringList ModelDataBaseExtend::getAbsolutePost2DFiles()
{
QStringList s = this->getPost2DFiles();
QStringList f;
QString path = this->getPath() + "/Result/";
for (int i = 0; i < s.size(); ++i)
{
f.append(path + s.at(i));
}
return f;
}
QStringList ModelDataBaseExtend::getPost2DVariables(QString f)
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
QStringList s;
if (info != nullptr)
s = info->get2DVariables(f);
return s;
}
QString ModelDataBaseExtend::getPost3DFile()
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
if (info != nullptr)
return info->getPost3DFile();
return "";
}
void ModelDataBaseExtend::get3DScalars(QStringList &node, QStringList &ele)
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
if (info != nullptr)
{
node = info->getNodeScalarVariable();
ele = info->getCellScalarVariable();
}
}
void ModelDataBaseExtend::get3DVector(QStringList &node, QStringList &ele)
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
if (info != nullptr)
{
node = info->getNodeVectorVariable();
ele = info->getCellVectorVariable();
}
}
void ModelDataBaseExtend::appendScalarVariable(QString v)
{
_scalarVariable.append(v);
}
void ModelDataBaseExtend::removeScalarVariable(int index)
{
if (index < 0 || index >= _scalarVariable.size()) return;
_scalarVariable.removeAt(index);
}
QStringList ModelDataBaseExtend::getScalarVariable()
{
return _scalarVariable;
}
void ModelDataBaseExtend::appendVectorVariable(QString v)
{
_vectorVariable.append(v);
}
void ModelDataBaseExtend::removeVectorVariable(int index)
{
if (index < 0 || index >= _vectorVariable.size()) return;
_vectorVariable.removeAt(index);
}
QStringList ModelDataBaseExtend::getVectorVariable()
{
return _vectorVariable;
}
void ModelDataBaseExtend::apppendPlotCurve(ConfigOption::PostCurve* c)
{
_postCurves.append(c);
}
QList<ConfigOption::PostCurve*> ModelDataBaseExtend::getPlotCurves()
{
return _postCurves;
}
void ModelDataBaseExtend::removePlotCurve(int index)
{
_postCurves.removeAt(index);
}
bool ModelDataBaseExtend::isPostCurveExist(QString name)
{
for (int i = 0; i < _postCurves.size(); ++i)
{
ConfigOption::PostCurve* c = _postCurves.at(i);
QString n = c->getDescribe();
if (n == name) return true;
}
return false;
}
void ModelDataBaseExtend::clearPlotCurve()
{
for (int i = 0; i < _postCurves.size(); ++i)
{
ConfigOption::PostCurve* c = _postCurves.at(i);
delete c;
}
_postCurves.clear();
}
void ModelDataBaseExtend::clear3DVariable()
{
_scalarVariable.clear();
_vectorVariable.clear();
}
DataProperty::ParameterBase* ModelDataBaseExtend::getParameterByName(QString name)
{
DataProperty::ParameterBase* P = nullptr;
P = ModelDataBase::getParameterByName(name);
if (P != nullptr) return P;
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
P = d->getParameterByName(name);
if (P != nullptr)
break;
}
return P;
}
void ModelDataBaseExtend::removeParameter(DataProperty::ParameterBase* p)
{
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
d->removeParameter(p);
}
ModelDataBase::removeParameter(p);
}
void ModelDataBaseExtend::removeParameterGroup(DataProperty::ParameterGroup* g)
{
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
d->removeParameterGroup(g);
}
ModelDataBase::removeParameterGroup(g);
}
DataProperty::ParameterGroup* ModelDataBaseExtend::getParameterGroupByName(QString name)
{
DataProperty::ParameterGroup* g = nullptr;
g = ModelDataBase::getParameterGroupByName(name);
if (g != nullptr) return g;
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
g = d->getParameterGroupByName(name);
if (g != nullptr)
break;
}
return g;
}
void ModelDataBaseExtend::registerObserver()
{
QList<ConfigOption::ParameterObserver*> obslist = ConfigOption::ConfigOption::getInstance()->getObseverConfig()->getObserverList(_treeType);
const int n = obslist.size();
for (int i = 0; i < n; ++i)
{
ConfigOption::ParameterObserver* obs = obslist.at(i)->copy();
if (obs == nullptr) continue;
_observerList.append(obs);
QStringList activePara = obs->getActiveParameterNames();
for (int i = 0; i < activePara.size(); ++i)
{
QString name = activePara.at(i);
qDebug() << name;
auto para = this->getParameterByName(name);
if (para == nullptr)
{
obs->removeConfigActive(name);
}
else
{
obs->appendDataActive(name, para);
para->appendObserver(obs);
}
}
QStringList followPara = obs->getFollowParameterNames();
for (int i = 0; i < followPara.size(); ++i)
{
QString name = followPara.at(i);
auto para = this->getParameterByName(name);
if (para == nullptr)
{
obs->removeConfigFollow(name);
}
else
obs->appendDataFollow(name, para);
}
QStringList followgroup = obs->getFollowGroupNames();
for (int i = 0; i < followgroup.size(); ++i)
{
QString name = followgroup.at(i);
auto para = this->getParameterGroupByName(name);
if (para == nullptr)
{
obs->removeConfigFollow(name);
}
else
obs->appendDataFollowGroup(name, para);
}
obs->observe();
}
}
void ModelDataBaseExtend::dataToStream(QDataStream* datas){
*datas << _name << _id << _treeType;
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.count();++i)
{
DataProperty::DataBase* data = datalist.at(i);
data->dataToStream(datas);
}
}
void ModelDataBaseExtend::generateParaInfo()
{
DataBase::generateParaInfo();
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* data = datalist.at(i);
data->generateParaInfo();
}
ModelDataBase::generateParaInfo();
}
void ModelDataBaseExtend::setPost2DWindow(Post::Post2DWindowInterface* p2d)
{
_post2DWindow = p2d;
}
Post::Post2DWindowInterface* ModelDataBaseExtend::getPost2DWindow()
{
return _post2DWindow;
}
void ModelDataBaseExtend::setPost3DWindow(Post::Post3DWindowInterface* p3d)
{
_post3DWindow = p3d;
}
Post::Post3DWindowInterface* ModelDataBaseExtend::getPost3DWindow()
{
return _post3DWindow;
}
} | 28.013216 | 143 | 0.671122 | jiaguobing |
444b370f61e5087fa2c7f7f540ee6ca18fce66eb | 5,202 | cc | C++ | src/ThreeOpt.cc | nklisch/AntColony-Parallel-Optimized | dd7e00d794a72d74b3761faf9d9282cfdd7fa356 | [
"MIT"
] | null | null | null | src/ThreeOpt.cc | nklisch/AntColony-Parallel-Optimized | dd7e00d794a72d74b3761faf9d9282cfdd7fa356 | [
"MIT"
] | null | null | null | src/ThreeOpt.cc | nklisch/AntColony-Parallel-Optimized | dd7e00d794a72d74b3761faf9d9282cfdd7fa356 | [
"MIT"
] | 1 | 2021-02-03T07:20:37.000Z | 2021-02-03T07:20:37.000Z |
#include "ThreeOpt.h"
#include "CandidateLists.h"
#include <iostream>
using namespace std;
// Code inspired and derived from http://tsp-basics.blogspot.com/2017/04/3-opt-with-neighbor-lists-and-dlb.html
ThreeOpt::ThreeOpt(Tour* tour, CandidateLists* cl) {
this->tour = tour;
this->cl = cl;
dontLookBit = new bool[cl->getNumberOfNodes()];
clearDLB();
}
ThreeOpt::~ThreeOpt() {
delete[] dontLookBit;
}
long ThreeOpt::gainFrom2Opt(unsigned int x1, unsigned int x2, unsigned int y1, unsigned int y2){
long delLength = cl->distance(x1, x2) + cl->distance(y1,y2);
long addLength = cl->distance(x1, y1) + cl->distance(x2,y2);
return delLength - addLength;
}
long ThreeOpt::gainFrom3Opt(unsigned int x1, unsigned int x2, unsigned int y1, unsigned int y2, unsigned int z1, unsigned int z2, OptCase c){
long addLength = 0;
switch(c){
case case6:
addLength = cl->distance(x1, y2) + cl->distance(z1, y1) + cl->distance(x2, z2);
break;
case case7:
addLength = cl->distance(x1, y2) + cl->distance(z1, x2) + cl->distance(y1, z2);
break;
case case1:
break;
}
long delLength = cl->distance(x1, x2) + cl->distance(y1, y2) + cl->distance(z1, z2);
return delLength - addLength;
}
void ThreeOpt::makeMove(const Move& move){
unsigned int N = cl->getNumberOfNodes();
switch(move.optCase){
case case1:
tour->reverse((move.k+1) % N, move.i);
break;
case case6:
tour->reverse((move.k+1) % N, move.i);
tour->reverse((move.j+1) % N, move.k);
break;
case case7:
tour->reverse((move.k+1) % N, move.i);
tour->reverse((move.i+1) % N, move.j);
tour->reverse((move.j+1) % N, move.k);
break;
}
}
bool ThreeOpt::oneCity3Opt(unsigned int start){
bool improved = false;
unsigned int N = cl->getNumberOfNodes();
unsigned int i, j;
long gainExpected = 0;
Move goodMove(0,0,0,case1,0);
for(int toggle = 0; toggle < 2; toggle++){
if(toggle)
i = (N + start - 1) % N;
else
i = start;
unsigned int x1 = tour->getNode(i);
unsigned int x2 = tour->getNode((i+1) % N);
for(unsigned int neighborIndex1 = 0; neighborIndex1 < cl->size(); neighborIndex1++){
unsigned int y2 = cl->getNode(x1,neighborIndex1);
j = (tour->getNodePositionInTour(y2) + N - 1) % N;
unsigned int y1 = tour->getNode(j);
if(y1 != x1 && y1 != x2){
gainExpected = gainFrom2Opt(x1,x2,y1,y2);
if (gainExpected > goodMove.gain){
improved = true;
goodMove.set(i,j,j,case1, gainExpected);
}
}
for(unsigned int neighborIndex2 = 0; neighborIndex2 < cl->size(); neighborIndex2++){
unsigned int z1_6 = cl->getNode(y1,neighborIndex2);
unsigned int k_6 = tour->getNodePositionInTour(z1_6);
unsigned int z2_6 = tour->getNode((k_6 + 1) % N);
unsigned int z2_7 = z1_6;
unsigned int k_7 = (tour->getNodePositionInTour(z2_7) + N - 1) % N;
unsigned int z1_7 = tour->getNode(k_7);
if (between(i,j,k_6)){
gainExpected = gainFrom3Opt(x1,x2,y1,y2,z1_6,z2_6,case6);
if (gainExpected > goodMove.gain){
improved = true;
goodMove.set(i,j,k_6,case6, gainExpected);
}
}
if (between(i,j,k_7)){
gainExpected = gainFrom3Opt(x1,x2,y1,y2,z1_7,z2_7,case7);
if (gainExpected > goodMove.gain){
improved = true;
goodMove.set(i,j,k_7,case7, gainExpected);
}
}
}
}
}
if (improved){
dontLookBit[goodMove.i] = false;
dontLookBit[goodMove.j] = false;
dontLookBit[goodMove.k] = false;
dontLookBit[(goodMove.i + 1) % N] = false;
dontLookBit[(goodMove.j + 1) % N] = false;
dontLookBit[(goodMove.k + 1) % N] = false;
makeMove(goodMove);
}
return improved;
}
void ThreeOpt::clearDLB(){
for(unsigned int i = 0; i < cl->getNumberOfNodes(); i++){
dontLookBit[i] = false;
}
}
bool ThreeOpt::between(unsigned int a, unsigned int x, unsigned int b){
if (b > a)
return (x > a) && (x < b);
else if (b < a)
return (x > a) || (x < b);
return false;
}
void ThreeOpt::optimize(){
bool optimal = false;
while(!optimal){
optimal = true;
for(unsigned int tourIndex = 0; tourIndex < cl->getNumberOfNodes(); tourIndex++){
unsigned int node = tour->getNode(tourIndex);
if(!dontLookBit[node]) {
if (oneCity3Opt(tourIndex))
optimal = false;
else
dontLookBit[node] = true;
}
}
}
} | 31.91411 | 141 | 0.524029 | nklisch |
444d82fa1f048509a2f06fd8b25fae965b39a3b6 | 14,312 | cc | C++ | src/script_parse.cc | pekdon/plux | 74d7dd1e4bd57dda0b2a3754e77af068205dabe1 | [
"MIT"
] | null | null | null | src/script_parse.cc | pekdon/plux | 74d7dd1e4bd57dda0b2a3754e77af068205dabe1 | [
"MIT"
] | null | null | null | src/script_parse.cc | pekdon/plux | 74d7dd1e4bd57dda0b2a3754e77af068205dabe1 | [
"MIT"
] | null | null | null | #include <fstream>
#include "regex.hh"
#include "script_parse.hh"
namespace plux
{
ScriptParseError::ScriptParseError(const std::string& path,
unsigned int linenumber,
const std::string& line,
const std::string& error) throw()
: _path(path),
_linenumber(linenumber),
_line(line),
_error(error)
{
}
ScriptParseError::~ScriptParseError(void) throw()
{
}
/**
* Script parser state, transitions go in order of apperance.
*/
enum parse_state {
PARSE_STATE_BEGIN,
PARSE_STATE_DOC,
PARSE_STATE_HEADERS,
PARSE_STATE_SHELL,
PARSE_STATE_CLEANUP
};
/** Textual representation of pattern matching shell names, keep
in sync with _shell_name_regex. */
std::string ScriptParse::SHELL_NAME_CHARS = "A-Z, a-z, 0-9, - and _";
/**
* Create a new ScriptParse instance, used for parsing a PLUX
* script with the parse method. Once parse is called this
* instance is consumed.
*/
ScriptParse::ScriptParse(const std::string& path, std::istream *is)
: _path(path),
_is(is),
_linenumber(0),
_shell_name_regex("^[A-Za-z0-9_-]+$")
{
}
/**
* Parse PLUX script from constructor provided istream.
*/
std::unique_ptr<Script> ScriptParse::parse(void)
{
auto script = std::unique_ptr<Script>(new Script(_path));
Line* line_cmd;
std::string buf;
ScriptParseCtx ctx;
enum parse_state state = PARSE_STATE_BEGIN;
while (next_line(ctx)) {
switch (state) {
case PARSE_STATE_BEGIN:
if (ctx.line.compare("[doc]") != 0) {
parse_error(ctx.line, "unexpected content, expected [doc]");
}
state = PARSE_STATE_DOC;
buf = "";
break;
case PARSE_STATE_DOC:
if (ctx.line.compare("[enddoc]") == 0) {
script->set_doc(buf);
state = PARSE_STATE_HEADERS;
} else if (ctx.starts_with("[")) {
parse_error(ctx.line,
"unexpected content, expected [enddoc]");
} else {
buf.append(ctx.line);
}
break;
case PARSE_STATE_HEADERS:
if (parse_shell(ctx, ctx.shell)) {
state = PARSE_STATE_SHELL;
} else if (ctx.starts_with("[function ")) {
auto fun = parse_function(ctx);
script->fun_add(fun->name(), fun);
} else if (ctx.starts_with("[macro ")) {
auto macro = parse_macro(ctx);
delete macro;
} else {
line_cmd = parse_header_cmd(ctx);
script->header_add(line_cmd);
}
break;
case PARSE_STATE_SHELL:
if (parse_shell(ctx, ctx.shell)) {
} else if (ctx.starts_with("[cleanup]")) {
state = PARSE_STATE_CLEANUP;
ctx.shell = "cleanup";
} else {
line_cmd = parse_line_cmd(ctx);
script->line_add(line_cmd);
}
break;
case PARSE_STATE_CLEANUP:
line_cmd = parse_line_cmd(ctx);
script->cleanup_add(line_cmd);
break;
}
}
return script;
}
/**
* Parse [shell name] command.
*
* @return true if line is a valid shell line, false if not a shell command.
*/
bool ScriptParse::parse_shell(ScriptParseCtx& ctx, std::string& shell_ret)
{
if (! ctx.starts_with("[shell ")) {
return false;
}
if (! ctx.ends_with("]")) {
parse_error(ctx.line, "shell command does not end with ]");
}
std::string name = ctx.substr(7, 1);
if (! plux::regex_match(name, _shell_name_regex)
|| name.compare("cleanup") == 0) {
std::string error("invalid shell name: ");
error += name + ". only " + SHELL_NAME_CHARS + " allowed";
parse_error(ctx.line, error);
}
shell_ret = name;
return true;
}
/**
* Parse commands valid in script header.
*/
Line* ScriptParse::parse_header_cmd(const ScriptParseCtx& ctx)
{
if (ctx.starts_with("[include ")) {
parse_error(ctx.line, "not implemented");
} else if (ctx.starts_with("[config ")) {
return parse_config(ctx);
} else if (ctx.starts_with("[global ")) {
return parse_global(ctx);
} else {
parse_error(ctx.line, "unexpected content in headers");
}
return nullptr;
}
/**
* Parse commands valid inside of [shell name] and [cleanup] section
*
* @return Line
*/
Line* ScriptParse::parse_line_cmd(const ScriptParseCtx& ctx)
{
if (ctx.starts_with("!")) {
auto output = ctx.substr(1, 0);
// FIXME: add list of control characters
if (output != "$_CTRL_C_") {
output += "\n";
}
return new LineOutput(_path, _linenumber, ctx.shell, output);
} else if (ctx.starts_with("?")) {
auto match_start = ctx.line.find_first_not_of("?", ctx.start);
if ((match_start - ctx.start) == 1) {
return new LineRegexMatch(_path, _linenumber, ctx.shell,
ctx.substr(1, 0));
} else if ((match_start - ctx.start) == 2) {
return new LineVarMatch(_path, _linenumber, ctx.shell,
ctx.substr(2, 0));
} else {
return new LineExactMatch(_path, _linenumber, ctx.shell,
ctx.substr(3, 0));
}
} else if (ctx.starts_with("-")) {
return new LineSetErrorPattern(_path, _linenumber, ctx.shell,
ctx.substr(1, 0));
} else if (ctx.starts_with("[") && ctx.ends_with("]")) {
if (ctx.starts_with("[global ")) {
return parse_global(ctx);
} else if (ctx.starts_with("[local ")) {
return parse_local(ctx);
} else if (ctx.starts_with("[timeout")) {
return parse_timeout(ctx);
} else if (ctx.starts_with("[call ")) {
return parse_call(ctx);
} else if (ctx.starts_with("[progress ")) {
return parse_progress(ctx);
} else if (ctx.starts_with("[log ")) {
return parse_log(ctx);
} else {
parse_error(ctx.line,
"unexpected content, unsupported function");
}
} else {
parse_error(ctx.line, "unexpected content");
}
return nullptr;
}
Line* ScriptParse::parse_timeout(const ScriptParseCtx& ctx)
{
unsigned int timeout_s = 0;
if (ctx.line[ctx.start + 8] != ']') {
std::string timeout_str = ctx.substr(9, 1);
try {
timeout_s = std::stoul(timeout_str);
} catch (std::invalid_argument&) {
throw ScriptParseError(_path, _linenumber, ctx.line,
"invalid timeout, not a valid number");
}
}
return new LineTimeout(_path, _linenumber, ctx.shell,
timeout_s * 1000);
}
Line* ScriptParse::parse_call(const ScriptParseCtx& ctx)
{
auto name_start = ctx.line.find_first_not_of(" \t", ctx.start + 6);
auto name_end = ctx.line.find_first_of(" \t", name_start);
if (name_end == std::string::npos) {
auto name = ctx.line.substr(name_start,
ctx.line.size() - name_start - 1);
return new LineCall(_path, _linenumber, ctx.shell,
name);
} else {
auto name = ctx.line.substr(name_start, name_end - name_start);
std::vector<std::string> args;
parse_args(ctx, name_end, args);
return new LineCall(_path, _linenumber, ctx.shell,
name, args);
}
}
Line* ScriptParse::parse_progress(const ScriptParseCtx& ctx)
{
return new LineProgress(_path, _linenumber, ctx.shell,
ctx.substr(10, 1));
}
Line* ScriptParse::parse_log(const ScriptParseCtx& ctx)
{
return new LineLog(_path, _linenumber, ctx.shell,
ctx.substr(5, 1));
}
Function* ScriptParse::parse_function(const ScriptParseCtx& ctx)
{
if (! ctx.ends_with("]")) {
parse_error(ctx.line, "function does not end with ]");
}
auto name_end = ctx.line.find_first_of(" \t", ctx.start + 10);
if (name_end == std::string::npos) {
name_end = ctx.line.size() - 1;
}
auto name = ctx.line.substr(ctx.start + 10, name_end - ctx.start - 10);
std::vector<std::string> args;
if (ctx.line[name_end] != ']') {
parse_args(ctx, name_end, args);
}
auto fun = new Function(_path, _linenumber, name, args);
ScriptParseCtx fun_ctx;
while (next_line(fun_ctx)) {
if (fun_ctx.starts_with("[endfunction]")) {
return fun;
}
if (! parse_shell(fun_ctx, fun_ctx.shell)) {
auto line_cmd = parse_line_cmd(fun_ctx);
fun->line_add(line_cmd);
}
}
delete fun;
parse_error("", "EOF while scanning for [endfunction]");
return nullptr;
}
Macro* ScriptParse::parse_macro(const ScriptParseCtx& ctx)
{
parse_error(ctx.line, "not implemented");
return nullptr;
}
Line* ScriptParse::parse_config(const ScriptParseCtx& ctx)
{
if (ctx.starts_with("[config require=")) {
std::string key, val;
auto val_start = ctx.line.find('=', ctx.start + 16);
if (val_start == std::string::npos) {
key = ctx.substr(16, 1);
val = "";
} else {
// value set, require specific value
key = ctx.substr(16, ctx.line.size() - val_start);
val = ctx.substr(val_start - ctx.start + 1, 1);
}
return new HeaderConfigRequire(_path, _linenumber, key, val);
}
parse_error(ctx.line, "unexpected content, config");
return nullptr;
}
Line* ScriptParse::parse_global(const ScriptParseCtx& ctx)
{
ScriptParseCtx var_ctx(ctx);
var_ctx.start += 8;
return parse_var_assign(var_ctx, VAR_SCOPE_GLOBAL);
}
Line* ScriptParse::parse_local(const ScriptParseCtx& ctx)
{
ScriptParseCtx var_ctx(ctx);
var_ctx.start += 7;
return parse_var_assign(var_ctx, VAR_SCOPE_SHELL);
}
Line* ScriptParse::parse_var_assign(const ScriptParseCtx& ctx,
enum var_scope scope)
{
std::string::size_type val_start = ctx.line.find('=', ctx.start);
if (val_start == std::string::npos) {
parse_error(ctx.line, "missing = in variable assignment");
}
std::string key = ctx.line.substr(ctx.start, val_start - ctx.start);
std::string val = ctx.line.substr(val_start + 1,
ctx.line.size() - val_start - 2);
if (scope == VAR_SCOPE_GLOBAL) {
return new LineVarAssignGlobal(_path, _linenumber, ctx.shell,
key, val);
} else if (scope == VAR_SCOPE_SHELL) {
return new LineVarAssignShell(_path, _linenumber, ctx.shell,
key, val);
} else {
throw ScriptParseError(_path, _linenumber, ctx.line,
"unsupporter variable scope");
}
}
/**
* Get next input line of relevance for the script parser thus
* including comment and empty lines.
*/
bool ScriptParse::next_line(ScriptParseCtx& ctx)
{
bool is_good = _is->good();
std::getline(*_is, ctx.line);
while (is_good) {
_linenumber++;
ctx.start = ctx.line.find_first_not_of(" \t");
if (ctx.start == std::string::npos
|| ctx.start == ctx.line.size()
|| ctx.starts_with("#")) {
// whitespace, empty or comment line
is_good = _is->good();
std::getline(*_is, ctx.line);
} else {
return true;
}
}
return false;
}
void ScriptParse::parse_args(const ScriptParseCtx& ctx,
std::string::size_type start,
std::vector<std::string> &args)
{
auto arg_start = ctx.line.find_first_not_of(" \t", start);
auto arg_end = ctx.line.find_first_of(" \t", arg_start);
while (arg_end != std::string::npos) {
auto arg = ctx.line.substr(arg_start, arg_end - arg_start);
args.push_back(arg);
arg_start = ctx.line.find_first_not_of(" \t", arg_end);
arg_end = ctx.line.find_first_of(" \t", arg_start);
}
auto arg = ctx.line.substr(arg_start,
ctx.line.size() - 1 - arg_start);
args.push_back(arg);
}
/**
* throw ScriptParseError for the current file/linenumber with
* error message and context line.
*/
void ScriptParse::parse_error(const std::string& line,
const std::string& error)
{
throw ScriptParseError(_path, _linenumber, line, error);
}
}
| 34.992665 | 80 | 0.506778 | pekdon |
444e4220ba110bea84070c9cd27bfccd14893eca | 139 | hpp | C++ | bot/includes/common.hpp | Antip003/irc | 973c4e1ee3d231c6aca1a434a735f236d4d55e77 | [
"MIT"
] | 1 | 2021-11-29T21:41:10.000Z | 2021-11-29T21:41:10.000Z | bot/includes/common.hpp | Antip003/irc | 973c4e1ee3d231c6aca1a434a735f236d4d55e77 | [
"MIT"
] | null | null | null | bot/includes/common.hpp | Antip003/irc | 973c4e1ee3d231c6aca1a434a735f236d4d55e77 | [
"MIT"
] | null | null | null | #ifndef COMMON_HPP
#define COMMON_HPP
#define BOTNAME "ircbot"
#define VERSION "0.1.7dev"
#define PREFIX '!'
#define CRLF "\r\n"
#endif
| 13.9 | 26 | 0.71223 | Antip003 |
444e46e23980a178cd86346f95b53120fe1db592 | 2,403 | cpp | C++ | src/Lego_I2C.cpp | cednik/LegoBTservoExpander | 78587d51ea2f9924a8df814656717fd4fc0bfca0 | [
"MIT"
] | null | null | null | src/Lego_I2C.cpp | cednik/LegoBTservoExpander | 78587d51ea2f9924a8df814656717fd4fc0bfca0 | [
"MIT"
] | null | null | null | src/Lego_I2C.cpp | cednik/LegoBTservoExpander | 78587d51ea2f9924a8df814656717fd4fc0bfca0 | [
"MIT"
] | null | null | null | #include "Lego_I2C.hpp"
#include <esp_log.h>
#define TAG "Lego_I2C"
LegoI2C::LegoI2C(i2c_port_t i2c)
: m_i2c(i2c),
m_msg_cnt(0),
m_tx_mutex(),
m_rx_mutex(),
m_rx_buff(),
m_callback()
{}
bool LegoI2C::install(addr_t addr, gpio_num_t sda, gpio_num_t scl, gpio_pullup_t pullup_en) {
i2c_config_t i2c_config;
i2c_config.sda_io_num = sda;
i2c_config.scl_io_num = scl;
i2c_config.sda_pullup_en = pullup_en;
i2c_config.scl_pullup_en = pullup_en;
i2c_config.mode = I2C_MODE_SLAVE;
i2c_config.slave.addr_10bit_en = I2C_ADDR_BIT_7;
i2c_config.slave.slave_addr = addr;
ESP_ERROR_CHECK(i2c_param_config(m_i2c, &i2c_config));
ESP_ERROR_CHECK(i2c_driver_install(m_i2c, i2c_config.mode, 128, 128, 0));
xTaskCreate(&LegoI2C::process_trampoline, "LegoI2C_loop", 4096, this, 2, NULL);
return true;
}
void LegoI2C::process() {
uint8_t buffer = 0;
int64_t last_read = esp_timer_get_time();
write_cnt();
for (;;) {
int size = i2c_slave_read_buffer(m_i2c, &buffer, 1, 1000 / portTICK_RATE_MS);
if (size == ESP_FAIL) {
ESP_LOGE(TAG, "I2C reading failed!");
} else if (size > 0) {
int64_t t = esp_timer_get_time();
if ((t - last_read) > 3000) {
write_cnt();
}
last_read = t;
m_rx_mutex.lock();
m_rx_buff.push(buffer);
m_rx_mutex.unlock();
if (m_callback)
m_callback(*this);
}
}
}
void LegoI2C::register_callback(callback_t callback) {
m_callback = callback;
}
size_t LegoI2C::available() {
std::lock_guard<std::mutex> guard(m_rx_mutex);
return m_rx_buff.size();
}
uint8_t LegoI2C::read() {
std::lock_guard<std::mutex> guard(m_rx_mutex);
if (m_rx_buff.empty())
return 0;
uint8_t v = m_rx_buff.front();
m_rx_buff.pop();
return v;
}
size_t LegoI2C::write(uint8_t v) {
return write(&v, 1);
}
size_t LegoI2C::write(uint8_t* data, size_t size) {
std::lock_guard<std::mutex> guard(m_tx_mutex);
return i2c_slave_write_buffer(m_i2c, data, size, 1000 / portTICK_RATE_MS);
}
void LegoI2C::write_cnt() {
write(m_msg_cnt++);
}
void LegoI2C::process_trampoline(void* cookie) {
((LegoI2C*)cookie)->process();
}
| 27.62069 | 94 | 0.611735 | cednik |
444ebc72faf7c34380a3a02f8182fd802d2daaff | 27,444 | cpp | C++ | inference-engine/src/preprocessing/cpu_x86_avx512/ie_preprocess_gapi_kernels_avx512.cpp | ermubuzhiming/openvino | 3a21c99b488b449bdfd2c2ba45d956448e7cfe25 | [
"Apache-2.0"
] | 1 | 2021-01-17T03:24:52.000Z | 2021-01-17T03:24:52.000Z | inference-engine/src/preprocessing/cpu_x86_avx512/ie_preprocess_gapi_kernels_avx512.cpp | ermubuzhiming/openvino | 3a21c99b488b449bdfd2c2ba45d956448e7cfe25 | [
"Apache-2.0"
] | null | null | null | inference-engine/src/preprocessing/cpu_x86_avx512/ie_preprocess_gapi_kernels_avx512.cpp | ermubuzhiming/openvino | 3a21c99b488b449bdfd2c2ba45d956448e7cfe25 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2019-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <algorithm>
#include <utility>
#include "ie_preprocess_gapi_kernels_avx512.hpp"
#include <immintrin.h>
#ifdef CV_AVX512_SKX
#undef CV_AVX512_SKX
#endif
#define CV_AVX512_SKX 1
#define CV_CPU_HAS_SUPPORT_SSE2 1
#ifdef CV_SIMD512
#undef CV_SIMD512
#endif
#define CV_SIMD512 1
#include "opencv_hal_intrin.hpp"
#include "ie_preprocess_gapi_kernels_simd_impl.hpp"
using namespace cv;
#if defined __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif
namespace InferenceEngine {
namespace gapi {
namespace kernels {
namespace avx512 {
void mergeRow_8UC2(const uint8_t in0[], const uint8_t in1[],
uint8_t out[], int length) {
mergeRow_8UC2_Impl(in0, in1, out, length);
}
void mergeRow_8UC3(const uint8_t in0[], const uint8_t in1[],
const uint8_t in2[], uint8_t out[], int length) {
mergeRow_8UC3_Impl(in0, in1, in2, out, length);
}
void mergeRow_8UC4(const uint8_t in0[], const uint8_t in1[], const uint8_t in2[],
const uint8_t in3[], uint8_t out[], int length) {
mergeRow_8UC4_Impl(in0, in1, in2, in3, out, length);
}
void mergeRow_32FC2(const float in0[], const float in1[],
float out[], int length) {
mergeRow_32FC2_Impl(in0, in1, out, length);
}
void mergeRow_32FC3(const float in0[], const float in1[], const float in2[],
float out[], int length) {
mergeRow_32FC3_Impl(in0, in1, in2, out, length);
}
void mergeRow_32FC4(const float in0[], const float in1[],
const float in2[], const float in3[],
float out[], int length) {
mergeRow_32FC4_Impl(in0, in1, in2, in3, out, length);
}
void splitRow_8UC2(const uint8_t in[], uint8_t out0[],
uint8_t out1[], int length) {
splitRow_8UC2_Impl(in, out0, out1, length);
}
void splitRow_8UC3(const uint8_t in[], uint8_t out0[],
uint8_t out1[], uint8_t out2[], int length) {
splitRow_8UC3_Impl(in, out0, out1, out2, length);
}
void splitRow_8UC4(const uint8_t in[], uint8_t out0[], uint8_t out1[],
uint8_t out2[], uint8_t out3[], int length) {
splitRow_8UC4_Impl(in, out0, out1, out2, out3, length);
}
void splitRow_32FC2(const float in[], float out0[], float out1[], int length) {
splitRow_32FC2_Impl(in, out0, out1, length);
}
void splitRow_32FC3(const float in[], float out0[], float out1[],
float out2[], int length) {
splitRow_32FC3_Impl(in, out0, out1, out2, length);
}
void splitRow_32FC4(const float in[], float out0[], float out1[],
float out2[], float out3[], int length) {
splitRow_32FC4_Impl(in, out0, out1, out2, out3, length);
}
void calculate_nv12_to_rgb(const uchar **srcY,
const uchar *srcUV,
uchar **dstRGBx,
int width) {
calculate_nv12_to_rgb_impl(srcY, srcUV, dstRGBx, width);
}
void calculate_i420_to_rgb(const uchar **srcY,
const uchar *srcU,
const uchar *srcV,
uchar **dstRGBx,
int width) {
calculate_i420_to_rgb_impl(srcY, srcU, srcV, dstRGBx, width);
}
void calcRowArea_8U(uchar dst[], const uchar *src[], const Size& inSz,
const Size& outSz, Q0_16 yalpha, const MapperUnit8U &ymap,
int xmaxdf, const short xindex[], const Q0_16 xalpha[],
Q8_8 vbuf[]) {
calcRowArea_impl(dst, src, inSz, outSz, yalpha, ymap, xmaxdf, xindex, xalpha, vbuf);
}
void calcRowArea_32F(float dst[], const float *src[], const Size& inSz,
const Size& outSz, float yalpha, const MapperUnit32F& ymap,
int xmaxdf, const int xindex[], const float xalpha[],
float vbuf[]) {
calcRowArea_impl(dst, src, inSz, outSz, yalpha, ymap, xmaxdf, xindex, xalpha, vbuf);
}
static inline void verticalPass_lpi4_8U(const uint8_t *src0[], const uint8_t *src1[],
uint8_t tmp[], v_int16& b0, v_int16& b1,
v_int16& b2, v_int16& b3, v_uint8& shuf_mask,
int half_nlanes, int width) {
v_uint32 permute_idxs1 = v_set_s32(23, 21, 7, 5, 22, 20, 6, 4, 19, 17, 3, 1, 18, 16, 2, 0);
v_uint32 permute_idxs2 = v_set_s32(31, 29, 15, 13, 30, 28, 14, 12, 27, 25, 11, 9, 26, 24, 10, 8);
for (int w = 0; w < width; ) {
for (; w <= width - half_nlanes; w += half_nlanes) {
v_int16 val0_0 = v_load_ccache_expand(&src0[0][w]);
v_int16 val0_1 = v_load_ccache_expand(&src0[1][w]);
v_int16 val0_2 = v_load_ccache_expand(&src0[2][w]);
v_int16 val0_3 = v_load_ccache_expand(&src0[3][w]);
v_int16 val1_0 = v_load_ccache_expand(&src1[0][w]);
v_int16 val1_1 = v_load_ccache_expand(&src1[1][w]);
v_int16 val1_2 = v_load_ccache_expand(&src1[2][w]);
v_int16 val1_3 = v_load_ccache_expand(&src1[3][w]);
v_int16 t0 = v_mulhrs(v_sub_wrap(val0_0, val1_0), b0);
v_int16 t1 = v_mulhrs(v_sub_wrap(val0_1, val1_1), b1);
v_int16 t2 = v_mulhrs(v_sub_wrap(val0_2, val1_2), b2);
v_int16 t3 = v_mulhrs(v_sub_wrap(val0_3, val1_3), b3);
v_int16 r0 = v_add_wrap(val1_0, t0);
v_int16 r1 = v_add_wrap(val1_1, t1);
v_int16 r2 = v_add_wrap(val1_2, t2);
v_int16 r3 = v_add_wrap(val1_3, t3);
v_uint8 q0 = v_packus(r0, r1);
v_uint8 q1 = v_packus(r2, r3);
#if 1
v_uint8 q2 = v_permutex2_s32(q0, q1, permute_idxs1);
v_uint8 q3 = v_permutex2_s32(q0, q1, permute_idxs2);
v_uint8 q4 = v_shuffle_s8(q2, shuf_mask);
v_uint8 q5 = v_shuffle_s8(q3, shuf_mask);
//Second variant of decompose. It'll be usefull in the future.
#else
v_uint8 q2 = v_mblend_shiftleft(q0, q1);
v_uint8 q3 = v_mblend_shiftright(q0, q1);
v_uint8 mask1 = v_setr_s8(0, 8, 4, 12, 1, 9, 5, 13,
2, 10, 6, 14, 3, 11, 7, 15,
0, 8, 4, 12, 1, 9, 5, 13,
2, 10, 6, 14, 3, 11, 7, 15,
0, 8, 4, 12, 1, 9, 5, 13,
2, 10, 6, 14, 3, 11, 7, 15,
0, 8, 4, 12, 1, 9, 5, 13,
2, 10, 6, 14, 3, 11, 7, 15);
v_uint8 q4 = v_shuffle_s8(q2, mask1);
v_uint8 q5 = v_shuffle_s8(q3, mask1);
v_uint64 idx1 = v_set_s64(11, 10, 3, 2, 9, 8, 1, 0);
v_uint64 idx2 = v_set_s64(15, 14, 7, 6, 13, 12, 5, 4);
v_uint8 q6 = v_permutex2_s64(q4, q5, permute_idxs1);
v_uint8 q7 = v_permutex2_s64(q4, q5, permute_idxs2);
#endif
vx_store(&tmp[4 * w + 0], q4);
vx_store(&tmp[4 * w + 2 * half_nlanes], q5);
}
if (w < width) {
w = width - half_nlanes;
}
}
}
static inline void main_computation_horizontalPass_lpi4(const v_uint8& val_0,
const v_uint8& val_1,
const v_uint8& val_2,
const v_uint8& val_3,
const v_int16& a10,
const v_int16& a32,
const v_int16& a54,
const v_int16& a76,
v_uint8& shuf_mask1,
v_uint8& shuf_mask2,
v_uint32& idxs1,
v_uint32& idxs2,
v_uint8& res1, v_uint8& res2) {
v_int16 val0_0 = v_reinterpret_as_s16(v_expand_low(val_0));
v_int16 val0_1 = v_reinterpret_as_s16(v_expand_low(val_1));
v_int16 val0_2 = v_reinterpret_as_s16(v_expand_low(val_2));
v_int16 val0_3 = v_reinterpret_as_s16(v_expand_low(val_3));
v_int16 val1_0 = v_reinterpret_as_s16(v_expand_high(val_0));
v_int16 val1_1 = v_reinterpret_as_s16(v_expand_high(val_1));
v_int16 val1_2 = v_reinterpret_as_s16(v_expand_high(val_2));
v_int16 val1_3 = v_reinterpret_as_s16(v_expand_high(val_3));
v_int16 t0 = v_mulhrs(v_sub_wrap(val0_0, val1_0), a10);
v_int16 t1 = v_mulhrs(v_sub_wrap(val0_1, val1_1), a32);
v_int16 t2 = v_mulhrs(v_sub_wrap(val0_2, val1_2), a54);
v_int16 t3 = v_mulhrs(v_sub_wrap(val0_3, val1_3), a76);
v_int16 r0 = v_add_wrap(val1_0, t0);
v_int16 r1 = v_add_wrap(val1_1, t1);
v_int16 r2 = v_add_wrap(val1_2, t2);
v_int16 r3 = v_add_wrap(val1_3, t3);
v_uint8 q0 = v_packus(r0, r1);
v_uint8 q1 = v_packus(r2, r3);
v_uint8 q2 = v_shuffle_s8(q0, shuf_mask1);
v_uint8 q3 = v_shuffle_s8(q1, shuf_mask1);
#if 1
v_uint8 q4 = v_permutex2_s32(q2, q3, idxs1);
v_uint8 q5 = v_permutex2_s32(q2, q3, idxs2);
res1 = v_shuffle_s8(q4, shuf_mask2);
res2 = v_shuffle_s8(q5, shuf_mask2);
//Second variant of decompose. It'll be usefull in the future.
#else
v_uint8 q4 = v_mask_blend_shiftleft<0xCCCCCCCC /*0b11001100110011001100110011001100*/, 4>(q2, q3);
v_uint8 q5 = v_mask_blend_shiftright<0xCCCCCCCC /*0b11001100110011001100110011001100*/, 4>(q2, q3);
v_int32 idx = v_set_s32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0);
v_uint8 q6 = v_permute32(idx, q4);
v_uint8 q7 = v_permute32(idx, q5);
v_uint8 mask2 = v_setr_s8(0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15);
v_uint8 q8 = v_shuffle_s8(q6, mask2);
v_uint8 q9 = v_shuffle_s8(q7, mask2);
#endif
}
static inline void horizontalPass_lpi4_U8C1(const short clone[], const short mapsx[],
uint8_t tmp[], uint8_t *dst[],
v_uint8& shuf_mask1,
int width, int half_nlanes) {
v_uint8 shuf_mask2 = v_setr_s8(0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15);
v_uint32 permute_idxs1 = v_set_s32(15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0);
v_uint32 permute_idxs2 = v_set_s32(29, 25, 21, 17, 13, 9, 5, 1, 28, 24, 20, 16, 12, 8, 4, 0);
v_uint32 permute_idxs3 = v_set_s32(31, 27, 23, 19, 15, 11, 7, 3, 30, 26, 22, 18, 14, 10, 6, 2);
v_uint8 val_0, val_1, val_2, val_3, res1, res2;
const int shift = half_nlanes / 4;
for (int x = 0; x < width; ) {
for (; x <= width - half_nlanes; x += half_nlanes) {
v_int16 a10 = vx_load(&clone[4 * x]);
v_int16 a32 = vx_load(&clone[4 * (x + 8)]);
v_int16 a54 = vx_load(&clone[4 * (x + 16)]);
v_int16 a76 = vx_load(&clone[4 * (x + 24)]);
v_set(val_0, val_1, val_2, val_3, tmp, mapsx, x, shift);
val_0 = v_permute32(val_0, permute_idxs1);
val_1 = v_permute32(val_1, permute_idxs1);
val_2 = v_permute32(val_2, permute_idxs1);
val_3 = v_permute32(val_3, permute_idxs1);
main_computation_horizontalPass_lpi4(val_0, val_1, val_2, val_3,
a10, a32, a54, a76,
shuf_mask1, shuf_mask2,
permute_idxs2, permute_idxs3,
res1, res2);
v_store_low(&dst[0][x], res1);
v_store_high(&dst[1][x], res1);
v_store_low(&dst[2][x], res2);
v_store_high(&dst[3][x], res2);
}
if (x < width) {
x = width - half_nlanes;
}
}
}
static inline void verticalPass_anylpi_8U(const uint8_t* src0[], const uint8_t* src1[],
uint8_t tmp[], const int& beta0, const int& half_nlanes,
const int& l, const int& length1, const int& length2) {
for (int w = 0; w < length2; ) {
for (; w <= length1 - half_nlanes; w += half_nlanes) {
v_int16 s0 = v_reinterpret_as_s16(vx_load_expand(&src0[l][w]));
v_int16 s1 = v_reinterpret_as_s16(vx_load_expand(&src1[l][w]));
v_int16 t = v_mulhrs(s0 - s1, beta0) + s1;
v_pack_u_store(tmp + w, t);
}
if (w < length1) {
w = length1 - half_nlanes;
}
}
}
static inline void horizontalPass_anylpi_8U(const short alpha[], const short mapsx[],
uint8_t* dst[], const uchar tmp[], const int& l,
const int& half_nlanes, const int& length) {
for (int x = 0; x < length; ) {
for (; x <= length - half_nlanes; x += half_nlanes) {
v_int16 a0 = vx_load(&alpha[x]); // as signed Q1.1.14
v_int16 sx = vx_load(&mapsx[x]); // as integer (int16)
v_uint8 t = v_gather_pairs(tmp, sx);
v_int16 t0, t1;
v_deinterleave_expand(t, t0, t1); // tmp pixels as int16
v_int16 d = v_mulhrs(t0 - t1, a0) + t1;
v_pack_u_store(&dst[l][x], d);
}
if (x < length) {
x = length - half_nlanes;
}
}
}
// 8UC1 Resize (bi-linear)
void calcRowLinear_8UC1( uint8_t* dst[],
const uint8_t* src0[],
const uint8_t* src1[],
const short alpha[],
const short clone[], // 4 clones of alpha
const short mapsx[],
const short beta[],
uint8_t tmp[],
const Size& inSz,
const Size& outSz,
int lpi) {
bool xRatioEq = inSz.width == outSz.width;
bool yRatioEq = inSz.height == outSz.height;
constexpr int nlanes = v_uint8::nlanes;
constexpr int half_nlanes = (nlanes / 2);
if (!xRatioEq && !yRatioEq) {
if (4 == lpi) {
// vertical pass
GAPI_DbgAssert(inSz.width >= half_nlanes);
v_int16 b0 = vx_setall_s16(beta[0]);
v_int16 b1 = vx_setall_s16(beta[1]);
v_int16 b2 = vx_setall_s16(beta[2]);
v_int16 b3 = vx_setall_s16(beta[3]);
v_uint8 shuf_mask1 = v_setr_s8(0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15);
verticalPass_lpi4_8U(src0, src1, tmp, b0, b1, b2, b3, shuf_mask1,
half_nlanes, inSz.width);
// horizontal pass
GAPI_DbgAssert(outSz.width >= half_nlanes);
horizontalPass_lpi4_U8C1(clone, mapsx, tmp, dst, shuf_mask1,
outSz.width, half_nlanes);
} else { // if any lpi
int inLength = inSz.width;
int outLength = outSz.width;
for (int l = 0; l < lpi; ++l) {
short beta0 = beta[l];
// vertical pass
GAPI_DbgAssert(inSz.width >= half_nlanes);
verticalPass_anylpi_8U(src0, src1, tmp, beta0, half_nlanes, l, inLength, inLength);
// horizontal pass
GAPI_DbgAssert(outSz.width >= half_nlanes);
horizontalPass_anylpi_8U(alpha, mapsx, dst, tmp, l, half_nlanes, outLength);
}
} // if lpi == 4
} else if (!xRatioEq) {
GAPI_DbgAssert(yRatioEq);
if (4 == lpi) {
// vertical pass
GAPI_DbgAssert(inSz.width >= nlanes);
for (int w = 0; w < inSz.width; ) {
for (; w <= inSz.width - nlanes; w += nlanes) {
v_uint8 s0, s1, s2, s3;
s0 = vx_load(&src0[0][w]);
s1 = vx_load(&src0[1][w]);
s2 = vx_load(&src0[2][w]);
s3 = vx_load(&src0[3][w]);
v_store_interleave(&tmp[4 * w], s0, s1, s2, s3);
}
if (w < inSz.width) {
w = inSz.width - nlanes;
}
}
// horizontal pass
v_uint8 shuf_mask1 = v_setr_s8(0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15);
horizontalPass_lpi4_U8C1(clone, mapsx, tmp, dst, shuf_mask1,
outSz.width, half_nlanes);
} else { // any LPI
for (int l = 0; l < lpi; ++l) {
const uchar *src = src0[l];
// horizontal pass
GAPI_DbgAssert(outSz.width >= half_nlanes);
horizontalPass_anylpi_8U(alpha, mapsx, dst, src, l, half_nlanes, outSz.width);
}
}
} else if (!yRatioEq) {
GAPI_DbgAssert(xRatioEq);
int inLength = inSz.width;
int outLength = outSz.width;
for (int l = 0; l < lpi; ++l) {
short beta0 = beta[l];
// vertical pass
GAPI_DbgAssert(inSz.width >= half_nlanes);
verticalPass_anylpi_8U(src0, src1, dst[l], beta0, half_nlanes, l,
inLength, outLength);
}
} else {
GAPI_DbgAssert(xRatioEq && yRatioEq);
int length = inSz.width;
for (int l = 0; l < lpi; ++l) {
memcpy(dst[l], src0[l], length);
}
}
}
// Resize (bi-linear, 8U, generic number of channels)
template<int chanNum>
static inline void calcRowLinear_8UC_Impl(std::array<std::array<uint8_t*, 4>, chanNum> &dst,
const uint8_t *src0[],
const uint8_t *src1[],
const short alpha[],
const short clone[], // 4 clones of alpha
const short mapsx[],
const short beta[],
uint8_t tmp[],
const Size &inSz,
const Size &outSz,
int lpi) {
constexpr int half_nlanes = (v_uint8::nlanes / 2);
constexpr int shift = (half_nlanes / 4);
if (4 == lpi) {
GAPI_DbgAssert(inSz.width >= half_nlanes);
v_uint8 shuf_mask1 = v_setr_s8(0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15,
0, 4, 8, 12, 1, 5, 9, 13,
2, 6, 10, 14, 3, 7, 11, 15);
// vertical pass
v_int16 b0 = vx_setall_s16(beta[0]);
v_int16 b1 = vx_setall_s16(beta[1]);
v_int16 b2 = vx_setall_s16(beta[2]);
v_int16 b3 = vx_setall_s16(beta[3]);
verticalPass_lpi4_8U(src0, src1, tmp, b0, b1, b2, b3,
shuf_mask1, half_nlanes, inSz.width*chanNum);
// horizontal pass
v_uint8 val_0, val_1, val_2, val_3, res1, res2;
v_uint8 shuf_mask2 = v_setr_s8(0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15,
0, 1, 4, 5, 8, 9, 12, 13,
2, 3, 6, 7, 10, 11, 14, 15);
v_uint32 idxs3 = v_set_s32(29, 25, 21, 17, 13, 9, 5, 1, 28, 24, 20, 16, 12, 8, 4, 0);
v_uint32 idxs4 = v_set_s32(31, 27, 23, 19, 15, 11, 7, 3, 30, 26, 22, 18, 14, 10, 6, 2);
GAPI_DbgAssert(outSz.width >= half_nlanes);
for (int x = 0; x < outSz.width; ) {
for (; x <= outSz.width - half_nlanes && x >= 0; x += half_nlanes) {
v_int16 a10 = vx_load(&clone[4 * x]);
v_int16 a32 = vx_load(&clone[4 * (x + 8)]);
v_int16 a54 = vx_load(&clone[4 * (x + 16)]);
v_int16 a76 = vx_load(&clone[4 * (x + 24)]);
for (int c = 0; c < chanNum; ++c) {
v_gather_channel(val_0, tmp, mapsx, chanNum, c, x, 0);
v_gather_channel(val_1, tmp, mapsx, chanNum, c, x, shift);
v_gather_channel(val_2, tmp, mapsx, chanNum, c, x, shift * 2);
v_gather_channel(val_3, tmp, mapsx, chanNum, c, x, shift * 3);
main_computation_horizontalPass_lpi4(val_0, val_1, val_2, val_3,
a10, a32, a54, a76,
shuf_mask1, shuf_mask2,
idxs3, idxs4,
res1, res2);
v_store_low(&dst[c][0][x], res1);
v_store_high(&dst[c][1][x], res1);
v_store_low(&dst[c][2][x], res2);
v_store_high(&dst[c][3][x], res2);
}
}
if (x < outSz.width) {
x = outSz.width - half_nlanes;
}
}
} else { // if any lpi
for (int l = 0; l < lpi; ++l) {
short beta0 = beta[l];
// vertical pass
GAPI_DbgAssert(inSz.width*chanNum >= half_nlanes);
verticalPass_anylpi_8U(src0, src1, tmp, beta0, half_nlanes, l,
inSz.width*chanNum, inSz.width*chanNum);
// horizontal pass
GAPI_DbgAssert(outSz.width >= half_nlanes);
for (int x = 0; x < outSz.width; ) {
for (; x <= outSz.width - half_nlanes && x >= 0; x += half_nlanes) {
for (int c = 0; c < chanNum; ++c) {
v_int16 a0 = vx_load(&alpha[x]); // as signed Q1.1.14
v_int16 sx = vx_load(&mapsx[x]); // as integer (int16)
v_int16 t0 = v_gather_chan<chanNum>(tmp, sx, c, 0);
v_int16 t1 = v_gather_chan<chanNum>(tmp, sx, c, 1);
v_int16 d = v_mulhrs(t0 - t1, a0) + t1;
v_pack_u_store(&dst[c][l][x], d);
}
}
if (x < outSz.width) {
x = outSz.width - half_nlanes;
}
}
}
}
}
// Resize (bi-linear, 8UC3)
void calcRowLinear_8U(C3, std::array<std::array<uint8_t*, 4>, 3> &dst,
const uint8_t *src0[],
const uint8_t *src1[],
const short alpha[],
const short clone[], // 4 clones of alpha
const short mapsx[],
const short beta[],
uint8_t tmp[],
const Size &inSz,
const Size &outSz,
int lpi) {
constexpr const int chanNum = 3;
calcRowLinear_8UC_Impl<chanNum>(dst, src0, src1, alpha, clone, mapsx, beta, tmp, inSz, outSz, lpi);
}
// Resize (bi-linear, 8UC4)
void calcRowLinear_8U(C4, std::array<std::array<uint8_t*, 4>, 4> &dst,
const uint8_t *src0[],
const uint8_t *src1[],
const short alpha[],
const short clone[], // 4 clones of alpha
const short mapsx[],
const short beta[],
uint8_t tmp[],
const Size &inSz,
const Size &outSz,
int lpi) {
constexpr const int chanNum = 4;
calcRowLinear_8UC_Impl<chanNum>(dst, src0, src1, alpha, clone, mapsx, beta, tmp, inSz, outSz, lpi);
}
void copyRow_8U(const uint8_t in[], uint8_t out[], int length) {
copyRow_8U_impl(in, out, length);
}
void copyRow_32F(const float in[], float out[], int length) {
copyRow_32F_impl(in, out, length);
}
void calcRowLinear_32F(float *dst[],
const float *src0[],
const float *src1[],
const float alpha[],
const int mapsx[],
const float beta[],
const Size& inSz,
const Size& outSz,
int lpi) {
calcRowLinear_32FC1(dst, src0, src1, alpha, mapsx, beta, inSz, outSz, lpi);
}
} // namespace avx512
} // namespace kernels
} // namespace gapi
} // namespace InferenceEngine
| 41.331325 | 103 | 0.463854 | ermubuzhiming |
4453c48b83a90a85306e765297fa4c42d14dff1c | 4,686 | hpp | C++ | em_unet/src/PyGreentea/evaluation/src_cython/zi/bits/cerrno.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 10 | 2018-09-13T17:37:22.000Z | 2020-05-08T16:20:42.000Z | em_unet/src/PyGreentea/evaluation/src_cython/zi/bits/cerrno.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 1 | 2018-12-02T14:17:39.000Z | 2018-12-02T20:59:26.000Z | em_unet/src/PyGreentea/evaluation/src_cython/zi/bits/cerrno.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 2 | 2019-03-03T12:06:10.000Z | 2020-04-12T13:23:02.000Z | //
// Copyright (C) 2010 Aleksandar Zlateski <zlateski@mit.edu>
// ----------------------------------------------------------
//
// 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/>.
//
#ifndef ZI_BITS_CERRNO_HPP
#define ZI_BITS_CERRNO_HPP 1
#
#include <cerror>
#
#ifndef EAFNOSUPPORT
# define EAFNOSUPPORT 9901
#endif
#
#ifndef EADDRINUSE
# define EADDRINUSE 9902
#endif
#
#ifndef EADDRNOTAVAIL
# define EADDRNOTAVAIL 9903
#endif
#
#ifndef EISCONN
# define EISCONN 9904
#endif
#
#ifndef EBADMSG
# define EBADMSG 9905
#endif
#
#ifndef ECONNABORTED
# define ECONNABORTED 9906
#endif
#
#ifndef EALREADY
# define EALREADY 9907
#endif
#
#ifndef ECONNREFUSED
# define ECONNREFUSED 9908
#endif
#
#ifndef ECONNRESET
# define ECONNRESET 9909
#endif
#
#ifndef EDESTADDRREQ
# define EDESTADDRREQ 9910
#endif
#
#ifndef EHOSTUNREACH
# define EHOSTUNREACH 9911
#endif
#
#ifndef EIDRM
# define EIDRM 9912
#endif
#
#ifndef EMSGSIZE
# define EMSGSIZE 9913
#endif
#
#ifndef ENETDOWN
# define ENETDOWN 9914
#endif
#
#ifndef ENETRESET
# define ENETRESET 9915
#endif
#
#ifndef ENETUNREACH
# define ENETUNREACH 9916
#endif
#
#ifndef ENOBUFS
# define ENOBUFS 9917
#endif
#
#ifndef ENOLINK
# define ENOLINK 9918
#endif
#
#ifndef ENODATA
# define ENODATA 9919
#endif
#
#ifndef ENOMSG
# define ENOMSG 9920
#endif
#
#ifndef ENOPROTOOPT
# define ENOPROTOOPT 9921
#endif
#
#ifndef ENOSR
# define ENOSR 9922
#endif
#
#ifndef ENOTSOCK
# define ENOTSOCK 9923
#endif
#
#ifndef ENOSTR
# define ENOSTR 9924
#endif
#
#ifndef ENOTCONN
# define ENOTCONN 9925
#endif
#
#ifndef ENOTSUP
# define ENOTSUP 9926
#endif
#
#ifndef ECANCELED
# define ECANCELED 9927
#endif
#
#ifndef EINPROGRESS
# define EINPROGRESS 9928
#endif
#
#ifndef EOPNOTSUPP
# define EOPNOTSUPP 9929
#endif
#
#ifndef EWOULDBLOCK
# define EWOULDBLOCK 9930
#endif
#
#ifndef EOWNERDEAD
# define EOWNERDEAD 9931
#endif
#
#ifndef EPROTO
# define EPROTO 9932
#endif
#
#ifndef EPROTONOSUPPORT
# define EPROTONOSUPPORT 9933
#endif
#
#ifndef ENOTRECOVERABLE
# define ENOTRECOVERABLE 9934
#endif
#
#ifndef ETIME
# define ETIME 9935
#endif
#
#ifndef ETXTBSY
# define ETXTBSY 9936
#endif
#
#ifndef ETIMEDOUT
# define ETIMEDOUT 9938
#endif
#
#ifndef ELOOP
# define ELOOP 9939
#endif
#
#ifndef EOVERFLOW
# define EOVERFLOW 9940
#endif
#
#ifndef EPROTOTYPE
# define EPROTOTYPE 9941
#endif
#
#ifndef ENOSYS
# define ENOSYS 9942
#endif
#
#ifndef EINVAL
# define EINVAL 9943
#endif
#
#ifndef ERANGE
# define ERANGE 9944
#endif
#
#ifndef EILSEQ
# define EILSEQ 9945
#endif
#
#ifndef E2BIG
# define E2BIG 9946
#endif
#
#ifndef EDOM
# define EDOM 9947
#endif
#
#ifndef EFAULT
# define EFAULT 9948
#endif
#
#ifndef EBADF
# define EBADF 9949
#endif
#
#ifndef EPIPE
# define EPIPE 9950
#endif
#
#ifndef EXDEV
# define EXDEV 9951
#endif
#
#ifndef EBUSY
# define EBUSY 9952
#endif
#
#ifndef ENOTEMPTY
# define ENOTEMPTY 9953
#endif
#
#ifndef ENOEXEC
# define ENOEXEC 9954
#endif
#
#ifndef EEXIST
# define EEXIST 9955
#endif
#
#ifndef EFBIG
# define EFBIG 9956
#endif
#
#ifndef ENAMETOOLONG
# define ENAMETOOLONG 9957
#endif
#
#ifndef ENOTTY
# define ENOTTY 9958
#endif
#
#ifndef EINTR
# define EINTR 9959
#endif
#
#ifndef ESPIPE
# define ESPIPE 9960
#endif
#
#ifndef EIO
# define EIO 9961
#endif
#
#ifndef EISDIR
# define EISDIR 9962
#endif
#
#ifndef ECHILD
# define ECHILD 9963
#endif
#
#ifndef ENOLCK
# define ENOLCK 9964
#endif
#
#ifndef ENOSPC
# define ENOSPC 9965
#endif
#
#ifndef ENXIO
# define ENXIO 9966
#endif
#
#ifndef ENODEV
# define ENODEV 9967
#endif
#
#ifndef ENOENT
# define ENOENT 9968
#endif
#
#ifndef ESRCH
# define ESRCH 9969
#endif
#
#ifndef ENOTDIR
# define ENOTDIR 9970
#endif
#
#ifndef ENOMEM
# define ENOMEM 9971
#endif
#
#ifndef EPERM
# define EPERM 9972
#endif
#
#ifndef EACCES
# define EACCES 9973
#endif
#
#ifndef EROFS
# define EROFS 9974
#endif
#
#ifndef EDEADLK
# define EDEADLK 9975
#endif
#
#ifndef EAGAIN
# define EAGAIN 9976
#endif
#
#ifndef ENFILE
# define ENFILE 9977
#endif
#
#ifndef EMFILE
# define EMFILE 9978
#endif
#
#ifndef EMLINK
# define EMLINK 9979
#endif
#
#endif
| 13.905045 | 72 | 0.726633 | VCG |
4454aa239fe731d0049377a278a1c23b00743b16 | 1,113 | hpp | C++ | Boss/Mod/PeerComplaintsDesk/Exempter.hpp | raphjaph/clboss | ceeb856ec72a7c7d743305e3b9a03a0a3ff512e6 | [
"MIT"
] | 108 | 2020-10-01T17:12:40.000Z | 2022-03-30T09:18:03.000Z | Boss/Mod/PeerComplaintsDesk/Exempter.hpp | raphjaph/clboss | ceeb856ec72a7c7d743305e3b9a03a0a3ff512e6 | [
"MIT"
] | 94 | 2020-10-03T13:40:30.000Z | 2022-03-30T09:18:00.000Z | Boss/Mod/PeerComplaintsDesk/Exempter.hpp | raphjaph/clboss | ceeb856ec72a7c7d743305e3b9a03a0a3ff512e6 | [
"MIT"
] | 17 | 2020-10-29T13:27:59.000Z | 2022-03-18T13:05:03.000Z | #ifndef BOSS_MOD_PEERCOMPLAINTSDESK_EXEMPTER_HPP
#define BOSS_MOD_PEERCOMPLAINTSDESK_EXEMPTER_HPP
#include<map>
#include<memory>
#include<string>
namespace Boss { namespace Mod { namespace PeerComplaintsDesk {
class Unmanager;
}}}
namespace Ev { template<typename a> class Io; }
namespace Ln { class NodeId; }
namespace S { class Bus; }
namespace Boss { namespace Mod { namespace PeerComplaintsDesk {
/** class Boss::Mod::PeerComplaintsDesk::Exempter
*
* @brief Provides exemptions from complaints, causing the
* complaints desk to ignore complaints about certain peers.
*/
class Exempter {
private:
class Impl;
std::unique_ptr<Impl> pimpl;
public:
Exempter() =delete;
Exempter(Exempter const&) =delete;
Exempter(Exempter&&);
~Exempter();
explicit
Exempter(S::Bus& bus, Unmanager& unmanager);
/** Boss::Mod::PeerComplaintsDesk::Exempter::get_exemptions
*
* @brief Creates a map containing reasons to ignore
* the complaints about certain peers.
*/
Ev::Io<std::map<Ln::NodeId, std::string>>
get_exemptions();
};
}}}
#endif /* !defined(BOSS_MOD_PEERCOMPLAINTSDESK_EXEMPTER_HPP) */
| 22.714286 | 63 | 0.744834 | raphjaph |
44556b00acad1137184c9a656b4d7d3ddd9b43f7 | 5,526 | cpp | C++ | networkit/cpp/dynamics/test/DynamicsGTest.cpp | clintg6/networkit | b4cba9a82436cd7ebc139c1a612f593fca9892c6 | [
"MIT"
] | null | null | null | networkit/cpp/dynamics/test/DynamicsGTest.cpp | clintg6/networkit | b4cba9a82436cd7ebc139c1a612f593fca9892c6 | [
"MIT"
] | null | null | null | networkit/cpp/dynamics/test/DynamicsGTest.cpp | clintg6/networkit | b4cba9a82436cd7ebc139c1a612f593fca9892c6 | [
"MIT"
] | null | null | null | /*
* DynamicsGTest.cpp
*
* Created on: 24.12.2013
* Author: cls
*/
#include <gtest/gtest.h>
#include "../../../include/networkit/dynamics/DGSStreamParser.hpp"
#include "../../../include/networkit/auxiliary/Log.hpp"
#include "../../../include/networkit/dynamics/GraphEvent.hpp"
#include "../../../include/networkit/dynamics/GraphUpdater.hpp"
#include "../../../include/networkit/dynamics/GraphDifference.hpp"
namespace NetworKit {
class DynamicsGTest: public testing::Test {};
TEST_F(DynamicsGTest, testDGSStreamParser) {
DGSStreamParser parser("input/example2.dgs");
auto stream = parser.getStream();
ASSERT_EQ(stream.size(),16);
ASSERT_EQ(stream[0].type,GraphEvent::NODE_ADDITION);
ASSERT_EQ(stream[1].type,GraphEvent::NODE_ADDITION);
ASSERT_EQ(stream[2].type,GraphEvent::EDGE_ADDITION);
ASSERT_EQ(stream[3].type,GraphEvent::TIME_STEP);
ASSERT_EQ(stream[4].type,GraphEvent::EDGE_WEIGHT_UPDATE);
ASSERT_EQ(stream[5].type,GraphEvent::EDGE_REMOVAL);
ASSERT_EQ(stream[6].type,GraphEvent::NODE_REMOVAL);
ASSERT_EQ(stream[7].type,GraphEvent::NODE_REMOVAL);
ASSERT_EQ(stream[8].type,GraphEvent::NODE_ADDITION);
ASSERT_EQ(stream[9].type,GraphEvent::NODE_ADDITION);
ASSERT_EQ(stream[10].type,GraphEvent::EDGE_ADDITION);
ASSERT_EQ(stream[11].type,GraphEvent::NODE_ADDITION);
ASSERT_EQ(stream[12].type,GraphEvent::EDGE_ADDITION);
ASSERT_EQ(stream[13].type,GraphEvent::NODE_ADDITION);
ASSERT_EQ(stream[14].type,GraphEvent::NODE_REMOVAL);
ASSERT_EQ(stream[15].type,GraphEvent::NODE_RESTORATION);
//apply updates
Graph G(0,true);
GraphUpdater updater(G);
updater.update(stream);
ASSERT_EQ(G.numberOfNodes(),4);
ASSERT_EQ(G.numberOfEdges(),2);
}
TEST_F(DynamicsGTest, debugDGSStreamParserOnRealGraph) {
std::string path;
std::cout << "enter .dgs file path: ";
std::cin >> path;
DGSStreamParser parser(path);
auto stream = parser.getStream();
}
TEST_F(DynamicsGTest, testGraphEventIncrement) {
Graph G(2, true, false); //undirected
Graph H(2, true, true); //directed
G.addEdge(0, 1, 3.14);
H.addEdge(0, 1, 3.14);
GraphEvent event(GraphEvent::EDGE_WEIGHT_INCREMENT, 0, 1, 2.1);
std::vector<GraphEvent> eventstream(1);
eventstream.push_back(event);
GraphUpdater Gupdater(G);
GraphUpdater Hupdater(H);
Gupdater.update(eventstream);
Hupdater.update(eventstream);
EXPECT_EQ(G.weight(0,1), 5.24);
EXPECT_EQ(H.weight(0,1), 5.24);
}
namespace {
// helper methods
std::string edits_to_string(const std::vector<GraphEvent>& events) {
std::stringstream ss;
ss << "[";
for (size_t i = 0; i < events.size(); ++i) {
ss << events[i].toString();
if (i < events.size() - 1) {
ss << ", ";
}
}
ss << "]";
return ss.str();
};
void expect_graph_equals(const Graph& G1, const Graph &G2) {
EXPECT_EQ(G1.numberOfNodes(), G2.numberOfNodes());
EXPECT_EQ(G1.numberOfEdges(), G2.numberOfEdges());
GraphDifference diff1(G1, G2);
diff1.run();
EXPECT_EQ(diff1.getNumberOfEdits(), 0);
EXPECT_TRUE(diff1.getEdits().empty()) << edits_to_string(diff1.getEdits());
GraphDifference diff2(G2, G2);
diff2.run();
EXPECT_EQ(diff2.getNumberOfEdits(), 0);
EXPECT_TRUE(diff2.getEdits().empty()) << edits_to_string(diff2.getEdits());
};
};
TEST_F(DynamicsGTest, testGraphDifference) {
Graph G1(11, false, false);
Graph G2(8, false, false);
G1.addEdge(2, 4);
G1.addEdge(2, 6);
G1.addEdge(9, 10);
G1.addEdge(4, 10);
G1.removeNode(3);
G1.removeNode(8);
G2.addEdge(3, 2);
G2.removeNode(4);
{
GraphDifference diff(G1, G2);
diff.run();
EXPECT_EQ(diff.getNumberOfEdgeRemovals(), 4) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfNodeRemovals(), 3) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfNodeRestorations(), 1) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfEdgeAdditions(), 1) << edits_to_string(diff.getEdits());
Graph H = G1;
GraphUpdater Hupdater(H);
Hupdater.update(diff.getEdits());
EXPECT_TRUE(H.hasEdge(2, 3));
expect_graph_equals(H, G2);
}
{
GraphDifference diff(G2, G1);
diff.run();
EXPECT_EQ(diff.getNumberOfEdgeAdditions(), 4) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfNodeRemovals(), 1) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfNodeAdditions(), 2) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfNodeRestorations(), 1) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfEdgeRemovals(), 1) << edits_to_string(diff.getEdits());
Graph H = G2;
GraphUpdater Hupdater(H);
Hupdater.update(diff.getEdits());
expect_graph_equals(H, G1);
}
}
TEST_F(DynamicsGTest, testGraphDifferenceDirectedWeighted) {
Graph G1(8, true, true);
Graph G2(8, true, true);
G1.addEdge(0, 1, 0.5);
G1.addEdge(1, 0, 2);
G1.addEdge(2, 3, 2.0);
G2.addEdge(1, 0, 0.5);
G2.addEdge(3, 2, 1.0);
G2.addEdge(3, 4, 2.5);
for (const auto& gs : std::vector<std::pair<Graph, Graph>>({{G1, G2}, {G2, G1}})) {
const Graph& g1 = gs.first;
const Graph& g2 = gs.second;
GraphDifference diff(g1, g2);
diff.run();
EXPECT_EQ(diff.getNumberOfEdgeRemovals(), 2) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfEdgeAdditions(), 2) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfEdgeWeightUpdates(), 1) << edits_to_string(diff.getEdits());
EXPECT_EQ(diff.getNumberOfEdits(), 5) << edits_to_string(diff.getEdits());
Graph H = g1;
GraphUpdater Hupdater(H);
Hupdater.update(diff.getEdits());
expect_graph_equals(H, g2);
}
}
} /* namespace NetworKit */
| 29.084211 | 88 | 0.709193 | clintg6 |
4457fb9e135da6ed04c0be0bba0bd885f65fc7e5 | 3,788 | hpp | C++ | backend/include/protect-eval.hpp | vkurilin/SHEEP | 2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb | [
"MIT"
] | 40 | 2018-12-03T13:01:06.000Z | 2022-02-23T13:04:12.000Z | backend/include/protect-eval.hpp | vkurilin/SHEEP | 2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb | [
"MIT"
] | 63 | 2018-09-11T14:13:31.000Z | 2020-01-14T16:12:39.000Z | backend/include/protect-eval.hpp | vkurilin/SHEEP | 2ccaef32c16efcf5dbc8eefd1dc243bed4ac2fbb | [
"MIT"
] | 7 | 2019-07-10T14:48:31.000Z | 2022-03-23T09:12:11.000Z | // This file provides a function protect_eval for calling another
// function (that might crash or call exit) within a forked process,
// allowing the calling process to continue and recover.
//
// It requires POSIX fork/wait, nanosleep and anonymous shared memory.
//
// The function protect_eval will cause the parent process to sleep
// until the forked child process returns, at which time the process
// receives a signal SIGCHLD and wakes up. To make sure that this
// signal is received, and not ignored, it may be necessary on your
// platform to specify a signal handler for it, even if this does
// nothing, e.g. by
//
// static void do_nothing(int) { }
// int main(void) {
// ...
// signal(SIGCHLD, do_nothing);
// ...
// }
//
// SharedBuffer is a helper class that wraps mmap/munmap to provide a
// buffer through which to return data back to the calling process.
// An important restriction is that the length of this buffer must be
// known by the calling process and specified in advance.
#ifndef PROTECT_EVAL_HPP
#define PROTECT_EVAL_HPP
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
// An anonymous shared-memory-buffer object, intended for use by
// protect_eval. Implemented as a simple wrapper around
// mmap/munmap. Objects of this type are non-copyable.
//
template <typename DataT>
class SharedBuffer {
size_t n;
DataT *m_data;
public:
DataT *data(void)
{
return m_data;
}
DataT& operator*()
{
return *m_data;
}
DataT& operator[](size_t idx)
{
return m_data[idx];
}
SharedBuffer(size_t n_ = 1)
: n(n_)
{
m_data = (DataT *)mmap(
NULL, n * sizeof(DataT), PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED, 0, 0);
if (m_data == MAP_FAILED) throw std::bad_alloc();
}
~SharedBuffer()
{
munmap(m_data, n * sizeof(DataT));
}
// not copy constructable or assignable
SharedBuffer(const SharedBuffer&) =delete;
SharedBuffer& operator=(const SharedBuffer&) =delete;
};
enum PE_ErrorCodes {PE_TIMEOUT = -2, PE_BADFORK, PE_SUCCESS};
// Wrap the functor fn (of templated type) in a forked child process.
// A timeout in seconds should be provided as the first argument. The
// functor fn must be callable with no arguments; its return value is
// not used or stored.
//
// Return values
// PE_TIMEOUT (-2): the fork succeeded but the child process exceeded
// its permitted runtime of timeout_secs seconds
//
// PE_BADFORK (-1): forking did not succeed
//
// PE_SUCCESS (0) : successful evaluation of function fn and termination
// of the child process
//
// other value >0 : abnormal termination of the child process. The
// status code is returned.
//
template <typename FnT>
int protect_eval(long timeout_secs, FnT&& fn)
{
pid_t child_pid = fork();
if (child_pid == -1) {
// fork did not succeed
return PE_BADFORK;
} else if (!child_pid) {
// fork succeeded; in child
// call the dangerous function
fn();
// exit, sending SIGCHLD to parent
_exit(0);
} else {
// fork succeeded; in parent
struct timespec req, rem;
req.tv_nsec = 0L;
req.tv_sec = timeout_secs;
nanosleep(&req, &rem);
// woke up: either sleep finished, or interrupted by signal here
// on waking up, is the child still alive?
int status;
if (!waitpid(child_pid, &status, WNOHANG)) {
// child is still alive after the time-out
kill(child_pid, SIGKILL);
return PE_TIMEOUT;
} else {
// Either success (zero status), or abnormal termination of
// child (non-zero status), indicated to caller via return
// status
return status;
}
}
};
#endif
| 28.268657 | 74 | 0.670011 | vkurilin |
44585f40d27a5486e2d530c6af6524d2d06b4188 | 4,391 | hpp | C++ | include/nornir/instrumenter.hpp | DanieleDeSensi/Nornir | 60587824d6b0a6e61b8fc75bdea37c9fc69199c7 | [
"MIT"
] | 2 | 2018-10-31T08:09:03.000Z | 2021-01-18T19:23:54.000Z | include/nornir/instrumenter.hpp | DanieleDeSensi/Nornir | 60587824d6b0a6e61b8fc75bdea37c9fc69199c7 | [
"MIT"
] | 1 | 2020-02-02T11:58:22.000Z | 2020-02-02T11:58:22.000Z | include/nornir/instrumenter.hpp | DanieleDeSensi/Nornir | 60587824d6b0a6e61b8fc75bdea37c9fc69199c7 | [
"MIT"
] | 1 | 2019-04-13T09:54:49.000Z | 2019-04-13T09:54:49.000Z | /*
* instrumenter.hpp
*
* Created on: 03/07/2016
*
* =========================================================================
* Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com)
*
* This file is part of nornir.
*
* nornir is free software: you can redistribute it and/or
* modify it under the terms of the Lesser GNU General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
* nornir 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public
* License along with nornir.
* If not, see <http://www.gnu.org/licenses/>.
*
* =========================================================================
*/
#ifndef NORNIR_INSTRUMENTER_HPP_
#define NORNIR_INSTRUMENTER_HPP_
#include <nornir/utils.hpp>
#include <nornir/parameters.hpp>
#include <riff/riff.hpp>
#include <riff/external/cppnanomsg/nn.hpp>
#include <riff/external/nanomsg/src/pair.h>
#include <mammut/mammut.hpp>
namespace nornir{
// We cannot use XDG runtime directories since they are
// user specific. Manager and application could be run
// by different users (e.g. manager by sudo user
// and application by normal user).
inline std::string getInstrumentationChannelsPath(){
return "/tmp/nornir_external_manager/";
}
inline std::string getInstrumentationConnectionChannelPath(){
return getInstrumentationChannelsPath() + "/connection.ipc";
}
inline std::string getInstrumentationPidChannelPath(uint pid){
return getInstrumentationChannelsPath() + "/" + mammut::utils::intToString(pid) + ".ipc";
}
inline std::string getInstrumentationConnectionChannel(){
return std::string("ipc://") + getInstrumentationConnectionChannelPath();
}
inline std::string getInstrumentationPidChannel(uint pid){
return std::string("ipc://") + getInstrumentationPidChannelPath(pid);
}
class InstrumenterHelper: public riff::Application, mammut::utils::NonCopyable{
public:
InstrumenterHelper(std::pair<nn::socket*, uint> p,
size_t numThreads = 1,
riff::Aggregator* aggregator = NULL):
riff::Application(*p.first, p.second, numThreads, aggregator){;}
};
/**
* Extends riff::Application by providing a way to automatically connect
* to the nornir manager server.
*/
class Instrumenter: public InstrumenterHelper{
private:
std::pair<nn::socket*, uint> getChannel(const std::string& parametersFile, bool startServer) const;
std::pair<nn::socket*, uint> connectPidChannel(const std::string& parametersFile, uint pid) const;
public:
/**
* Creates a client for interaction with a local server. The suggestion
* is to create as soon as possible (i.e. before the beginning of critical
* parts of application) such that in the meanwhile a connection
* with the manager can be established.
* @param parametersFile The file containing the Nornir parameters.
* @param numThreads The number of threads calling the instrumentation calls.
* @param aggregator The riff aggregator.
*/
explicit Instrumenter(const std::string& parametersFile,
size_t numThreads = 1,
riff::Aggregator* aggregator = NULL,
bool startServer = false);
/**
* This function can be used to dynamically change the user requirements
* while the application is running. If this function is used, the
* storeCustomValue MUST NOT be used by the user. Moreover, aggregator MUST NOT
* be specified when constructing the instrumenter.
* This function must be called after the end() function.
* @param type The type of requirement.
* @param value The value of the requirement.
*/
void changeRequirement(RequirementType type, double value);
};
/**
* A server which can interact with the Instrumenter.
**/
class InstrumenterServer: public mammut::utils::Thread{
private:
bool _singleClient;
public:
InstrumenterServer(bool singleClient = true):_singleClient(singleClient){;}
void run();
};
}
#endif /* NORNIR_INSTRUMENTER_HPP_ */
| 36.289256 | 103 | 0.68777 | DanieleDeSensi |
445a4787b4a68734a6e7ea9f761511a647f5bca8 | 2,956 | cpp | C++ | sdk/app/ultra_simple/Compass.cpp | ivanmaNTNU/FolloMe | bd0bb2ddbb77129178f04da51b12b1f7f4f14dd5 | [
"BSD-2-Clause"
] | null | null | null | sdk/app/ultra_simple/Compass.cpp | ivanmaNTNU/FolloMe | bd0bb2ddbb77129178f04da51b12b1f7f4f14dd5 | [
"BSD-2-Clause"
] | null | null | null | sdk/app/ultra_simple/Compass.cpp | ivanmaNTNU/FolloMe | bd0bb2ddbb77129178f04da51b12b1f7f4f14dd5 | [
"BSD-2-Clause"
] | null | null | null | #include "Compass.h"
#include <math.h>
#include <string>
#include <iostream>
#include <math.h>
#define MPU9250_ADDR_ACCELCONFIG 0x1C
#define MPU9250_ADDR_INT_PIN_CFG 0x37
#define MPU9250_ADDR_ACCEL_XOUT_H 0x3B
#define MPU9250_ADDR_GYRO_XOUT_H 0x43
#define MPU9250_ADDR_PWR_MGMT_1 0x6B
#define MPU9250_ADDR_WHOAMI 0x75
void Compass::i2cRead(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t* Data) {
if (Address == AK8963_ADDRESS){
uint8_t index=0;
while (index < Nbytes) {
Data[index++]= wiringPiI2CReadReg8(magFile, Register); // Change to Address if not working.
Register++;
}
}
else if (Address == MPU9250_ADDRESS_AD0_LOW){
uint8_t index=0;
while (index < Nbytes) {
Data[index++]= wiringPiI2CReadReg8(mainFile, Register); // Change to Address if not working.
Register++;
}
}
}
void Compass::i2cWriteByte(uint8_t Address, uint8_t Register, uint8_t Data) {
if (Address == AK8963_ADDRESS){
wiringPiI2CWriteReg8(magFile, Register, Data);
}
else if (Address == MPU9250_ADDRESS_AD0_LOW){
wiringPiI2CWriteReg8(mainFile, Register, Data);
}
}
uint8_t Compass::readId() {
uint8_t id;
i2cRead(address, MPU9250_ADDR_WHOAMI, 1, &id);
return id;
}
void Compass::magReadAdjustValues() {
magSetMode(MAG_MODE_POWERDOWN);
magSetMode(MAG_MODE_FUSEROM);
uint8_t buff[3];
i2cRead(AK8963_ADDRESS, AK8963_RA_ASAX, 3, buff);
magXAdjust = buff[0];
magYAdjust = buff[1];
magZAdjust = buff[2];
}
void Compass::beginMag(uint8_t mode) {
magWakeup();
magEnableSlaveMode();
magReadAdjustValues();
magSetMode(MAG_MODE_POWERDOWN);
magSetMode(mode);
delay(10);
}
void Compass::magSetMode(uint8_t mode) {
i2cWriteByte(AK8963_ADDRESS, AK8963_RA_CNTL1, mode);
delay(10);
}
void Compass::magWakeup() {
unsigned char bits;
i2cRead(address, MPU9250_ADDR_PWR_MGMT_1, 1, &bits);
bits &= ~0x70; // Turn off SLEEP, STANDBY, CYCLE
i2cWriteByte(address, MPU9250_ADDR_PWR_MGMT_1, bits);
delay(10);
}
void Compass::magEnableSlaveMode() {
unsigned char bits;
i2cRead(address, MPU9250_ADDR_INT_PIN_CFG, 1, &bits);
bits |= 0x02; // Activate BYPASS_EN
i2cWriteByte(address, MPU9250_ADDR_INT_PIN_CFG, bits);
delay(10);
}
const float Pi = 3.14159265359;
float Compass::magHorizDirection() {
double dir = atan2(magY(), magX()) * 180 / Pi;
if (dir < 0){
dir += 360;
}
return dir;
}
void Compass::magUpdate() {
i2cRead(AK8963_ADDRESS, AK8963_RA_HXL, 7, magBuf);
}
int16_t Compass::magGet(uint8_t highIndex, uint8_t lowIndex) {
return (((int16_t) magBuf[highIndex]) << 8) | magBuf[lowIndex];
}
float adjustMagValue(int16_t value, uint8_t adjust) {
return ((float) value * (((((float) adjust - 128) * 0.5) / 128) + 1));
}
float Compass::magX() {
return adjustMagValue(magGet(1, 0), magXAdjust) + magXOffset;
}
float Compass::magY() {
return adjustMagValue(magGet(3, 2), magYAdjust) + magYOffset;
}
float Compass::magZ() {
return adjustMagValue(magGet(5, 4), magZAdjust) + magZOffset;
}
| 22.393939 | 95 | 0.721583 | ivanmaNTNU |
445a5f448f24c8ce0d0021d6c3acb720509f6a10 | 1,186 | cpp | C++ | AtCoder/ABC192/D_sol1_binary_search.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | AtCoder/ABC192/D_sol1_binary_search.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | AtCoder/ABC192/D_sol1_binary_search.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool isValid(const string& X, const long long& BASE, const long long& M){
long long num = 0;
for(long long i = 0; i < (int)X.length(); ++i){
if(num > (M - (X[i] - '0')) / BASE){
return false;
}
num = BASE * num + (X[i] - '0');
}
return true;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string X;
long long M;
cin >> X >> M;
const long long MIN_BASE = *max_element(X.begin(), X.end()) - '0' + 1;
const long long MAX_BASE = max(MIN_BASE, M);
long long answer = 0;
if(X.length() == 1){
answer = ((X[0] - '0') <= M);
}else{
long long l = MIN_BASE;
long long r = MAX_BASE;
while(l != r){
long long mid = (l + r + 1) / 2;
if(isValid(X, mid, M)){
l = mid;
}else{
r = mid - 1;
}
}
if(MIN_BASE == r){
answer = isValid(X, MIN_BASE, M);
}else{
answer = r - MIN_BASE + 1;
}
}
cout << answer;
return 0;
} | 23.254902 | 75 | 0.427487 | Tudor67 |
446486783cad1f815b316ca2835d5c5b1d5d8c30 | 1,243 | hpp | C++ | irohad/network/ordering_service.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | irohad/network/ordering_service.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | irohad/network/ordering_service.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
* http://soramitsu.co.jp
*
* 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 IROHA_ORDERINGSERVICE_H
#define IROHA_ORDERINGSERVICE_H
#include "network/ordering_service_transport.hpp"
namespace iroha {
namespace network {
class OrderingService : public network::OrderingServiceNotification {
public:
/**
* Transform model proposal to transport object and send to peers
* @param proposal - object for propagation
*/
virtual void publishProposal(
std::unique_ptr<shared_model::interface::Proposal> proposal) = 0;
};
} // namespace network
} // namespace iroha
#endif // IROHA_ORDERINGSERVICE_H
| 32.710526 | 75 | 0.720032 | coderintherye |
4467727982616e880bac5ac70d5337abcc44be0e | 4,451 | cc | C++ | src/vnsw/agent/contrail/main.cc | EWERK-DIGITAL/tf-controller | 311ea863b03d425a67d04d27c1f1b9cf1e20c926 | [
"Apache-2.0"
] | 37 | 2020-09-21T10:42:26.000Z | 2022-01-09T10:16:40.000Z | src/vnsw/agent/contrail/main.cc | EWERK-DIGITAL/tf-controller | 311ea863b03d425a67d04d27c1f1b9cf1e20c926 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/contrail/main.cc | EWERK-DIGITAL/tf-controller | 311ea863b03d425a67d04d27c1f1b9cf1e20c926 | [
"Apache-2.0"
] | 21 | 2020-08-25T12:48:42.000Z | 2022-03-22T04:32:18.000Z | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <boost/program_options.hpp>
#include <base/logging.h>
#include <base/contrail_ports.h>
#include <pugixml/pugixml.hpp>
#include <base/task.h>
#include <io/event_manager.h>
#include <sandesh/common/vns_types.h>
#include <sandesh/common/vns_constants.h>
#include <base/misc_utils.h>
#include <cmn/buildinfo.h>
#include <cmn/agent_cmn.h>
#include <cfg/cfg_init.h>
#include <cfg/cfg_mirror.h>
#include <init/agent_param.h>
#include <oper/operdb_init.h>
#include <oper/vrf.h>
#include <oper/multicast.h>
#include <oper/mirror_table.h>
#include <controller/controller_init.h>
#include <controller/controller_vrf_export.h>
#include <pkt/pkt_init.h>
#include <services/services_init.h>
#include <vrouter/ksync/ksync_init.h>
#include <uve/agent_uve.h>
#include <kstate/kstate.h>
#include <pkt/proto.h>
#include <diag/diag.h>
#include <boost/functional/factory.hpp>
#include <cmn/agent_factory.h>
#include "contrail_agent_init.h"
#define MAX_RETRY 60
namespace opt = boost::program_options;
void RouterIdDepInit(Agent *agent) {
// Parse config and then connect
Agent::GetInstance()->controller()->Connect();
LOG(DEBUG, "Router ID Dependent modules (Nova and BGP) INITIALIZED");
}
bool is_vhost_interface_up() {
struct ifreq ifr;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, "vhost0");
int err = ioctl(sock, SIOCGIFFLAGS, &ifr);
if (err < 0 || !(ifr.ifr_flags & IFF_UP)) {
close(sock);
LOG(DEBUG, "vhost is down");
return false;
}
err = ioctl(sock, SIOCGIFADDR, &ifr);
if (err < 0) {
close(sock);
LOG(DEBUG, "vhost is up, but ip is not set");
return false;
}
close(sock);
return true;
}
bool GetBuildInfo(std::string &build_info_str) {
return MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info_str);
}
int main(int argc, char *argv[]) {
AgentParam params;
srand(unsigned(time(NULL)));
try {
params.ParseArguments(argc, argv);
} catch (...) {
std::cout << "Invalid arguments. ";
std::cout << params.options() << std::endl;
exit(0);
}
opt::variables_map var_map = params.var_map();
if (var_map.count("help")) {
std::cout << params.options() << std::endl;
exit(0);
}
if (var_map.count("version")) {
string build_info;
MiscUtils::GetBuildInfo(MiscUtils::Agent, BuildInfo, build_info);
std::cout << params.options() << std::endl;
exit(0);
}
string init_file = "";
if (var_map.count("config_file")) {
init_file = var_map["config_file"].as<string>();
struct stat s;
if (stat(init_file.c_str(), &s) != 0) {
std::cout << "Error opening config file <" << init_file
<< ">. Error number <" << errno << ">";
exit(EINVAL);
}
}
// Read agent parameters from config file and arguments
params.Init(init_file, argv[0]);
if (!params.cat_is_agent_mocked() &&
params.loopback_ip() == Ip4Address(0)) {
uint16_t i;
for (i = 0; i < MAX_RETRY; i++) {
std::cout << "INFO: wait vhost0 to be initilaized... "
<< i << "/" << MAX_RETRY << std::endl;
if (is_vhost_interface_up()) {
std::cout << "INFO: vhost0 is ready." << std::endl;
break;
}
usleep(5000000); //sleep for 5 seconds
}
if (i == MAX_RETRY) {
std::cout << "INFO: vhost0 is not ready." << std::endl;
exit(0);
}
}
// Initialize TBB
// Call to GetScheduler::GetInstance() will also create Task Scheduler
TaskScheduler::Initialize(params.tbb_thread_count());
// Initialize the agent-init control class
ContrailAgentInit init;
if (params.cat_is_agent_mocked()) {
init.set_create_vhost(false);
}
init.set_agent_param(¶ms);
// kick start initialization
int ret = 0;
if ((ret = init.Start()) != 0) {
return ret;
}
string build_info;
GetBuildInfo(build_info);
MiscUtils::LogVersionInfo(build_info, Category::VROUTER);
Agent *agent = init.agent();
TaskScheduler::GetInstance()->set_event_manager(agent->event_manager());
agent->event_manager()->Run();
return 0;
}
| 27.475309 | 80 | 0.614469 | EWERK-DIGITAL |
446b4bb62a26a94afa70d7cb047296e462273f31 | 1,135 | cpp | C++ | src/RE/N/NiMatrix3.cpp | gottyduke/CommonLibSSE | 8a749684395942fccf43443b4509eac4f0f3e8ee | [
"MIT"
] | 1 | 2021-07-24T17:03:18.000Z | 2021-07-24T17:03:18.000Z | src/RE/N/NiMatrix3.cpp | gottyduke/CommonLibSSE | 8a749684395942fccf43443b4509eac4f0f3e8ee | [
"MIT"
] | null | null | null | src/RE/N/NiMatrix3.cpp | gottyduke/CommonLibSSE | 8a749684395942fccf43443b4509eac4f0f3e8ee | [
"MIT"
] | 1 | 2021-11-29T10:14:44.000Z | 2021-11-29T10:14:44.000Z | #include "RE/N/NiMatrix3.h"
#include "RE/N/NiMath.h"
#include "RE/N/NiPoint3.h"
namespace RE
{
NiPoint3 NiMatrix3::operator*(const NiPoint3& a_rhs) const
{
return NiPoint3(
entry[0][0] * a_rhs.x + entry[0][1] * a_rhs.y + entry[0][2] * a_rhs.z,
entry[1][0] * a_rhs.x + entry[1][1] * a_rhs.y + entry[1][2] * a_rhs.z,
entry[2][0] * a_rhs.x + entry[2][1] * a_rhs.y + entry[2][2] * a_rhs.z);
}
bool NiMatrix3::ToEulerAnglesXYZ(NiPoint3& a_angle) const
{
return ToEulerAnglesXYZ(a_angle.x, a_angle.y, a_angle.z);
}
bool NiMatrix3::ToEulerAnglesXYZ(float& a_xAngle, float& a_yAngle, float& a_zAngle) const
{
a_yAngle = -NiASin(entry[0][2]);
if (a_yAngle < NI_HALF_PI) {
if (a_yAngle > -NI_HALF_PI) {
a_xAngle = -NiFastATan2(-entry[1][2], entry[2][2]);
a_zAngle = -NiFastATan2(-entry[0][1], entry[0][0]);
return true;
} else {
float rmY = NiFastATan2(entry[1][0], entry[1][1]);
a_zAngle = 0.0;
a_xAngle = rmY - a_zAngle;
return false;
}
} else {
float rpY = NiFastATan2(entry[1][0], entry[1][1]);
a_zAngle = 0.0;
a_xAngle = a_zAngle - rpY;
return false;
}
}
}
| 26.395349 | 90 | 0.621145 | gottyduke |
446e1229bf11f11535bf68e84d9f2a9f770ab027 | 303 | hpp | C++ | Jagerts.Kaleid.Graphics/Cube.hpp | Jagreaper/Kaleid | 4fd28f5921d54048d9dfd75f1640abe68a09f580 | [
"MIT"
] | null | null | null | Jagerts.Kaleid.Graphics/Cube.hpp | Jagreaper/Kaleid | 4fd28f5921d54048d9dfd75f1640abe68a09f580 | [
"MIT"
] | null | null | null | Jagerts.Kaleid.Graphics/Cube.hpp | Jagreaper/Kaleid | 4fd28f5921d54048d9dfd75f1640abe68a09f580 | [
"MIT"
] | null | null | null | #pragma once
#include "Jagerts.Kaleid.Graphics/RenderableShape.hpp"
namespace Jagerts::Kaleid::Graphics
{
class JAGERTS_KALEID_GRAPHICS_API Cube : public RenderableShape
{
public:
Cube();
~Cube();
jkgUsingRenderableShape;
jkmUsingTransformableObject;
jkgRenderableShapeStaticHeader;
};
} | 18.9375 | 64 | 0.782178 | Jagreaper |
446e2f4e72f7ea39e8efb3e3c884db813c69d7c0 | 3,726 | cpp | C++ | src/App.cpp | ColeDeanShepherd/12-Steps-To-Navier-Stokes | 3bb31990457df3c31ab024a84ca521a3dfbf178d | [
"MIT"
] | 45 | 2018-01-14T17:58:51.000Z | 2022-03-16T23:47:48.000Z | src/App.cpp | ColeDeanShepherd/12-Steps-To-Navier-Stokes | 3bb31990457df3c31ab024a84ca521a3dfbf178d | [
"MIT"
] | null | null | null | src/App.cpp | ColeDeanShepherd/12-Steps-To-Navier-Stokes | 3bb31990457df3c31ab024a84ca521a3dfbf178d | [
"MIT"
] | 8 | 2018-07-02T00:34:48.000Z | 2021-05-12T09:33:04.000Z | #include "App.h"
#include "Core.h"
#include "Step1.h"
#include "Step2.h"
#include "Step3.h"
#include "Step4.h"
#include "Step5.h"
#include "Step6.h"
#include "Step7.h"
#include "Step8.h"
#include "Step9.h"
#include "Step10.h"
#include "Step11.h"
#include "Step12.h"
void App::run()
{
initSDL();
changeStep(1);
lastPerfCount = SDL_GetPerformanceCounter();
accumulatedTime = 0;
#ifndef __EMSCRIPTEN__
shouldExit = false;
while(!shouldExit)
{
runFrame();
}
#else
emscripten_set_main_loop(runFrame, 0, 1);
#endif
cleanupSDL();
}
void App::initSDL()
{
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow(
"12 Steps to Navier-Stokes", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
WINDOW_WIDTH, WINDOW_HEIGHT, 0
);
renderer = SDL_CreateRenderer(window, -1, 0);
}
void App::cleanupSDL()
{
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
std::unique_ptr<Step> App::createStep(const int stepNumber) const
{
switch(stepNumber)
{
case 1:
return std::make_unique<Step1LinearConvection1D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 2:
return std::make_unique<Step2NonlinearConvection1D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 3:
return std::make_unique<Step3Diffusion1D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 4:
return std::make_unique<Step4BurgersEquation1D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 5:
return std::make_unique<Step5LinearConvection2D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 6:
return std::make_unique<Step6NonlinearConvection2D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 7:
return std::make_unique<Step7Diffusion2D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 8:
return std::make_unique<Step8BurgersEquation2D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 9:
return std::make_unique<Step9LaplaceEquation2D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 10:
return std::make_unique<Step10PoissonEquation2D>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 11:
return std::make_unique<Step11CavityFlow>(WINDOW_WIDTH, WINDOW_HEIGHT);
case 12:
return std::make_unique<Step12ChannelFlow>(WINDOW_WIDTH, WINDOW_HEIGHT);
default:
throw std::runtime_error("Invalid step number.");
}
}
void App::changeStep(const int newStepNumber)
{
stepNumber = newStepNumber;
step = createStep(stepNumber);
SDL_SetWindowTitle(window, step->title.c_str());
}
void App::updateTiming()
{
const auto curPerfCount = SDL_GetPerformanceCounter();
const double dt = (double)(curPerfCount - lastPerfCount) / SDL_GetPerformanceFrequency();
accumulatedTime += dt;
lastPerfCount = curPerfCount;
}
void App::handleSDLEvent(const SDL_Event& event)
{
if(event.type == SDL_QUIT)
{
shouldExit = true;
}
else if(event.type == SDL_KEYDOWN)
{
if(event.key.keysym.sym == SDLK_LEFT)
{
changeStep(wrap(stepNumber - 1, 1, 12));
}
else if(event.key.keysym.sym == SDLK_RIGHT)
{
changeStep(wrap(stepNumber + 1, 1, 12));
}
}
}
void App::drawFrame()
{
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
step->draw(renderer);
SDL_RenderPresent(renderer);
}
void App::runFrame()
{
updateTiming();
SDL_Event event;
while(SDL_PollEvent(&event))
{
handleSDLEvent(event);
}
auto updatesThisFrame = 0;
while((updatesThisFrame < MAX_UPDATES_PER_FRAME) && (accumulatedTime >= step->fixedTimeStep))
{
step->update(step->fixedTimeStep);
accumulatedTime -= step->fixedTimeStep;
updatesThisFrame++;
}
drawFrame();
} | 26.055944 | 97 | 0.672303 | ColeDeanShepherd |
4470ad19b10331540348190c471f321e0c0a4054 | 1,824 | cpp | C++ | 02_ofApp/code/myStridePatternSketch/src/ofApp.cpp | abrennec/sose20_cc2 | e609bbc2b2834dcd1998c7d044d80f8d325c9e52 | [
"MIT"
] | null | null | null | 02_ofApp/code/myStridePatternSketch/src/ofApp.cpp | abrennec/sose20_cc2 | e609bbc2b2834dcd1998c7d044d80f8d325c9e52 | [
"MIT"
] | null | null | null | 02_ofApp/code/myStridePatternSketch/src/ofApp.cpp | abrennec/sose20_cc2 | e609bbc2b2834dcd1998c7d044d80f8d325c9e52 | [
"MIT"
] | null | null | null | // This example is taken from the Book "openFrameworks Essentials"
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(0);
auto myWindowWidth;
auto myWindowHeight;
myWindowWidth = ofGetWidth() / 2;
myWindowHeight = ofGetHeight() / 2;
ofPushMatrix();
ofTranslate( myWindowWidth, myWindowHeight );
ofSetColor( ofColor::white );
ofSetLineWidth( 3.0 );
ofNoFill();
for (auto i{-50}; i<50; ++i) {
ofPushMatrix();
ofTranslate( i*20, 0 );
ofRotateDeg( i*5 );
ofScale( 6, 6 );
ofDrawTriangle( 0, 0, -50, 100, 50, 100 );
ofPopMatrix();
}
ofPopMatrix();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
| 20.965517 | 66 | 0.365132 | abrennec |
4470c98a1468a299a7dd9171ad583ebd5f753dab | 3,861 | hpp | C++ | libff/algebra/fields/binary/gf256.hpp | meilof/libff | c71bbbd25a64c2dda38a942584f3e2cc3be06021 | [
"MIT"
] | null | null | null | libff/algebra/fields/binary/gf256.hpp | meilof/libff | c71bbbd25a64c2dda38a942584f3e2cc3be06021 | [
"MIT"
] | null | null | null | libff/algebra/fields/binary/gf256.hpp | meilof/libff | c71bbbd25a64c2dda38a942584f3e2cc3be06021 | [
"MIT"
] | null | null | null | /**@file
*****************************************************************************
Declaration of GF(2^256) finite field.
*****************************************************************************
* @author This file is part of libff (see AUTHORS), migrated from libiop
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LIBFF_ALGEBRA_GF256_HPP_
#define LIBFF_ALGEBRA_GF256_HPP_
#include <cstddef>
#include <cstdint>
#include <vector>
#include <libff/algebra/field_utils/bigint.hpp>
namespace libff {
/* x^256 + x^10 + x^5 + x^2 + 1 */
/* gf256 implements the field GF(2)/(x^256 + x^10 + x^5 + x^2 + 1).
Elements are represented internally with four uint64s */
class gf256 {
public:
#ifdef PROFILE_OP_COUNTS // NOTE: op counts are affected when you exponentiate with ^
static long long add_cnt;
static long long sub_cnt;
static long long mul_cnt;
static long long sqr_cnt;
static long long inv_cnt;
#endif
// x^256 + x^10 + x^5 + x^2 + 1
static const constexpr uint64_t modulus_ = 0b10000100101;
static const constexpr uint64_t num_bits = 256;
explicit gf256();
/* we need a constructor that only initializes the low 64 bits of value_ to
be able to do gf256(0) and gf256(1). */
explicit gf256(const uint64_t value_low);
explicit gf256(const uint64_t value_high, const uint64_t value_midh,
const uint64_t value_midl, const uint64_t value_low);
gf256& operator+=(const gf256 &other);
gf256& operator-=(const gf256 &other);
gf256& operator*=(const gf256 &other);
gf256& operator^=(const unsigned long pow);
template<mp_size_t m>
gf256& operator^=(const bigint<m> &pow);
gf256& square();
gf256& invert();
gf256 operator+(const gf256 &other) const;
gf256 operator-(const gf256 &other) const;
gf256 operator-() const;
gf256 operator*(const gf256 &other) const;
gf256 operator^(const unsigned long pow) const;
template<mp_size_t m>
gf256 operator^(const bigint<m> &pow) const;
gf256 squared() const;
gf256 inverse() const;
gf256 sqrt() const;
void randomize();
void clear();
bool operator==(const gf256 &other) const;
bool operator!=(const gf256 &other) const;
bool is_zero() const;
void print() const;
/**
* Returns the constituent bits in 64 bit words, in little-endian order.
* Only the right-most ceil_size_in_bits() bits are used; other bits are 0.
*/
std::vector<uint64_t> to_words() const;
/**
* Sets the field element from the given bits in 64 bit words, in little-endian order.
* Only the right-most ceil_size_in_bits() bits are used; other bits are ignored.
* Should always return true since the right-most bits are always valid.
*/
bool from_words(std::vector<uint64_t> words);
static gf256 random_element();
static gf256 zero();
static gf256 one();
static gf256 multiplicative_generator; // generator of gf256^*
static std::size_t ceil_size_in_bits() { return num_bits; }
static std::size_t floor_size_in_bits() { return num_bits; }
static constexpr std::size_t extension_degree() { return 256; }
template<mp_size_t n>
static constexpr bigint<n> field_char() { return bigint<n>(2); }
friend std::ostream& operator<<(std::ostream &out, const gf256 &p);
friend std::istream& operator>>(std::istream &in, gf256 &p);
private:
/* little-endian */
uint64_t value_[4];
};
#ifdef PROFILE_OP_COUNTS
long long gf256::add_cnt = 0;
long long gf256::sub_cnt = 0;
long long gf256::mul_cnt = 0;
long long gf256::sqr_cnt = 0;
long long gf256::inv_cnt = 0;
#endif
} // namespace libff
#include <libff/algebra/fields/binary/gf256.tcc>
#endif // namespace libff_ALGEBRA_GF256_HPP_
| 33.284483 | 90 | 0.64258 | meilof |
4472e91ce38b4e48c16a06429112a1476197ed79 | 3,883 | cc | C++ | src/runtime/v8rt/v8rt.cc | fuxiaohei/xiaohei-worker | 2c6a6357f86a06880d296ecbba2e3f88d3dbd1b5 | [
"Apache-2.0"
] | null | null | null | src/runtime/v8rt/v8rt.cc | fuxiaohei/xiaohei-worker | 2c6a6357f86a06880d296ecbba2e3f88d3dbd1b5 | [
"Apache-2.0"
] | null | null | null | src/runtime/v8rt/v8rt.cc | fuxiaohei/xiaohei-worker | 2c6a6357f86a06880d296ecbba2e3f88d3dbd1b5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 fuxiaohei. All rights reserved.
* Licensed under the Apache-2.0 License. See License file in the project root for
* license information.
*/
#include <common/common.h>
#include <hv/hlog.h>
#include <runtime/v8rt/v8js_context.h>
#include <runtime/v8rt/v8rt.h>
#include <v8wrap/isolate.h>
#include <v8wrap/js_value.h>
#include <webapi/global_scope.h>
namespace v8rt {
V8Runtime::V8Runtime(const Options &options) { // create a new isolate
size_t memory_size = V8_JS_ISOLATE_MEMORY_LIMIT;
if (options.memory_limit > 0) {
memory_size = options.memory_limit; // in mb
}
allocator_ = new v8wrap::Allocator();
isolate_ = v8wrap::new_isolate(allocator_, memory_size * 1024 * 1024);
hlogd("v8js: create isolate, iso:%p, alloc:%p, memory_size:%zu", isolate_, allocator_,
memory_size);
}
V8Runtime::~V8Runtime() {
hlogd("v8js: dispose isolate, iso:%p, alloc:%p", isolate_, allocator_);
v8wrap::IsolateData::Release(isolate_);
isolate_->Dispose();
isolate_ = nullptr;
delete allocator_;
allocator_ = nullptr;
}
RuntimeContext *V8Runtime::get_context() {
RuntimeContext *jsContext;
// if queue is empty create new one
if (context_queue_.empty()) {
jsContext = V8JsContext::Create(this, content_, origin_);
hlogd("v8js: create jsContext, iso:%p, jsCtx:%p, queue:%ld", isolate_, jsContext,
context_queue_.size());
} else {
jsContext = context_queue_.front();
context_queue_.pop();
hlogd("v8js: get jsContext, iso:%p, jsCtx:%p, queue:%ld", isolate_, jsContext,
context_queue_.size());
}
return jsContext;
}
void V8Runtime::recycle_context(RuntimeContext *context) {
V8JsContext *jsContext = static_cast<V8JsContext *>(context);
if (jsContext->get_error_code() != 0) {
hlogd("v8js: recycle error jsContext, jsCtx:%p, error_code:%d, msg:%s", jsContext,
jsContext->get_error_code(), jsContext->get_exception_msg().c_str());
delete jsContext;
return;
}
// push bach to queue
context_queue_.push(jsContext);
hlogd("v8js: recycle jsContext, iso:%p, jsCtx:%p, queue:%ld", isolate_, jsContext,
context_queue_.size());
}
int V8Runtime::compile(const std::string &content, const std::string &origin) {
content_ = content;
origin_ = origin;
auto jsContext = V8JsContext::Create(this, content_, origin_);
if (jsContext == nullptr) {
hlogw("v8js: compile nullptr, iso:%p, jsCtx:%p, error_code:%d, msg:%s", isolate_, jsContext,
jsContext->get_error_code(), jsContext->get_exception_msg().c_str());
return common::ERROR_RUNTIME_COMPILE_ERROR;
}
if (jsContext->get_error_code() != 0) {
int error_code = jsContext->get_error_code();
compile_error_message_ = jsContext->get_exception_msg();
hlogw("v8js: compile error, error_code:%d, msg:%s", error_code, compile_error_message_.c_str());
delete jsContext;
return error_code;
}
context_queue_.push(jsContext);
hlogd("v8js: create jsContext, iso:%p, jsCtx:%p, queue:%ld, result:%s", isolate_, jsContext,
context_queue_.size(), jsContext->get_compiled_result().data());
return 0;
}
// --- single methods
common::Heap *getHeap(v8::Local<v8::Context> context) {
// allocate request scope
auto reqScope = getRequestScope(context);
if (reqScope != nullptr) {
return reqScope->heap_;
}
// alloc by global scope
auto scope =
v8wrap::get_ptr<webapi::ServiceWorkerGlobalScope>(context, V8_JS_CONTEXT_JSGLOBAL_INDEX);
if (scope == nullptr) {
return nullptr;
}
return scope->heap_;
}
core::RequestScope *getRequestScope(v8::Local<v8::Context> context) {
return v8wrap::get_ptr<core::RequestScope>(context, V8_JS_CONTEXT_REQUEST_SCOPE_INDEX);
}
V8JsContext *getJsContext(v8::Local<v8::Context> context) {
return v8wrap::get_ptr<V8JsContext>(context, V8_JS_CONTEXT_SELF_INDEX);
}
} // namespace v8rt
| 31.569106 | 100 | 0.700747 | fuxiaohei |
447561b2681207b5872a64f9556ceb1b06264041 | 915 | cpp | C++ | Excelenta/Problema2.cpp | NegreanV/MyAlgorithms | 7dd16d677d537d34280c3858ccf4cbea4b3ddf26 | [
"Apache-2.0"
] | 1 | 2015-10-24T10:02:06.000Z | 2015-10-24T10:02:06.000Z | Excelenta/Problema2.cpp | NegreanV/MyAlgorithms | 7dd16d677d537d34280c3858ccf4cbea4b3ddf26 | [
"Apache-2.0"
] | null | null | null | Excelenta/Problema2.cpp | NegreanV/MyAlgorithms | 7dd16d677d537d34280c3858ccf4cbea4b3ddf26 | [
"Apache-2.0"
] | null | null | null | /* Fisierul text bac.txt contine, pe o singura linie, cel mult 1000 de numere
naturale nenule, numerele fiind separate prin câte un spatiu. Scrieti un
program C/C++ care citeste de la tastatura un numar natural nenul n si numerele 0
din fisierul bac.txt si care afiseaza pe ecran, separate prin câte un spatiu, toate
numerele din fisier care sunt divizibile cu n. Daca fisierul nu contine niciun astfel
de numar, atunci se va afisa pe ecran mesajul NU EXISTA. Exemplu: daca fisierul
bac.txt contine numerele: 3 100 40 70 25 5 80 6 3798, pentru n=10 atunci pe ecran se va afisa: 100 40 70 80 */
#include <fstream>
using namespace std;
ifstream f("input.in");
int main()
{
int n, x, k = 0;
cin >> n;
while(f >> x)
{
if(x % n == 0)
{
cout << x << " ";
k++;
}
if(k == 0)
{
cout << "NU EXISTA";
}
return 0;
}
| 26.142857 | 111 | 0.621858 | NegreanV |
4476e40e21b87d1c70d037b7afa78f7226fbebe5 | 1,477 | cpp | C++ | src/TextFTGL.cpp | macton/chromium-bsu | 27e70290913f62401f1ecfca9e806b6ba9170547 | [
"ClArtistic"
] | 3 | 2019-06-07T16:09:28.000Z | 2021-04-01T21:46:24.000Z | src/TextFTGL.cpp | macton/chromium-bsu | 27e70290913f62401f1ecfca9e806b6ba9170547 | [
"ClArtistic"
] | 1 | 2020-12-19T15:20:14.000Z | 2020-12-28T10:00:31.000Z | src/TextFTGL.cpp | macton/chromium-bsu | 27e70290913f62401f1ecfca9e806b6ba9170547 | [
"ClArtistic"
] | 3 | 2016-04-19T17:07:30.000Z | 2019-03-01T05:47:53.000Z | /*
* Copyright 2009 Paul Wise
*
* "Chromium B.S.U." is free software; you can redistribute
* it and/or use it and/or modify it under the terms of the
* "Clarified Artistic License"
*/
#ifdef HAVE_CONFIG_H
#include <chromium-bsu-config.h>
#endif
#ifdef TEXT_FTGL
#include "gettext.h"
#include "TextFTGL.h"
#include <sys/stat.h>
#include <FTGL/ftgl.h>
#ifdef HAVE_FONTCONFIG
#include <fontconfig/fontconfig.h>
#endif
using namespace std;
//====================================================================
TextFTGL::TextFTGL()
{
fontFile = findFont();
ftFont = new FTBufferFont(fontFile);
if(ftFont->Error())
{
fprintf(stderr, _("FTGL: error loading font: %s\n"), fontFile);
delete ftFont; ftFont = NULL;
free((void*)fontFile); fontFile = NULL;
throw _("FTGL: error loading font");
}
free((void*)fontFile); fontFile = NULL;
ftFont->FaceSize(24);
}
TextFTGL::~TextFTGL()
{
delete ftFont; ftFont = NULL;
free((void*)fontFile); fontFile = NULL;
}
void TextFTGL::Render(const char* str, const int len)
{
/*
FTGL renders the whole string when len == 0
but we don't want any text rendered then.
*/
if(len != 0)
ftFont->Render(str, len);
}
float TextFTGL::Advance(const char* str, const int len)
{
return ftFont->Advance(str, len);
}
float TextFTGL::LineHeight(const char* str, const int len)
{
return ftFont->LineHeight();
}
const char* TextFTGL::findFont()
{
return strdup("c:\\windows\\fonts\\arial.ttf");
}
#endif // TEXT_FTGL
| 19.434211 | 70 | 0.654705 | macton |
4478daa11e975de6c2787eb6c3f88d9a975f2c04 | 1,653 | cpp | C++ | snowman.cpp | SolomonWriter/messageboard-b | 0e80c6f307ec1b6e0c6cddc5d5f31cd9d537d949 | [
"MIT"
] | null | null | null | snowman.cpp | SolomonWriter/messageboard-b | 0e80c6f307ec1b6e0c6cddc5d5f31cd9d537d949 | [
"MIT"
] | null | null | null | snowman.cpp | SolomonWriter/messageboard-b | 0e80c6f307ec1b6e0c6cddc5d5f31cd9d537d949 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <array>
using namespace std;
#include "snowman.hpp"
using namespace ariel;
int charToInt( char c ) { return c - '0'; }
namespace ariel
{
std::string snowman(int number)
{
if( number < 0){throw std::out_of_range {"The Number must be POSITIVE"};}
//The number length must be 8 otherwise we would not know how to produce the snowman
string man = to_string(number);
if(man.size() != EIGHT) { throw std::out_of_range {"Number Length must be = "+to_string(EIGHT)};}
/*
Here we are cheking integer by integer
The integers that allowed are 1,2,3,4 other than that we cannot produce a perfect looking snowman
*/
int copy = number;
while(copy > 0){
int check = copy%TEN;
if(check == ONE || check == TWO || check == THREE || check == FOUR){
copy /=TEN;
continue;
}
throw std::out_of_range {"Number must not include Integer = "+to_string(check)};
}
string build;
// Converting all characters into integers
int h = charToInt(man[H]);
int n = charToInt(man[N]);
int l = charToInt(man[L]);
int r = charToInt(man[R]);
int x = charToInt(man[X]);
int y = charToInt(man[Y]);
int t = charToInt(man[T]);
int b = charToInt(man[B]);
//Here we are building the string line by line -> To get a perfect looking snowman
build = Hat.at(h) + "\n";
build += XUp.at(x) + Left.at(l) + Nose.at(n) + Right.at(r) + YUp.at(y) + "\n";
build += XDown.at(x) + Torso.at(t) + YDown.at(y) + "\n";
build += " "+Base.at(b);
return build;
}
};
| 24.308824 | 102 | 0.591652 | SolomonWriter |
44796ad0b7a34eaf24e293b355187c54832fe1c2 | 2,693 | hpp | C++ | include/reduction/ConnectedComponentSeparator.hpp | sgraf812/pbqp-papa | b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07 | [
"MIT"
] | 1 | 2020-08-10T04:18:11.000Z | 2020-08-10T04:18:11.000Z | include/reduction/ConnectedComponentSeparator.hpp | sgraf812/pbqp-papa | b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07 | [
"MIT"
] | null | null | null | include/reduction/ConnectedComponentSeparator.hpp | sgraf812/pbqp-papa | b5ae6fcb0842cb66956cccc4663f6fd9e6f6ae07 | [
"MIT"
] | 1 | 2019-03-07T10:20:50.000Z | 2019-03-07T10:20:50.000Z | #ifndef REDUCTION_CONNECTEDCOMPONENTSEPARATOR_HPP_
#define REDUCTION_CONNECTEDCOMPONENTSEPARATOR_HPP_
#include <vector>
namespace pbqppapa {
template<typename T>
class PBQPGraph;
template<typename T>
class NtoNDependentSolution;
template<typename T>
class NodeConsistentReduction;
template<typename T>
class PBQPNode;
template<typename T>
class PBQP_Reduction;
/**
* Splits up a graph into its connected components by putting each of them into their own graph instance
*/
template<typename T>
class ConnectedComponentSeparator: public PBQP_Reduction<T> {
public:
ConnectedComponentSeparator(PBQPGraph<T>* graph) :
PBQP_Reduction<T>(graph) {
}
~ConnectedComponentSeparator() {
}
std::vector<PBQPGraph<T>*>& reduce() override {
while (true) {
std::set<PBQPNode<T>*> foundNodes = std::set<PBQPNode<T>*>();
std::vector<PBQPNode<T>*> todoStack = std::vector<PBQPNode<T>*>();
if (this->graph->getNodeCount() > 0) {
auto iter = this->graph->getNodeBegin();
todoStack.push_back(*iter);
}
while (!todoStack.empty()) {
PBQPNode<T>* node = todoStack.back();
todoStack.pop_back();
if (foundNodes.count(node) > 0) {
continue;
}
foundNodes.insert(node);
for (PBQPNode<T>* adjacentNode : node->getAdjacentNodes()) {
if (foundNodes.count(adjacentNode) == 0) {
todoStack.push_back(adjacentNode);
}
}
}
if (foundNodes.size() == this->graph->getNodeCount()) {
//only one connected component
this->result.push_back(this->graph);
break;
} else {
//multiple connected components in this graph, so we remove the one we found and keep going
//TODO Removing the part of the original graph that is not in this component would make more sense
//as we're more likely to find the bigger components when randomly picking a node
//That way we'd have to do another log(n) lookup for every node in the original graph though
PBQPGraph<T>* replacementGraph = new PBQPGraph<T>();
for (PBQPNode<T>* node : foundNodes) {
this->graph->removeNode(node, false);
replacementGraph->addNode(node);
for (PBQPEdge<T>* edge : node->getAdjacentEdges(true)) {
//makes us iterate only over outgoing edges, so we can always insert all of those safely
//while ensuring that every edge is inserted once. We dont need to remove the edge from the
//old graph as removing the node already does that
replacementGraph->addEdge(edge);
}
}
this->result.push_back(replacementGraph);
}
}
return this->result;
}
void solve(PBQPSolution<T>& solution) override {
//don't need to do anything
}
};
}
#endif /* REDUCTION_CONNECTEDCOMPONENTSEPARATOR_HPP_ */
| 30.258427 | 104 | 0.70182 | sgraf812 |
447f0953dcc0c2faa714220a28f2150597542027 | 3,051 | hpp | C++ | libs/ledger/include/ledger/genesis_loading/genesis_file_creator.hpp | chr15murray/ledger | 85be05221f19598de8c6c58652139a1f2d9e362f | [
"Apache-2.0"
] | 96 | 2018-08-23T16:49:05.000Z | 2021-11-25T00:47:16.000Z | libs/ledger/include/ledger/genesis_loading/genesis_file_creator.hpp | chr15murray/ledger | 85be05221f19598de8c6c58652139a1f2d9e362f | [
"Apache-2.0"
] | 1,011 | 2018-08-17T12:25:21.000Z | 2021-11-18T09:30:19.000Z | libs/ledger/include/ledger/genesis_loading/genesis_file_creator.hpp | chr15murray/ledger | 85be05221f19598de8c6c58652139a1f2d9e362f | [
"Apache-2.0"
] | 65 | 2018-08-20T20:05:40.000Z | 2022-02-26T23:54:35.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 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 "core/byte_array/byte_array.hpp"
#include "ledger/chain/block.hpp"
#include "ledger/chain/main_chain.hpp"
#include "ledger/consensus/consensus.hpp"
#include "ledger/consensus/consensus_interface.hpp"
#include "storage/object_store.hpp"
#include <string>
namespace fetch {
namespace variant {
class Variant;
}
namespace ledger {
class BlockCoordinator;
class StorageUnitInterface;
class StakeSnapshot;
class GenesisFileCreator
{
public:
using ConsensusPtr = std::shared_ptr<fetch::ledger::ConsensusInterface>;
using ByteArray = byte_array::ByteArray;
using ConstByteArray = byte_array::ConstByteArray;
using CertificatePtr = std::shared_ptr<crypto::Prover>;
using GenesisStore = fetch::storage::ObjectStore<Block>;
using MainChain = ledger::MainChain;
using StakeSnapshotPtr = std::shared_ptr<StakeSnapshot>;
enum class Result
{
FAILURE = 0,
LOADED_PREVIOUS_GENESIS,
CREATED_NEW_GENESIS
};
struct ConsensusParameters
{
uint16_t cabinet_size{0};
uint64_t start_time{0};
StakeSnapshotPtr snapshot{};
beacon::BlockEntropy::Cabinet whitelist;
};
// Construction / Destruction
GenesisFileCreator(StorageUnitInterface &storage_unit, CertificatePtr certificate,
std::string const &db_prefix);
GenesisFileCreator(GenesisFileCreator const &) = delete;
GenesisFileCreator(GenesisFileCreator &&) = delete;
~GenesisFileCreator() = default;
Result LoadContents(ConstByteArray const &contents, bool proof_of_stake,
ConsensusParameters ¶ms);
// Operators
GenesisFileCreator &operator=(GenesisFileCreator const &) = delete;
GenesisFileCreator &operator=(GenesisFileCreator &&) = delete;
private:
bool LoadState(variant::Variant const &object, ConsensusParameters const *consensus = nullptr);
bool LoadConsensus(variant::Variant const &object, ConsensusParameters ¶ms);
CertificatePtr certificate_;
StorageUnitInterface &storage_unit_;
GenesisStore genesis_store_;
Block genesis_block_;
std::string db_name_;
};
} // namespace ledger
} // namespace fetch
| 32.806452 | 97 | 0.670272 | chr15murray |
4480c8257aaa266ea705845623a27860f0510618 | 4,280 | cpp | C++ | kernel/src/memory/heap.cpp | JoannaHammond/JOS | 642a78efd40b1cf994da837bf9a31eb62cefee0b | [
"Unlicense"
] | 1 | 2021-04-14T17:31:16.000Z | 2021-04-14T17:31:16.000Z | kernel/src/memory/heap.cpp | JoannaHammond/JOS | 642a78efd40b1cf994da837bf9a31eb62cefee0b | [
"Unlicense"
] | null | null | null | kernel/src/memory/heap.cpp | JoannaHammond/JOS | 642a78efd40b1cf994da837bf9a31eb62cefee0b | [
"Unlicense"
] | 1 | 2021-04-17T17:39:26.000Z | 2021-04-17T17:39:26.000Z | #include "heap.h"
#include "../paging/PageTableManager.h"
#include "../paging/PageFrameAllocator.h"
void* heapStart;
void* heapEnd;
HeapSegHdr* LastHdr;
void InitializeHeap(void* heapAddress, size_t pageCount){
void* pos = heapAddress;
for (size_t i = 0; i < pageCount; i++){
void* newPage = GlobalAllocator.RequestPage();
g_PageTableManager.MapMemory(pos, newPage);
pos = (void*)((size_t)pos + 0x1000);
}
size_t heapLength = pageCount * 0x1000;
heapStart = heapAddress;
heapEnd = (void*)((size_t)heapStart + heapLength);
HeapSegHdr* startSeg = (HeapSegHdr*)heapAddress;
startSeg->length = heapLength - sizeof(HeapSegHdr);
startSeg->next = NULL;
startSeg->last = NULL;
startSeg->free = true;
LastHdr = startSeg;
}
void free(void* address, long unsigned int i)
{
free(address);
}
void free(void* address){
//GlobalRenderer->Println("FREE Heap");
HeapSegHdr* segment = (HeapSegHdr*)address - 1;
segment->free = true;
segment->CombineForward();
segment->CombineBackward();
}
void* malloc(size_t size){
//GlobalRenderer->Println("MALLOC Heap");
if (size % 0x10 > 0){ // it is not a multiple of 0x10
size -= (size % 0x10);
size += 0x10;
}
if (size == 0) return NULL;
HeapSegHdr* currentSeg = (HeapSegHdr*) heapStart;
while(true){
if(currentSeg->free){
if (currentSeg->length > size){
currentSeg->Split(size);
currentSeg->free = false;
return (void*)((uint64_t)currentSeg + sizeof(HeapSegHdr));
}
if (currentSeg->length == size){
currentSeg->free = false;
return (void*)((uint64_t)currentSeg + sizeof(HeapSegHdr));
}
}
if (currentSeg->next == NULL) break;
currentSeg = currentSeg->next;
}
//GlobalRenderer->Println("Expanding Heap");
ExpandHeap(size);
return malloc(size);
}
HeapSegHdr* HeapSegHdr::Split(size_t splitLength){
//GlobalRenderer->Println("SPLIT Heap");
if (splitLength < 0x10) return NULL;
int64_t splitSegLength = length - splitLength - (sizeof(HeapSegHdr));
if (splitSegLength < 0x10) return NULL;
HeapSegHdr* newSplitHdr = (HeapSegHdr*) ((size_t)this + splitLength + sizeof(HeapSegHdr));
if(next != NULL)
next->last = newSplitHdr; // Set the next segment's last segment to our new segment
newSplitHdr->next = next; // Set the new segment's next segment to out original next segment
next = newSplitHdr; // Set our new segment to the new segment
newSplitHdr->last = this; // Set our new segment's last segment to the current segment
newSplitHdr->length = splitSegLength; // Set the new header's length to the calculated value
newSplitHdr->free = free; // make sure the new segment's free is the same as the original
length = splitLength; // set the length of the original segment to its new length
if (LastHdr == this) LastHdr = newSplitHdr;
return newSplitHdr;
}
void ExpandHeap(size_t length){
//GlobalRenderer->Println("EXPAND Heap");
if (length % 0x1000) {
length -= length % 0x1000;
length += 0x1000;
}
size_t pageCount = length / 0x1000;
HeapSegHdr* newSegment = (HeapSegHdr*)heapEnd;
for (size_t i = 0; i < pageCount; i++){
void* newPage = GlobalAllocator.RequestPage();
g_PageTableManager.MapMemory(heapEnd, newPage);
heapEnd = (void*)((size_t)heapEnd + 0x1000 );
}
newSegment->free = true;
newSegment->last = LastHdr;
LastHdr->next = newSegment;
LastHdr = newSegment;
newSegment->next = NULL;
newSegment->length = length - sizeof(HeapSegHdr);
newSegment->CombineBackward();
}
void HeapSegHdr::CombineForward(){
//GlobalRenderer->Println("CFWD Heap");
if (next == NULL) return;
if (!next->free) return;
if (next == LastHdr) LastHdr = this;
if (next->next != NULL){
next->next->last = this;
}
length = length + next->length + sizeof(HeapSegHdr);
next = next->next;
}
void HeapSegHdr::CombineBackward(){
//GlobalRenderer->Println("CBKWD Heap");
if (last != NULL && last->free) last->CombineForward();
}
| 29.517241 | 96 | 0.631075 | JoannaHammond |
44837499b3710751c33f4a1a261cca171ae424fb | 1,365 | hpp | C++ | addons/cbrn/CfgWeapons.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 1 | 2020-06-07T00:45:49.000Z | 2020-06-07T00:45:49.000Z | addons/cbrn/CfgWeapons.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 27 | 2020-05-24T11:09:56.000Z | 2020-05-25T12:28:10.000Z | addons/cbrn/CfgWeapons.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 2 | 2020-05-31T08:52:45.000Z | 2021-04-16T23:16:37.000Z |
class CfgWeapons {
class UniformItem;
class Uniform_Base;
class HelmetBase;
class H_HelmetB;
class JSHK_contam_suit_base: Uniform_Base {
GVAR(protectedParts[]) = {"body"};
};
class U_C_CBRN_Suit_01_Blue_F: Uniform_Base {
GVAR(protectedParts[]) = {"head", "body"};
};
class U_C_CBRN_Suit_01_White_F: Uniform_Base {
GVAR(protectedParts[]) = {"head", "body"};
};
class U_B_CBRN_Suit_01_MTP_F: Uniform_Base {
GVAR(protectedParts[]) = {"head", "body"};
};
class U_B_CBRN_Suit_01_Tropic_F: Uniform_Base {
GVAR(protectedParts[]) = {"head", "body"};
};
class U_B_CBRN_Suit_01_Wdl_F: Uniform_Base {
GVAR(protectedParts[]) = {"head", "body"};
};
class U_I_CBRN_Suit_01_AAF_F: Uniform_Base {
GVAR(protectedParts[]) = {"head", "body"};
};
class U_I_E_CBRN_Suit_01_EAF_F: Uniform_Base {
GVAR(protectedParts[]) = {"head", "body"};
};
class H_PilotHelmetFighter_B: H_HelmetB {
GVAR(airFilter) = 3;
GVAR(protectedParts[]) = {"face"};
};
class H_Shemag_khk: HelmetBase {
GVAR(airFilter) = 1;
};
class H_ShemagOpen_khk: HelmetBase {
GVAR(airFilter) = 1;
};
class H_HelmetO_ViperSP_hex_F: H_HelmetB {
GVAR(airFilter) = 3;
GVAR(protectedParts[]) = {"face", "head"};
};
};
| 29.673913 | 51 | 0.611722 | Krzyciu |
44861c1209a64ea77e8f89461e7e84a410045428 | 2,423 | hpp | C++ | src/irc/iid.hpp | lep/biboumi | ba4fcbb68efdf34d173b0bc475d30e6dcbdb9553 | [
"Zlib"
] | null | null | null | src/irc/iid.hpp | lep/biboumi | ba4fcbb68efdf34d173b0bc475d30e6dcbdb9553 | [
"Zlib"
] | null | null | null | src/irc/iid.hpp | lep/biboumi | ba4fcbb68efdf34d173b0bc475d30e6dcbdb9553 | [
"Zlib"
] | null | null | null | #pragma once
#include <string>
#include <set>
class Bridge;
/**
* A name representing an IRC channel on an IRC server, or an IRC user on an
* IRC server, or just an IRC server.
*
* The separator is '%' between the local part (nickname or channel) and the
* server part. If no separator is present, it's just an irc server.
* If it is present, the first character of the local part determines if it’s
* a channel or a user: ff the local part is empty or if its first character
* is part of the chantypes characters, then it’s a channel, otherwise it’s
* a user.
*
* It’s possible to have an empty-string server, but it makes no sense in
* biboumi’s context.
*
* Assuming the chantypes are '#' and '&':
*
* #test%irc.example.org has :
* - local: "#test" (the # is part of the name, it could very well be absent, or & (for example) instead)
* - server: "irc.example.org"
* - type: channel
*
* %irc.example.org:
* - local: ""
* - server: "irc.example.org"
* - type: channel
* Note: this is the special empty-string channel, used internally in biboumi
* but has no meaning on IRC.
*
* foo%irc.example.org
* - local: "foo"
* - server: "irc.example.org"
* - type: user
* Note: the empty-string user (!irc.example.org) makes no sense for biboumi
*
* irc.example.org:
* - local: ""
* - server: "irc.example.org"
* - type: server
*/
class Iid
{
public:
enum class Type
{
Channel,
User,
Server,
};
static constexpr char separator[]{"%"};
Iid(const std::string& iid, const std::set<char>& chantypes);
Iid(const std::string& iid, const std::initializer_list<char>& chantypes);
Iid(const std::string& iid, const Bridge* bridge);
Iid(const std::string& local, const std::string& server, Type type);
Iid() = default;
Iid(const Iid&) = default;
Iid(Iid&&) = delete;
Iid& operator=(const Iid&) = delete;
Iid& operator=(Iid&&) = delete;
void set_local(const std::string& loc);
void set_server(const std::string& serv);
const std::string& get_local() const;
const std::string get_encoded_local() const;
const std::string& get_server() const;
std::tuple<std::string, std::string> to_tuple() const;
Type type { Type::Server };
private:
void init(const std::string& iid);
void set_type(const std::set<char>& chantypes);
std::string local;
std::string server;
};
namespace std {
const std::string to_string(const Iid& iid);
}
| 25.776596 | 105 | 0.664466 | lep |
449185edf2aca3b2cc70313f0ce4768edde4e4b6 | 345 | cpp | C++ | problems/adhocs/UVA_Judge_11364.cpp | Riei-Joaquim/ICPC-Library | fe6c652b7d4736f9b279ab0614085f71777c277f | [
"MIT"
] | null | null | null | problems/adhocs/UVA_Judge_11364.cpp | Riei-Joaquim/ICPC-Library | fe6c652b7d4736f9b279ab0614085f71777c277f | [
"MIT"
] | null | null | null | problems/adhocs/UVA_Judge_11364.cpp | Riei-Joaquim/ICPC-Library | fe6c652b7d4736f9b279ab0614085f71777c277f | [
"MIT"
] | 2 | 2021-10-30T01:31:59.000Z | 2021-11-01T02:29:20.000Z | #include<bits/stdc++.h>
using namespace std;
int main(){
int n_cases;
vector<int> p;
int n;
cin >> n_cases;
for(int x = 0; x < n_cases; x++){
cin >> n;
for(int y = 0; y < n; y++){
int aux; cin >> aux;
p.push_back(aux);
}
sort(p.begin(), p.end());
int calc = 2 * (p[n-1] - p[0]);
cout << calc << endl;
p.clear();
}
}
| 15.681818 | 34 | 0.510145 | Riei-Joaquim |
4495ba1ab7a50511d4c204bec8530abd1f07c31d | 4,424 | hpp | C++ | include/VROSC/UI/UIMaterialSettings.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/UI/UIMaterialSettings.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/UI/UIMaterialSettings.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.ScriptableObject
#include "UnityEngine/ScriptableObject.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Material
class Material;
}
// Completed forward declares
// Type namespace: VROSC.UI
namespace VROSC::UI {
// Forward declaring type: UIMaterialSettings
class UIMaterialSettings;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::UI::UIMaterialSettings);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::UI::UIMaterialSettings*, "VROSC.UI", "UIMaterialSettings");
// Type namespace: VROSC.UI
namespace VROSC::UI {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: VROSC.UI.UIMaterialSettings
// [TokenAttribute] Offset: FFFFFFFF
// [CreateAssetMenuAttribute] Offset: 66B048
class UIMaterialSettings : public ::UnityEngine::ScriptableObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// protected UnityEngine.Material _opaqueMaterial
// Size: 0x8
// Offset: 0x18
::UnityEngine::Material* opaqueMaterial;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
// protected UnityEngine.Material _transparentMaterial
// Size: 0x8
// Offset: 0x20
::UnityEngine::Material* transparentMaterial;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: protected UnityEngine.Material _opaqueMaterial
::UnityEngine::Material*& dyn__opaqueMaterial();
// Get instance field reference: protected UnityEngine.Material _transparentMaterial
::UnityEngine::Material*& dyn__transparentMaterial();
// public UnityEngine.Material GetMaterial(System.Boolean needsTransparency)
// Offset: 0x139F350
::UnityEngine::Material* GetMaterial(bool needsTransparency);
// public System.Void .ctor()
// Offset: 0x139F368
// Implemented from: UnityEngine.ScriptableObject
// Base method: System.Void ScriptableObject::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static UIMaterialSettings* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::UI::UIMaterialSettings::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<UIMaterialSettings*, creationType>()));
}
}; // VROSC.UI.UIMaterialSettings
#pragma pack(pop)
static check_size<sizeof(UIMaterialSettings), 32 + sizeof(::UnityEngine::Material*)> __VROSC_UI_UIMaterialSettingsSizeCheck;
static_assert(sizeof(UIMaterialSettings) == 0x28);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::UI::UIMaterialSettings::GetMaterial
// Il2CppName: GetMaterial
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Material* (VROSC::UI::UIMaterialSettings::*)(bool)>(&VROSC::UI::UIMaterialSettings::GetMaterial)> {
static const MethodInfo* get() {
static auto* needsTransparency = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::UI::UIMaterialSettings*), "GetMaterial", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{needsTransparency});
}
};
// Writing MetadataGetter for method: VROSC::UI::UIMaterialSettings::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 44.24 | 183 | 0.733725 | RedBrumbler |
449b45667ff21f0bfff09f901cf10d0b491a186c | 153 | cpp | C++ | Plugins/Source/WindowsTextureMovie/Private/CodecMovieMp4.cpp | friendsincode/TextureMoviePlugin | e2736d665ae4f4e25084dbb79efe0faeb4cfc2f8 | [
"MIT"
] | 53 | 2015-01-30T13:44:50.000Z | 2021-05-28T04:41:40.000Z | Plugins/Source/WindowsTextureMovie/Private/CodecMovieMp4.cpp | friendsincode/TextureMoviePlugin | e2736d665ae4f4e25084dbb79efe0faeb4cfc2f8 | [
"MIT"
] | null | null | null | Plugins/Source/WindowsTextureMovie/Private/CodecMovieMp4.cpp | friendsincode/TextureMoviePlugin | e2736d665ae4f4e25084dbb79efe0faeb4cfc2f8 | [
"MIT"
] | 31 | 2015-01-18T20:13:44.000Z | 2019-04-02T07:20:53.000Z |
#include "WindowsTextureMoviePrivatePCH.h"
UCodecMovieMp4::UCodecMovieMp4( const class FPostConstructInitializeProperties& PCIP )
: Super( PCIP )
{
}
| 19.125 | 86 | 0.797386 | friendsincode |
449bdd73046060e76f87eedf5c2e14664e391c96 | 23,715 | cpp | C++ | peg_parser/lib/PegParsingExpression.cpp | VayuDev/samal | edb67289b7a1160f917be9bd44cd734f9d865460 | [
"MIT"
] | 2 | 2021-02-26T07:39:08.000Z | 2021-03-30T21:13:47.000Z | peg_parser/lib/PegParsingExpression.cpp | VayuDev/samal | edb67289b7a1160f917be9bd44cd734f9d865460 | [
"MIT"
] | null | null | null | peg_parser/lib/PegParsingExpression.cpp | VayuDev/samal | edb67289b7a1160f917be9bd44cd734f9d865460 | [
"MIT"
] | null | null | null | #include "peg_parser/PegParsingExpression.hpp"
#include "peg_parser/PegTokenizer.hpp"
#include <cassert>
namespace peg {
const std::regex gNextStringRegex{ "^[^ \n\t]*", std::regex::optimize };
std::string ExpressionFailInfo::dump(const PegTokenizer& tokenizer, bool) const {
auto [line, column] = tokenizer.getPosition(mState);
std::string msg;
switch(mReason) {
case ExpressionFailReason::SEQUENCE_CHILD_FAILED:
msg += "\033[36m";
break;
case ExpressionFailReason::CHOICE_NO_CHILD_SUCCEEDED:
msg += "\033[34m";
break;
case ExpressionFailReason::ADDITIONAL_ERROR_MESSAGE:
msg += "\033[31m";
break;
default:
break;
}
msg += "" + std::to_string(line) + ":" + std::to_string(column) + ": " + mSelfDump + " - ";
switch(mReason) {
case ExpressionFailReason::SUCCESS:
msg += "Success!";
break;
case ExpressionFailReason::SEQUENCE_CHILD_FAILED:
msg += "Needed to parse more children - already parsed: '" + mInfo1 + "'. Children failure info:\033[0m";
break;
case ExpressionFailReason::CHOICE_NO_CHILD_SUCCEEDED:
msg += "No possible choice matched. The options were (in order):\033[0m";
break;
case ExpressionFailReason::REQUIRED_ONE_OR_MORE:
msg += "We need to match one or more of the following, but not even one succeeded:";
break;
case ExpressionFailReason::UNMATCHED_REGEX:
msg += "Expected regex '" + mInfo1 + "', got: '" + mInfo2 + "'";
break;
case ExpressionFailReason::UNMATCHED_STRING:
msg += "Expected '" + mInfo1 + "', got: '" + mInfo2 + "'";
break;
case ExpressionFailReason::ADDITIONAL_ERROR_MESSAGE:
msg += mInfo1 + ", got: '" + mInfo2 + "'\033[0m";
break;
case ExpressionFailReason::CALLBACK_THREW_EXCEPTION:
msg += "Exception in callback: " + mInfo1;
break;
case ExpressionFailReason::NOT_CHILD_SUCCEEDED:
msg += "Not failed because child succeeded";
break;
case ExpressionFailReason::AND_CHILD_FAILED:
msg += "And failed because child failed";
break;
default:
assert(false);
}
return msg;
}
SequenceParsingExpression::SequenceParsingExpression(std::vector<sp<ParsingExpression>> children)
: mChildren(std::move(children)) {
}
RuleResult SequenceParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto startState = state;
auto startPtr = tokenizer.getPtr(state);
std::vector<MatchInfo> childrenResults;
std::vector<ExpressionFailInfo> childrenFailReasons;
for(auto& child : mChildren) {
auto childRet = child->match(state, rules, tokenizer);
if(childRet.index() == 0) {
// child matched
state = std::get<0>(childRet).getState();
childrenResults.emplace_back(std::get<0>(childRet).moveMatchInfo());
childrenFailReasons.emplace_back(std::get<0>(childRet).moveFailInfo());
} else {
// child failed
childrenFailReasons.emplace_back(std::move(std::get<1>(childRet)));
return ExpressionFailInfo{
state,
dump(),
ExpressionFailReason::SEQUENCE_CHILD_FAILED,
std::string{ std::string_view(startPtr, tokenizer.getPtr(state) - startPtr) },
"",
std::move(childrenFailReasons)
};
}
}
return ExpressionSuccessInfo{
state,
MatchInfo{
.start = startPtr,
.len = static_cast<size_t>(tokenizer.getPtr(state) - startPtr),
.sourcePosition = tokenizer.getPosition(startState),
.subs = std::move(childrenResults) },
ExpressionFailInfo{ state, dump(), std::move(childrenFailReasons) }
};
}
std::string SequenceParsingExpression::dump() const {
std::string ret;
for(auto it = mChildren.cbegin(); it != mChildren.cend(); it++) {
ret += (*it)->dump();
if(std::next(it) != mChildren.cend()) {
ret += " ";
}
}
return ret;
}
TerminalParsingExpression::TerminalParsingExpression(std::string value)
: mStringRepresentation(std::move(value)) {
}
TerminalParsingExpression::TerminalParsingExpression(std::string stringRep, std::regex value)
: mStringRepresentation(std::move(stringRep)), mRegex(std::move(value)) {
}
RuleResult TerminalParsingExpression::match(ParsingState state, const RuleMap&, const PegTokenizer& tokenizer) const {
auto startState = state;
auto startPtr = tokenizer.getPtr(state);
std::optional<ParsingState> tokenizerRet;
if(mRegex) {
tokenizerRet = tokenizer.matchRegex(state, *mRegex);
} else {
tokenizerRet = tokenizer.matchString(state, mStringRepresentation);
}
if(tokenizerRet) {
return ExpressionSuccessInfo{
*tokenizerRet,
MatchInfo{
.start = startPtr,
.len = static_cast<size_t>(tokenizer.getPtr(*tokenizerRet) - startPtr),
.sourcePosition = tokenizer.getPosition(startState) },
ExpressionFailInfo{ state, dump() }
};
} else {
state = tokenizer.skipWhitespaces(state);
size_t len = tokenizer.getPtr(*tokenizer.matchRegex(state, gNextStringRegex)) - tokenizer.getPtr(state);
std::string failedString{ std::string_view{ tokenizer.getPtr(state), len } };
return ExpressionFailInfo{
state,
dump(),
mRegex ? ExpressionFailReason::UNMATCHED_REGEX : ExpressionFailReason::UNMATCHED_STRING,
mStringRepresentation,
failedString
};
}
}
std::string TerminalParsingExpression::dump() const {
if(mRegex) {
return mStringRepresentation;
}
return '\'' + mStringRepresentation + '\'';
}
ChoiceParsingExpression::ChoiceParsingExpression(std::vector<sp<ParsingExpression>> children)
: mChildren(std::move(children)) {
}
RuleResult ChoiceParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
std::vector<ExpressionFailInfo> childrenFailReasons;
size_t i = 0;
for(auto& child : mChildren) {
auto childRet = child->match(state, rules, tokenizer);
if(childRet.index() == 0) {
// child matched
std::vector<MatchInfo> subs;
auto start = std::get<0>(childRet).getMatchInfo().start;
auto len = std::get<0>(childRet).getMatchInfo().len;
auto pos = std::get<0>(childRet).getMatchInfo().sourcePosition;
subs.emplace_back(std::get<0>(childRet).moveMatchInfo());
childrenFailReasons.push_back(std::get<0>(childRet).moveFailInfo());
return ExpressionSuccessInfo{
std::get<0>(childRet).getState(),
MatchInfo{
.start = start,
.len = len,
.sourcePosition = pos,
.choice = i,
.subs = std::move(subs) },
ExpressionFailInfo{ state, dump(), std::move(childrenFailReasons) }
};
} else {
childrenFailReasons.emplace_back(std::get<1>(childRet));
}
i++;
}
return ExpressionFailInfo{
state,
dump(),
ExpressionFailReason::CHOICE_NO_CHILD_SUCCEEDED,
std::move(childrenFailReasons)
};
}
std::string ChoiceParsingExpression::dump() const {
std::string ret = "(";
for(auto it = mChildren.cbegin(); it != mChildren.cend(); it++) {
ret += (*it)->dump();
if(std::next(it) != mChildren.cend()) {
ret += " | ";
}
}
ret += ')';
return ret;
}
NotParsingExpression::NotParsingExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult NotParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto childResult = mChild->match(state, rules, tokenizer);
std::vector<MatchInfo> subs;
if(childResult.index() == 0) {
// child success
return ExpressionFailInfo{state, dump(), ExpressionFailReason::NOT_CHILD_SUCCEEDED, { std::get<ExpressionSuccessInfo>(childResult).moveFailInfo() }};
}
// child failure
return ExpressionSuccessInfo{
state,
MatchInfo{
.start = tokenizer.getPtr(state),
.len = 0,
.sourcePosition = tokenizer.getPosition(state)},
ExpressionFailInfo{ state, dump(), { std::get<ExpressionFailInfo>(childResult) } }
};
}
std::string NotParsingExpression::dump() const {
return "!" + mChild->dump();
}
AndParsingExpression::AndParsingExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult AndParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto childResult = mChild->match(state, rules, tokenizer);
std::vector<MatchInfo> subs;
if(childResult.index() == 0) {
// child success
subs.emplace_back(std::move(std::get<ExpressionSuccessInfo>(childResult).moveMatchInfo()));
return ExpressionSuccessInfo{
state,
MatchInfo{
.start = tokenizer.getPtr(state),
.len = 0,
.sourcePosition = tokenizer.getPosition(state),
.subs = std::move(subs)},
ExpressionFailInfo{ state, dump(), { std::get<ExpressionSuccessInfo>(childResult).moveFailInfo() } }
};
}
// child failure
return ExpressionFailInfo{state, dump(), ExpressionFailReason::AND_CHILD_FAILED, { std::get<ExpressionFailInfo>(childResult) }};
}
std::string AndParsingExpression::dump() const {
return "&" + mChild->dump();
}
NonTerminalParsingExpression::NonTerminalParsingExpression(std::string value)
: mNonTerminal(std::move(value)) {
}
RuleResult NonTerminalParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto startState = state;
auto startPtr = tokenizer.getPtr(state);
auto maybeRule = rules.find(mNonTerminal);
if(maybeRule == rules.end()) {
if(mNonTerminal == "BUILTIN_ANY_UTF8_CODEPOINT") {
auto decodedValue = decodeUTF8Codepoint(std::string_view{ tokenizer.getPtr(state), tokenizer.getRemainingBytesCount(state) });
if(!decodedValue) {
return ExpressionFailInfo{
state,
dump(),
ExpressionFailReason::UNMATCHED_STRING,
"<any unicode string>"
};
}
return ExpressionSuccessInfo{
state.advance(decodedValue->len),
MatchInfo{ .start = startPtr, .len = decodedValue->len, .sourcePosition = tokenizer.getPosition(startState), .result = Any::create<int32_t>(std::move(decodedValue->utf32Value)), .subs = {} },
ExpressionFailInfo{state, dump()} };
}
throw std::runtime_error{"No rule found for nonterminal '" + mNonTerminal + "'"};
}
auto& rule = maybeRule->second;
auto ruleRetValue = rule.expr->match(state, rules, tokenizer);
if(ruleRetValue.index() == 1) {
// error in child
return ruleRetValue;
}
Any callbackResult;
if(rule.callback) {
try {
callbackResult = rule.callback(std::get<0>(ruleRetValue).getMatchInfoMut());
} catch(std::exception& e) {
return ExpressionFailInfo{
std::get<0>(ruleRetValue).getState(),
dump(),
ExpressionFailReason::CALLBACK_THREW_EXCEPTION,
e.what()
};
}
}
auto len = static_cast<size_t>(tokenizer.getPtr(std::get<0>(ruleRetValue).getState()) - startPtr);
std::vector<MatchInfo> subs;
subs.emplace_back(std::get<0>(ruleRetValue).moveMatchInfo());
return ExpressionSuccessInfo{ std::get<0>(ruleRetValue).getState(), MatchInfo{ .start = startPtr, .len = len, .sourcePosition = tokenizer.getPosition(startState), .result = std::move(callbackResult), .subs = std::move(subs) }, std::get<0>(ruleRetValue).moveFailInfo() };
}
std::string NonTerminalParsingExpression::dump() const {
return mNonTerminal;
}
OptionalParsingExpression::OptionalParsingExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult OptionalParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto startState = state;
auto childRet = mChild->match(state, rules, tokenizer);
if(childRet.index() == 1) {
// error
return ExpressionSuccessInfo{ state, MatchInfo{
.start = tokenizer.getPtr(startState),
.len = 0,
.sourcePosition = tokenizer.getPosition(state),
},
ExpressionFailInfo{ state, dump(), { std::move(std::get<1>(childRet)) } } };
}
// success
state = std::get<0>(childRet).getState();
std::vector<MatchInfo> subs;
subs.emplace_back(std::get<0>(childRet).moveMatchInfo());
return ExpressionSuccessInfo{ state, MatchInfo{ .start = tokenizer.getPtr(startState), .len = static_cast<size_t>(tokenizer.getPtr(state) - tokenizer.getPtr(startState)), .sourcePosition = tokenizer.getPosition(startState), .subs = std::move(subs) }, ExpressionFailInfo{ state, dump(), { std::get<0>(childRet).moveFailInfo() } } };
assert(false);
}
std::string OptionalParsingExpression::dump() const {
return "(" + mChild->dump() + ")?";
}
OneOrMoreParsingExpression::OneOrMoreParsingExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult OneOrMoreParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto startState = state;
auto startPtr = tokenizer.getPtr(state);
auto childRet = mChild->match(state, rules, tokenizer);
if(childRet.index() == 1) {
// error
return ExpressionFailInfo{ state, dump(), ExpressionFailReason::REQUIRED_ONE_OR_MORE, { std::get<1>(childRet) } };
}
// success
state = std::get<0>(childRet).getState();
std::vector<MatchInfo> childrenResults;
std::vector<ExpressionFailInfo> childrenFailReasons;
childrenResults.emplace_back(std::get<0>(childRet).moveMatchInfo());
childrenFailReasons.emplace_back(std::get<0>(childRet).moveFailInfo());
while(true) {
childRet = mChild->match(state, rules, tokenizer);
if(childRet.index() == 1) {
childrenFailReasons.emplace_back(std::move(std::get<1>(childRet)));
break;
}
childrenResults.emplace_back(std::get<0>(childRet).moveMatchInfo());
childrenFailReasons.emplace_back(std::get<0>(childRet).moveFailInfo());
state = std::get<0>(childRet).getState();
}
return ExpressionSuccessInfo{ state, MatchInfo{ .start = startPtr, .len = static_cast<size_t>(tokenizer.getPtr(state) - startPtr), .sourcePosition = tokenizer.getPosition(startState), .subs = std::move(childrenResults) }, ExpressionFailInfo{ state, dump(), std::move(childrenFailReasons) } };
}
std::string OneOrMoreParsingExpression::dump() const {
return "(" + mChild->dump() + ")+";
}
ZeroOrMoreParsingExpression::ZeroOrMoreParsingExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult ZeroOrMoreParsingExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto startState = state;
auto startPtr = tokenizer.getPtr(state);
std::vector<MatchInfo> childrenResults;
std::vector<ExpressionFailInfo> childrenFailReasons;
while(true) {
auto childRet = mChild->match(state, rules, tokenizer);
if(childRet.index() == 1) {
childrenFailReasons.emplace_back(std::move(std::get<1>(childRet)));
break;
}
childrenResults.emplace_back(std::get<0>(childRet).moveMatchInfo());
childrenFailReasons.emplace_back(std::get<0>(childRet).moveFailInfo());
state = std::get<0>(childRet).getState();
}
return ExpressionSuccessInfo{ state, MatchInfo{ .start = startPtr, .len = static_cast<size_t>(tokenizer.getPtr(state) - startPtr), .sourcePosition = tokenizer.getPosition(startState), .subs = std::move(childrenResults) }, ExpressionFailInfo{ state, dump(), std::move(childrenFailReasons) } };
}
std::string ZeroOrMoreParsingExpression::dump() const {
return "(" + mChild->dump() + ")*";
}
ErrorMessageInfoExpression::ErrorMessageInfoExpression(sp<ParsingExpression> child, std::string error)
: mChild(std::move(child)), mErrorMsg(std::move(error)) {
}
RuleResult ErrorMessageInfoExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
auto childRes = mChild->match(state, rules, tokenizer);
if(childRes.index() == 0) {
return childRes;
}
state = tokenizer.skipWhitespaces(state);
size_t len = tokenizer.getPtr(*tokenizer.matchRegex(state, gNextStringRegex)) - tokenizer.getPtr(state);
std::string failedString{ std::string_view{ tokenizer.getPtr(state), len } };
return ExpressionFailInfo{
state,
mChild->dump(),
ExpressionFailReason::ADDITIONAL_ERROR_MESSAGE,
mErrorMsg,
std::move(failedString),
{ std::move(std::get<1>(childRes)) }
};
}
std::string ErrorMessageInfoExpression::dump() const {
return mChild->dump() + " #" + mErrorMsg + "#";
}
SkipWhitespacesExpression::SkipWhitespacesExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult SkipWhitespacesExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
state = tokenizer.skipWhitespaces(state);
return mChild->match(state, rules, tokenizer);
}
std::string SkipWhitespacesExpression::dump() const {
return mChild->dump();
}
DoNotSkipWhitespacesExpression::DoNotSkipWhitespacesExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult DoNotSkipWhitespacesExpression::match(ParsingState state, const RuleMap& rules, const PegTokenizer& tokenizer) const {
return mChild->match(state, rules, tokenizer);
}
std::string DoNotSkipWhitespacesExpression::dump() const {
return "~nws~(" + mChild->dump() + ")";
}
ForceSkippingWhitespacesExpression::ForceSkippingWhitespacesExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult ForceSkippingWhitespacesExpression::match(ParsingState state,
const RuleMap& rules,
const PegTokenizer& tokenizer) const {
auto newState = tokenizer.skipWhitespaces(state);
if(newState == state) {
return ExpressionFailInfo{ state, dump(), ExpressionFailReason::REQUIRED_WHITESPACES, std::vector<ExpressionFailInfo>{} };
}
return mChild->match(newState, rules, tokenizer);
}
std::string ForceSkippingWhitespacesExpression::dump() const {
return "~fws~(" + mChild->dump() + ")";
}
SkipWhitespacesNoNewlinesExpression::SkipWhitespacesNoNewlinesExpression(sp<ParsingExpression> child)
: mChild(std::move(child)) {
}
RuleResult SkipWhitespacesNoNewlinesExpression::match(ParsingState state,
const RuleMap& rules,
const PegTokenizer& tokenizer) const {
state = tokenizer.skipWhitespaces(state, false);
return mChild->match(state, rules, tokenizer);
}
std::string SkipWhitespacesNoNewlinesExpression::dump() const {
return "~snn~(" + mChild->dump() + ")";
}
class ErrorTree {
public:
ErrorTree(wp<ErrorTree> parent, const ExpressionFailInfo& sourceNode)
: mParent(std::move(parent)), mSourceNode(sourceNode) {
}
void attach(sp<ErrorTree>&& child) {
mChildren.emplace_back(std::move(child));
}
[[nodiscard]] const auto& getChildren() const {
return mChildren;
}
[[nodiscard]] auto& getChildren() {
return mChildren;
}
[[nodiscard]] auto getParent() const {
return mParent;
}
[[nodiscard]] const auto& getSourceNode() const {
return mSourceNode;
}
[[nodiscard]] std::string dump(const PegTokenizer& tok, size_t depth) const {
std::string ret = dumpSelf(tok, depth, false);
for(const auto& child : mChildren) {
ret += child->dump(tok, depth + 1);
}
return ret;
}
[[nodiscard]] std::string dumpReverse(const PegTokenizer& tok, size_t depth, size_t maxDepth) const {
if(depth >= maxDepth) {
return "";
}
std::string ret;
for(const auto& child : mChildren) {
assert(depth > 0);
ret += child->dumpSelf(tok, depth - 1, true);
}
ret += mParent.lock()->dumpReverse(tok, depth + 1, maxDepth);
return ret;
}
private:
[[nodiscard]] std::string dumpSelf(const PegTokenizer& tok, size_t depth, bool revOrder) const {
std::string ret;
for(size_t i = 0; i < depth; ++i) {
ret += " ";
}
ret += mSourceNode.dump(tok, revOrder);
ret += "\n";
return ret;
}
std::vector<sp<ErrorTree>> mChildren;
wp<ErrorTree> mParent;
const ExpressionFailInfo& mSourceNode;
};
sp<ErrorTree> createErrorTree(const ExpressionFailInfo& info, const PegTokenizer& tokenizer, wp<ErrorTree> parent) {
auto tree = std::make_shared<ErrorTree>(parent, info);
for(const auto& child : info.mSubExprFailInfo) {
tree->attach(createErrorTree(child, tokenizer, tree));
}
return tree;
}
std::string errorsToString(const ParsingFailInfo& info, const PegTokenizer& tokenizer) {
auto tree = createErrorTree(*info.error, tokenizer, wp<ErrorTree>{});
/*
// walk to the last node in the tree
sp<ErrorTree> lastNode = tree;
while(lastNode) {
if(lastNode->getChildren().empty()) {
break;
} else {
lastNode = lastNode->getChildren().at(lastNode->getChildren().size() - 1);
}
}
size_t stepsToSuccess = 0;
assert(lastNode);
// walk up from the last node until we encounter something like Success or an additional error
sp<ErrorTree> lastSuccessNode = lastNode;
while(lastSuccessNode) {
if(lastSuccessNode->getSourceNode().isStoppingPoint()) {
break;
}
auto next = lastSuccessNode->getParent().lock();
if(!next) {
break;
}
lastSuccessNode = next;
stepsToSuccess += 1;
}
assert(lastSuccessNode);*/
size_t lastLine = 0;
sp<ErrorTree> node = tree;
std::function<void(sp<ErrorTree>)> search = [&](sp<ErrorTree> node) {
auto [line, column] = tokenizer.getPosition(node->getSourceNode().getState());
if(line > lastLine) {
lastLine = line;
}
for(auto& child : node->getChildren()) {
search(child);
}
};
search(tree);
std::function<bool(sp<ErrorTree>)> prune = [&](sp<ErrorTree> node) -> bool {
auto [line, column] = tokenizer.getPosition(node->getSourceNode().getState());
for(ssize_t i = node->getChildren().size() - 1; i >= 0; --i) {
if(prune(node->getChildren().at(i))) {
node->getChildren().erase(node->getChildren().cbegin() + i);
}
}
return line != lastLine && node->getChildren().empty();
};
prune(tree);
std::string ret;
if(info.eof) {
ret += "Unexpected EOF\n";
}
ret += tree->dump(tokenizer, 0); // + "\n" + lastNode->dumpReverse(tokenizer, 0, stepsToSuccess);
return ret;
}
} | 40.607877 | 335 | 0.641704 | VayuDev |
449c98399dc948b5a09f4bd221693036bd6e5d49 | 708 | cpp | C++ | plugin_sa/game_sa/CAERadioTrackManager.cpp | Aleksandr-Belousov/plugin-sdk | 5ca5f7d5575ae4138a4f165410a1acf0ae922260 | [
"Zlib"
] | 1 | 2021-08-02T03:07:11.000Z | 2021-08-02T03:07:11.000Z | plugin_sa/game_sa/CAERadioTrackManager.cpp | SteepCheat/plugin-sdk | a17c5d933cb8b06e4959b370092828a6a7aa00ef | [
"Zlib"
] | null | null | null | plugin_sa/game_sa/CAERadioTrackManager.cpp | SteepCheat/plugin-sdk | a17c5d933cb8b06e4959b370092828a6a7aa00ef | [
"Zlib"
] | 3 | 2022-01-05T23:58:55.000Z | 2022-03-03T16:48:08.000Z | /*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CAERadioTrackManager.h"
CAERadioTrackManager &AERadioTrackManager = *(CAERadioTrackManager*)0x8CB6F8;
bool CAERadioTrackManager::IsVehicleRadioActive()
{
return ((bool (__thiscall *)(CAERadioTrackManager *))0x4E9800)(this);
}
char *CAERadioTrackManager::GetRadioStationName(signed char id)
{
return ((char *(__thiscall *)(CAERadioTrackManager *, signed char))0x4E9E10)(this, id);
}
tMusicTrackHistory *CAERadioTrackManager::m_nMusicTrackIndexHistory = (tMusicTrackHistory *)0xB62B40;
| 32.181818 | 101 | 0.771186 | Aleksandr-Belousov |
449df68da39f1201c98e2e1c996d7fd30a32b124 | 3,433 | cpp | C++ | source/cpp/source/Connection.cpp | steve-baker-cradle/juce-end-to-end | 2a8b8f3d458884b3bf8be094d3e0f326bfbdcd53 | [
"Apache-2.0"
] | 28 | 2021-11-10T15:39:38.000Z | 2022-03-26T15:39:32.000Z | source/cpp/source/Connection.cpp | steve-baker-cradle/juce-end-to-end | 2a8b8f3d458884b3bf8be094d3e0f326bfbdcd53 | [
"Apache-2.0"
] | 9 | 2021-11-10T15:55:24.000Z | 2022-03-01T00:06:37.000Z | source/cpp/source/Connection.cpp | steve-baker-cradle/juce-end-to-end | 2a8b8f3d458884b3bf8be094d3e0f326bfbdcd53 | [
"Apache-2.0"
] | 2 | 2021-11-10T15:55:32.000Z | 2021-11-10T15:59:24.000Z | #include "Connection.h"
#include <juce_events/juce_events.h>
#if JUCE_MAC
#include <sys/socket.h>
#endif
namespace
{
#pragma pack(push, 1)
struct Header
{
static constexpr uint32_t magicNumber = 0x30061990;
uint32_t magic = 0;
uint32_t size = 0;
};
#pragma pack(pop)
static_assert (sizeof (Header) == 2 * sizeof (uint32_t), "Expecting header to be 8 bytes");
bool writeBytesToSocket (juce::StreamingSocket & socket, const void * data, int numBytes)
{
while (numBytes > 0)
{
const auto numBytesWritten = socket.write (data, numBytes);
if (numBytesWritten < 0)
return false;
numBytes -= numBytesWritten;
}
return true;
}
}
namespace focusrite::e2e
{
std::shared_ptr<Connection> Connection::create (int port)
{
return std::shared_ptr<Connection> (new Connection (port));
}
Connection::Connection (int port)
: Thread ("Test fixture connection")
, _port (port)
{
}
Connection::~Connection ()
{
closeSocket ();
constexpr int timeoutMs = 1000;
stopThread (timeoutMs);
}
void Connection::start ()
{
startThread ();
}
void Connection::run ()
{
preventSigPipeExceptions ();
const auto connected = _socket.connect ("localhost", _port);
if (! connected)
return;
try
{
while (! threadShouldExit ())
{
Header header;
auto headerBytesRead = _socket.read (&header, sizeof (header), true);
if (headerBytesRead != sizeof (header))
{
closeSocket ();
break;
}
header.magic = juce::ByteOrder::swapIfBigEndian (header.magic);
header.size = juce::ByteOrder::swapIfBigEndian (header.size);
if (header.magic != Header::magicNumber)
{
closeSocket ();
break;
}
juce::MemoryBlock block (header.size);
auto bytesRead = _socket.read (block.getData (), int (header.size), true);
if (bytesRead != int (header.size))
{
closeSocket ();
break;
}
notifyData (block);
}
}
catch (...)
{
}
}
void Connection::send (const juce::MemoryBlock & data)
{
jassert (isConnected ());
Header header {juce::ByteOrder::swapIfBigEndian (Header::magicNumber),
juce::ByteOrder::swapIfBigEndian (uint32_t (data.getSize ()))};
if (! writeBytesToSocket (_socket, &header, sizeof (header)))
{
closeSocket ();
return;
}
if (! writeBytesToSocket (_socket, data.getData (), int (data.getSize ())))
closeSocket ();
}
bool Connection::isConnected () const
{
return _socket.isConnected ();
}
void Connection::closeSocket ()
{
if (_socket.isConnected ())
_socket.close ();
}
void Connection::notifyData (const juce::MemoryBlock & data)
{
juce::MessageManager::callAsync (
[weakSelf = weak_from_this (), data]
{
if (auto connection = weakSelf.lock ())
if (connection->_onDataReceived)
connection->_onDataReceived (data);
});
}
void Connection::preventSigPipeExceptions ()
{
#if JUCE_MAC
auto socketFd = _socket.getRawSocketHandle ();
const int set = 1;
setsockopt (socketFd, SOL_SOCKET, SO_NOSIGPIPE, (void *) &set, sizeof (int));
#endif
}
}
| 21.06135 | 91 | 0.58462 | steve-baker-cradle |
44a8c19ddcc72148c5ea09705cc2cd5967a8fe92 | 9,511 | cpp | C++ | Builds/JuceLibraryCode/modules/juce_gui_basics/positioning/juce_RelativeRectangle.cpp | eriser/CSL | 6f4646369f0c90ea90e2c113374044818ab37ded | [
"BSD-4-Clause-UC"
] | 1 | 2019-10-16T08:54:44.000Z | 2019-10-16T08:54:44.000Z | JuceLibraryCode/modules/juce_gui_basics/positioning/juce_RelativeRectangle.cpp | connerlacy/quneo_demo_lab | 073a81d7fa7fa462e07c7b33de3e982a03a0055c | [
"Unlicense"
] | null | null | null | JuceLibraryCode/modules/juce_gui_basics/positioning/juce_RelativeRectangle.cpp | connerlacy/quneo_demo_lab | 073a81d7fa7fa462e07c7b33de3e982a03a0055c | [
"Unlicense"
] | null | null | null | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
namespace RelativeRectangleHelpers
{
inline void skipComma (String::CharPointerType& s)
{
s = s.findEndOfWhitespace();
if (*s == ',')
++s;
}
static bool dependsOnSymbolsOtherThanThis (const Expression& e)
{
if (e.getType() == Expression::operatorType && e.getSymbolOrFunction() == ".")
return true;
if (e.getType() == Expression::symbolType)
{
switch (RelativeCoordinate::StandardStrings::getTypeOf (e.getSymbolOrFunction()))
{
case RelativeCoordinate::StandardStrings::x:
case RelativeCoordinate::StandardStrings::y:
case RelativeCoordinate::StandardStrings::left:
case RelativeCoordinate::StandardStrings::right:
case RelativeCoordinate::StandardStrings::top:
case RelativeCoordinate::StandardStrings::bottom: return false;
default: break;
}
return true;
}
else
{
for (int i = e.getNumInputs(); --i >= 0;)
if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
return true;
}
return false;
}
}
//==============================================================================
RelativeRectangle::RelativeRectangle()
{
}
RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
: left (left_), right (right_), top (top_), bottom (bottom_)
{
}
RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
: left (rect.getX()),
right (Expression::symbol (RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
top (rect.getY()),
bottom (Expression::symbol (RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
{
}
RelativeRectangle::RelativeRectangle (const String& s)
{
String::CharPointerType text (s.getCharPointer());
left = RelativeCoordinate (Expression::parse (text));
RelativeRectangleHelpers::skipComma (text);
top = RelativeCoordinate (Expression::parse (text));
RelativeRectangleHelpers::skipComma (text);
right = RelativeCoordinate (Expression::parse (text));
RelativeRectangleHelpers::skipComma (text);
bottom = RelativeCoordinate (Expression::parse (text));
}
bool RelativeRectangle::operator== (const RelativeRectangle& other) const noexcept
{
return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
}
bool RelativeRectangle::operator!= (const RelativeRectangle& other) const noexcept
{
return ! operator== (other);
}
//==============================================================================
// An expression context that can evaluate expressions using "this"
class RelativeRectangleLocalScope : public Expression::Scope
{
public:
RelativeRectangleLocalScope (const RelativeRectangle& rect_) : rect (rect_) {}
Expression getSymbolValue (const String& symbol) const
{
switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
{
case RelativeCoordinate::StandardStrings::x:
case RelativeCoordinate::StandardStrings::left: return rect.left.getExpression();
case RelativeCoordinate::StandardStrings::y:
case RelativeCoordinate::StandardStrings::top: return rect.top.getExpression();
case RelativeCoordinate::StandardStrings::right: return rect.right.getExpression();
case RelativeCoordinate::StandardStrings::bottom: return rect.bottom.getExpression();
default: break;
}
return Expression::Scope::getSymbolValue (symbol);
}
private:
const RelativeRectangle& rect;
JUCE_DECLARE_NON_COPYABLE (RelativeRectangleLocalScope);
};
const Rectangle<float> RelativeRectangle::resolve (const Expression::Scope* scope) const
{
if (scope == nullptr)
{
RelativeRectangleLocalScope defaultScope (*this);
return resolve (&defaultScope);
}
else
{
const double l = left.resolve (scope);
const double r = right.resolve (scope);
const double t = top.resolve (scope);
const double b = bottom.resolve (scope);
return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
}
}
void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope)
{
left.moveToAbsolute (newPos.getX(), scope);
right.moveToAbsolute (newPos.getRight(), scope);
top.moveToAbsolute (newPos.getY(), scope);
bottom.moveToAbsolute (newPos.getBottom(), scope);
}
bool RelativeRectangle::isDynamic() const
{
using namespace RelativeRectangleHelpers;
return dependsOnSymbolsOtherThanThis (left.getExpression())
|| dependsOnSymbolsOtherThanThis (right.getExpression())
|| dependsOnSymbolsOtherThanThis (top.getExpression())
|| dependsOnSymbolsOtherThanThis (bottom.getExpression());
}
String RelativeRectangle::toString() const
{
return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
}
void RelativeRectangle::renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope)
{
left = left.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
right = right.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
top = top.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
bottom = bottom.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
}
//==============================================================================
class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
{
public:
RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
: RelativeCoordinatePositionerBase (component_),
rectangle (rectangle_)
{
}
bool registerCoordinates()
{
bool ok = addCoordinate (rectangle.left);
ok = addCoordinate (rectangle.right) && ok;
ok = addCoordinate (rectangle.top) && ok;
ok = addCoordinate (rectangle.bottom) && ok;
return ok;
}
bool isUsingRectangle (const RelativeRectangle& other) const noexcept
{
return rectangle == other;
}
void applyToComponentBounds()
{
for (int i = 4; --i >= 0;)
{
ComponentScope scope (getComponent());
const Rectangle<int> newBounds (rectangle.resolve (&scope).getSmallestIntegerContainer());
if (newBounds == getComponent().getBounds())
return;
getComponent().setBounds (newBounds);
}
jassertfalse; // Seems to be a recursive reference!
}
void applyNewBounds (const Rectangle<int>& newBounds)
{
if (newBounds != getComponent().getBounds())
{
ComponentScope scope (getComponent());
rectangle.moveToAbsolute (newBounds.toFloat(), &scope);
applyToComponentBounds();
}
}
private:
RelativeRectangle rectangle;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
};
void RelativeRectangle::applyToComponent (Component& component) const
{
if (isDynamic())
{
RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
if (current == nullptr || ! current->isUsingRectangle (*this))
{
RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
component.setPositioner (p);
p->apply();
}
}
else
{
component.setPositioner (nullptr);
component.setBounds (resolve (nullptr).getSmallestIntegerContainer());
}
}
| 36.163498 | 138 | 0.609505 | eriser |
44acfcf07bdc183cee6266e62f5f750c3988d2e4 | 9,945 | cpp | C++ | Kernel/Prekernel/init.cpp | densogiaichned/serenity | 99c0b895fed02949b528437d6b450d85befde7a5 | [
"BSD-2-Clause"
] | 2 | 2022-02-16T02:12:38.000Z | 2022-02-20T18:40:41.000Z | Kernel/Prekernel/init.cpp | densogiaichned/serenity | 99c0b895fed02949b528437d6b450d85befde7a5 | [
"BSD-2-Clause"
] | null | null | null | Kernel/Prekernel/init.cpp | densogiaichned/serenity | 99c0b895fed02949b528437d6b450d85befde7a5 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
* Copyright (c) 2021, Liav A. <liavalb@hotmail.co.il>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Types.h>
#include <Kernel/Multiboot.h>
#include <Kernel/PhysicalAddress.h>
#include <Kernel/Prekernel/Prekernel.h>
#include <Kernel/VirtualAddress.h>
#include <LibC/elf.h>
#include <LibELF/Relocation.h>
#if ARCH(I386) || ARCH(X86_64)
# include <Kernel/Arch/x86/ASM_wrapper.h>
# include <Kernel/Arch/x86/CPUID.h>
#endif
// Defined in the linker script
extern size_t __stack_chk_guard;
size_t __stack_chk_guard __attribute__((used));
extern "C" [[noreturn]] void __stack_chk_fail();
extern "C" u8 start_of_prekernel_image[];
extern "C" u8 end_of_prekernel_image[];
extern "C" u8 gdt64ptr[];
extern "C" u16 code64_sel;
extern "C" u64 boot_pml4t[512];
extern "C" u64 boot_pdpt[512];
extern "C" u64 boot_pd0[512];
extern "C" u64 boot_pd0_pts[512 * (MAX_KERNEL_SIZE >> 21 & 0x1ff)];
extern "C" u64 boot_pd_kernel[512];
extern "C" u64 boot_pd_kernel_pt0[512];
extern "C" u64 boot_pd_kernel_image_pts[512 * (MAX_KERNEL_SIZE >> 21 & 0x1ff)];
extern "C" u64 boot_pd_kernel_pt1023[512];
extern "C" char const kernel_cmdline[4096];
extern "C" void reload_cr3();
extern "C" {
multiboot_info_t* multiboot_info_ptr;
}
[[noreturn]] static void halt()
{
asm volatile("hlt");
__builtin_unreachable();
}
void __stack_chk_fail()
{
halt();
}
void __assertion_failed(char const*, char const*, unsigned int, char const*)
{
halt();
}
namespace Kernel {
// boot.S expects these functions to exactly have the following signatures.
// We declare them here to ensure their signatures don't accidentally change.
extern "C" [[noreturn]] void init();
// SerenityOS Pre-Kernel Environment C++ entry point :^)
//
// This is where C++ execution begins, after boot.S transfers control here.
//
u64 generate_secure_seed();
extern "C" [[noreturn]] void init()
{
if (multiboot_info_ptr->mods_count < 1)
halt();
multiboot_module_entry_t* kernel_module = (multiboot_module_entry_t*)(FlatPtr)multiboot_info_ptr->mods_addr;
u8* kernel_image = (u8*)(FlatPtr)kernel_module->start;
// copy the ELF header and program headers because we might end up overwriting them
ElfW(Ehdr) kernel_elf_header = *(ElfW(Ehdr)*)kernel_image;
ElfW(Phdr) kernel_program_headers[16];
if (kernel_elf_header.e_phnum > array_size(kernel_program_headers))
halt();
__builtin_memcpy(kernel_program_headers, kernel_image + kernel_elf_header.e_phoff, sizeof(ElfW(Phdr)) * kernel_elf_header.e_phnum);
FlatPtr kernel_physical_base = 0x200000;
#if ARCH(I386)
FlatPtr default_kernel_load_base = 0xc0200000;
#else
FlatPtr default_kernel_load_base = 0x2000200000;
#endif
FlatPtr kernel_load_base = default_kernel_load_base;
if (__builtin_strstr(kernel_cmdline, "disable_kaslr") == nullptr) {
FlatPtr maximum_offset = (FlatPtr)KERNEL_PD_SIZE - MAX_KERNEL_SIZE - 2 * MiB; // The first 2 MiB are used for mapping the pre-kernel
kernel_load_base += (generate_secure_seed() % maximum_offset);
kernel_load_base &= ~(2 * MiB - 1);
}
FlatPtr kernel_load_end = 0;
for (size_t i = 0; i < kernel_elf_header.e_phnum; i++) {
auto& kernel_program_header = kernel_program_headers[i];
if (kernel_program_header.p_type != PT_LOAD)
continue;
auto start = kernel_load_base + kernel_program_header.p_vaddr;
auto end = start + kernel_program_header.p_memsz;
if (start < (FlatPtr)end_of_prekernel_image)
halt();
if (kernel_physical_base + kernel_program_header.p_paddr < (FlatPtr)end_of_prekernel_image)
halt();
if (end > kernel_load_end)
kernel_load_end = end;
}
// align to 1GB
FlatPtr kernel_mapping_base = kernel_load_base & ~(FlatPtr)0x3fffffff;
VERIFY(kernel_load_base % 0x1000 == 0);
VERIFY(kernel_load_base >= kernel_mapping_base + 0x200000);
#if ARCH(I386)
int pdpt_flags = 0x1;
#else
int pdpt_flags = 0x3;
#endif
boot_pdpt[(kernel_mapping_base >> 30) & 0x1ffu] = (FlatPtr)boot_pd_kernel | pdpt_flags;
boot_pd_kernel[0] = (FlatPtr)boot_pd_kernel_pt0 | 0x3;
for (FlatPtr vaddr = kernel_load_base; vaddr <= kernel_load_end; vaddr += PAGE_SIZE * 512)
boot_pd_kernel[(vaddr - kernel_mapping_base) >> 21] = (FlatPtr)(&boot_pd_kernel_image_pts[(vaddr - kernel_load_base) >> 12]) | 0x3;
__builtin_memset(boot_pd_kernel_pt0, 0, sizeof(boot_pd_kernel_pt0));
VERIFY((size_t)end_of_prekernel_image < array_size(boot_pd_kernel_pt0) * PAGE_SIZE);
/* pseudo-identity map 0M - end_of_prekernel_image */
for (size_t i = 0; i < (FlatPtr)end_of_prekernel_image / PAGE_SIZE; i++)
boot_pd_kernel_pt0[i] = i * PAGE_SIZE | 0x3;
__builtin_memset(boot_pd_kernel_image_pts, 0, sizeof(boot_pd_kernel_image_pts));
for (size_t i = 0; i < kernel_elf_header.e_phnum; i++) {
auto& kernel_program_header = kernel_program_headers[i];
if (kernel_program_header.p_type != PT_LOAD)
continue;
for (FlatPtr offset = 0; offset < kernel_program_header.p_memsz; offset += PAGE_SIZE) {
auto pte_index = ((kernel_load_base & 0x1fffff) + kernel_program_header.p_vaddr + offset) >> 12;
boot_pd_kernel_image_pts[pte_index] = (kernel_physical_base + kernel_program_header.p_paddr + offset) | 0x3;
}
}
boot_pd_kernel[511] = (FlatPtr)boot_pd_kernel_pt1023 | 0x3;
reload_cr3();
for (ssize_t i = kernel_elf_header.e_phnum - 1; i >= 0; i--) {
auto& kernel_program_header = kernel_program_headers[i];
if (kernel_program_header.p_type != PT_LOAD)
continue;
__builtin_memmove((u8*)kernel_load_base + kernel_program_header.p_vaddr, kernel_image + kernel_program_header.p_offset, kernel_program_header.p_filesz);
}
for (ssize_t i = kernel_elf_header.e_phnum - 1; i >= 0; i--) {
auto& kernel_program_header = kernel_program_headers[i];
if (kernel_program_header.p_type != PT_LOAD)
continue;
__builtin_memset((u8*)kernel_load_base + kernel_program_header.p_vaddr + kernel_program_header.p_filesz, 0, kernel_program_header.p_memsz - kernel_program_header.p_filesz);
}
multiboot_info_ptr->mods_count--;
multiboot_info_ptr->mods_addr += sizeof(multiboot_module_entry_t);
auto adjust_by_mapping_base = [kernel_mapping_base](auto ptr) {
return (decltype(ptr))((FlatPtr)ptr + kernel_mapping_base);
};
BootInfo info {};
info.start_of_prekernel_image = (PhysicalPtr)start_of_prekernel_image;
info.end_of_prekernel_image = (PhysicalPtr)end_of_prekernel_image;
info.physical_to_virtual_offset = kernel_load_base - kernel_physical_base;
info.kernel_mapping_base = kernel_mapping_base;
info.kernel_load_base = kernel_load_base;
#if ARCH(X86_64)
info.gdt64ptr = (PhysicalPtr)gdt64ptr;
info.code64_sel = code64_sel;
info.boot_pml4t = (PhysicalPtr)boot_pml4t;
#endif
info.boot_pdpt = (PhysicalPtr)boot_pdpt;
info.boot_pd0 = (PhysicalPtr)boot_pd0;
info.boot_pd_kernel = (PhysicalPtr)boot_pd_kernel;
info.boot_pd_kernel_pt1023 = (FlatPtr)adjust_by_mapping_base(boot_pd_kernel_pt1023);
info.kernel_cmdline = (FlatPtr)adjust_by_mapping_base(kernel_cmdline);
info.multiboot_flags = multiboot_info_ptr->flags;
info.multiboot_memory_map = adjust_by_mapping_base((FlatPtr)multiboot_info_ptr->mmap_addr);
info.multiboot_memory_map_count = multiboot_info_ptr->mmap_length / sizeof(multiboot_memory_map_t);
info.multiboot_modules = adjust_by_mapping_base((FlatPtr)multiboot_info_ptr->mods_addr);
info.multiboot_modules_count = multiboot_info_ptr->mods_count;
if ((multiboot_info_ptr->flags & MULTIBOOT_INFO_FRAMEBUFFER_INFO) != 0) {
info.multiboot_framebuffer_addr = multiboot_info_ptr->framebuffer_addr;
info.multiboot_framebuffer_pitch = multiboot_info_ptr->framebuffer_pitch;
info.multiboot_framebuffer_width = multiboot_info_ptr->framebuffer_width;
info.multiboot_framebuffer_height = multiboot_info_ptr->framebuffer_height;
info.multiboot_framebuffer_bpp = multiboot_info_ptr->framebuffer_bpp;
info.multiboot_framebuffer_type = multiboot_info_ptr->framebuffer_type;
}
asm(
#if ARCH(I386)
"add %0, %%esp"
#else
"mov %0, %%rax\n"
"add %%rax, %%rsp"
#endif
::"g"(kernel_mapping_base)
: "ax");
// unmap the 0-1MB region
for (size_t i = 0; i < 256; i++)
boot_pd0_pts[i] = 0;
// unmap the end_of_prekernel_image - MAX_KERNEL_SIZE region
for (FlatPtr vaddr = (FlatPtr)end_of_prekernel_image; vaddr < MAX_KERNEL_SIZE; vaddr += PAGE_SIZE)
boot_pd0_pts[vaddr >> 12] = 0;
reload_cr3();
ELF::perform_relative_relocations(kernel_load_base);
void (*entry)(BootInfo const&) = (void (*)(BootInfo const&))(kernel_load_base + kernel_elf_header.e_entry);
entry(*adjust_by_mapping_base(&info));
__builtin_unreachable();
}
u64 generate_secure_seed()
{
u32 seed = 0xFEEBDAED;
#if ARCH(I386) || ARCH(X86_64)
CPUID processor_info(0x1);
if (processor_info.edx() & (1 << 4)) // TSC
seed ^= read_tsc();
if (processor_info.ecx() & (1 << 30)) // RDRAND
seed ^= rdrand();
CPUID extended_features(0x7);
if (extended_features.ebx() & (1 << 18)) // RDSEED
seed ^= rdseed();
#else
# warning No native randomness source available for this architecture
#endif
seed ^= multiboot_info_ptr->mods_addr;
seed ^= multiboot_info_ptr->framebuffer_addr;
return seed;
}
// Define some Itanium C++ ABI methods to stop the linker from complaining.
// If we actually call these something has gone horribly wrong
void* __dso_handle __attribute__((visibility("hidden")));
}
| 36.428571 | 180 | 0.712821 | densogiaichned |
44ae2ef0ed9f295400d48e27f25ddf0ab211bb9a | 650 | cpp | C++ | ACM-ICPC/4811.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/4811.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | ACM-ICPC/4811.cpp | KimBoWoon/ACM-ICPC | 146c36999488af9234d73f7b4b0c10d78486604f | [
"MIT"
] | null | null | null | #include <cstdio>
using namespace std;
typedef long long LLONG;
int n;
LLONG dp[61][61];
LLONG split(int w, int h) {
// 메모이제이션
if (dp[w][h]) {
return dp[w][h];
}
// 온전한 알약이 없으면 무조건 쪼개진 것을 먹어야 하기 때문에 한 가지 경우 밖에 없다
if (w == 0) {
return 1;
}
// 하나의 알약을 쪼개 먹는다
dp[w][h] = split(w - 1, h + 1);
// 쪼개진 알약을 먹는다
if (h > 0) {
dp[w][h] += split(w, h - 1);
}
return dp[w][h];
}
int main() {
while (true) {
scanf("%d", &n);
if (n == 0) {
return 0;
}
printf("%lld\n", split(n - 1, 1));
}
} | 15.853659 | 55 | 0.401538 | KimBoWoon |
44af71895fa2eb43d483f72186a3baab7fb606ab | 769 | cc | C++ | src/MissionManager/ComplexMissionItem.cc | uavosky/uavosky-qgroundcontrol | 9a49a206e4fe2d3291c212ae8dadd4d5aa0e3197 | [
"Apache-2.0"
] | 12 | 2020-04-19T17:36:34.000Z | 2022-02-02T01:42:06.000Z | src/MissionManager/ComplexMissionItem.cc | uavosky/uavosky-qgroundcontrol | 9a49a206e4fe2d3291c212ae8dadd4d5aa0e3197 | [
"Apache-2.0"
] | 27 | 2020-04-20T16:33:54.000Z | 2022-03-10T13:57:23.000Z | src/MissionManager/ComplexMissionItem.cc | uavosky/uavosky-qgroundcontrol | 9a49a206e4fe2d3291c212ae8dadd4d5aa0e3197 | [
"Apache-2.0"
] | 39 | 2020-04-18T00:45:45.000Z | 2022-03-21T10:41:46.000Z | /****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "ComplexMissionItem.h"
const char* ComplexMissionItem::jsonComplexItemTypeKey = "complexItemType";
ComplexMissionItem::ComplexMissionItem(Vehicle* vehicle, bool flyView, QObject* parent)
: VisualMissionItem(vehicle, flyView, parent)
{
}
const ComplexMissionItem& ComplexMissionItem::operator=(const ComplexMissionItem& other)
{
VisualMissionItem::operator=(other);
return *this;
}
| 29.576923 | 88 | 0.605982 | uavosky |
44afc320d16169209e93d41d75f75c6e33ed2182 | 782 | cpp | C++ | explore/1514-lpc/eeprom/main.cpp | lispnik/embello | adae98d03f5ac843160e17e490ccc72de81d8be3 | [
"Unlicense"
] | 10 | 2019-10-27T10:31:28.000Z | 2022-03-04T13:55:03.000Z | explore/1514-lpc/eeprom/main.cpp | davidcollins001/embello | 08297eb920e7e8c35df08aa64e91bb01a5c99409 | [
"Unlicense"
] | null | null | null | explore/1514-lpc/eeprom/main.cpp | davidcollins001/embello | 08297eb920e7e8c35df08aa64e91bb01a5c99409 | [
"Unlicense"
] | 7 | 2019-10-27T15:21:01.000Z | 2022-03-04T20:04:44.000Z | // Try out eeprom emulation using upper flash memory.
// see http://jeelabs.org/2015/04/01/emulating-eeprom/
#include "embello.h"
#include <string.h>
#include "flash.h"
#include "romvars.h"
RomVars<Flash64,0x0F80> rom;
int main () {
serial.init(115200);
printf("\n[eeprom]\n");
tick.init(1000);
rom.init();
unsigned i = 0;
while (true) {
int varNum = i++ % 5 + 1;
if (varNum == 1) {
uint16_t v10 = rom[10];
printf("bump #10 to %u\n", ++v10);
rom[10] = v10;
}
uint16_t oldVal = rom[varNum];
uint16_t newVal = tick.millis;
int start = tick.millis;
rom[varNum] = newVal;
int elapsed = tick.millis - start;
printf("#%d: old %-6u new %-6u %d ms\n", varNum, oldVal, newVal, elapsed);
tick.delay(500);
}
}
| 19.073171 | 78 | 0.59335 | lispnik |
44b011334587bb4f9bcca81163dabdf7a6303a27 | 39,659 | cpp | C++ | src/base/propagator/PropagationStateManager.cpp | saichikine/GMAT | 80bde040e12946a61dae90d9fc3538f16df34190 | [
"Apache-2.0"
] | null | null | null | src/base/propagator/PropagationStateManager.cpp | saichikine/GMAT | 80bde040e12946a61dae90d9fc3538f16df34190 | [
"Apache-2.0"
] | null | null | null | src/base/propagator/PropagationStateManager.cpp | saichikine/GMAT | 80bde040e12946a61dae90d9fc3538f16df34190 | [
"Apache-2.0"
] | 1 | 2021-12-05T05:40:15.000Z | 2021-12-05T05:40:15.000Z | //$Id$
//------------------------------------------------------------------------------
// PropagationStateManager
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2018 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: 2008/12/15
//
/**
* Implementation of the PropagationStateManager base class. This is the class
* for state managers used in GMAT's propagation subsystem.
*/
//------------------------------------------------------------------------------
#include "PropagationStateManager.hpp"
#include "GmatBase.hpp"
#include "MessageInterface.hpp"
#include "PropagatorException.hpp"
#include "Rvector.hpp"
#include "Rmatrix.hpp"
#include "RealUtilities.hpp" // for IsNaN() and IsInf()
#include <sstream> // for <<
#include "FormationInterface.hpp" // To allow formation member state updates
//#define DEBUG_STATE_CONSTRUCTION
//#define DUMP_STATE
//#define DEBUG_OBJECT_UPDATES
// When Spacecraft epochs are this close, the PSM will call them identical:
#define IDENTICAL_TIME_TOLERANCE 5.0e-11
//------------------------------------------------------------------------------
// PropagationStateManager(Integer size)
//------------------------------------------------------------------------------
/**
* Default constructor
*
* @param size The size of the (initial) propagation state vector
*/
//------------------------------------------------------------------------------
PropagationStateManager::PropagationStateManager(Integer size) :
StateManager (size),
hasPostSuperpositionMember (false)
{
}
//------------------------------------------------------------------------------
// ~PropagationStateManager()
//------------------------------------------------------------------------------
/**
* Destructor
*/
//------------------------------------------------------------------------------
PropagationStateManager::~PropagationStateManager()
{
}
//------------------------------------------------------------------------------
// PropagationStateManager(const PropagationStateManager& psm)
//------------------------------------------------------------------------------
/**
* Copy constructor
*
* @param psm The state manager that is copied to the new one
*/
//------------------------------------------------------------------------------
PropagationStateManager::
PropagationStateManager(const PropagationStateManager& psm) :
StateManager (psm),
hasPostSuperpositionMember (psm.hasPostSuperpositionMember)
{
}
//------------------------------------------------------------------------------
// PropagationStateManager& operator=(const PropagationStateManager& psm)
//------------------------------------------------------------------------------
/**
* Assignment operator
*
* @param psm The state manager that is copied to this one
*
* @return This PSM configured to match psm
*/
//------------------------------------------------------------------------------
PropagationStateManager&
PropagationStateManager::operator=(const PropagationStateManager& psm)
{
if (this != &psm)
{
StateManager::operator=(psm);
hasPostSuperpositionMember = psm.hasPostSuperpositionMember;
}
return *this;
}
//------------------------------------------------------------------------------
// Integer GetCount(Integer elementType)
//------------------------------------------------------------------------------
/**
* Returns the number of objects that support the specified type
*
* This default version just returns the total number of unique objects managed
* by the StateManager
*
* @param elementType ID for the type of state element that is being queried.
*
* @return The count of the number of objects supporting the type specified
*/
//------------------------------------------------------------------------------
Integer PropagationStateManager::GetCount(Gmat::StateElementId elementType)
{
if (elementType == Gmat::UNKNOWN_STATE)
return StateManager::GetCount(elementType);
Integer count = 0;
GmatBase *obj = NULL;
for (Integer index = 0; index < stateSize; ++index)
{
if (stateMap[index]->elementID == elementType)
{
if (stateMap[index]->object != obj)
{
obj = stateMap[index]->object;
++count;
}
}
}
#ifdef DEBUG_STATE_ACCESS
MessageInterface::ShowMessage("PropagationStateManager::GetCount found "
"%d objects supporting type %d\n", count, elementType);
#endif
return count;
}
//------------------------------------------------------------------------------
// bool SetObject(GmatBase* theObject)
//------------------------------------------------------------------------------
/**
* Adds an object to the prop state manager
*
* @param theObject The reference to the object
*
* @return true on success, false on failure or if the object is already in the
* list
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::SetObject(GmatBase* theObject)
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Setting object %s\n",
theObject->GetName().c_str());
#endif
// Be sure object is not already in the list
if (find(objects.begin(), objects.end(), theObject) != objects.end())
return false; // Could throw here, but that would stop everything
// todo: validate that theObject can be propagated
objects.push_back(theObject);
if (theObject->IsOfType(Gmat::FORMATION))
{
Integer id = theObject->GetParameterID("A1Epoch");
epochIDs.push_back(id);
}
else
{
Integer id = theObject->GetParameterID("Epoch");
if (theObject->GetParameterType(id) != Gmat::REAL_TYPE)
id = theObject->GetParameterID("A1Epoch");
epochIDs.push_back(id);
}
current = theObject;
StringArray *objectProps = new StringArray;
elements[current] = objectProps;
*objectProps = current->GetDefaultPropItems();
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Object set; current points to %s\n",
current->GetName().c_str());
MessageInterface::ShowMessage("Managing %d objects:\n", objects.size());
for (UnsignedInt i = 0; i < objects.size(); ++i)
MessageInterface::ShowMessage(" %2d: %s with %d prop items\n", i,
objects[i]->GetName().c_str(),
objects[i]->GetDefaultPropItems().size());
#endif
return true;
}
//------------------------------------------------------------------------------
// bool SetProperty(std::string propName)
//------------------------------------------------------------------------------
/**
* Identifies a propagation property for the current object
*
* @param propName The name of the property
*
* @return true if the property was saved for the current object; false if not
* (or if there is no current object)
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::SetProperty(std::string propName)
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Entered SetProperty(%s); current = %ld\n",
propName.c_str(), current);
#endif
if (current)
{
// Validate that the property can be propagated
if (current->SetPropItem(propName) == Gmat::UNKNOWN_STATE)
throw PropagatorException(propName
+ " is not a known propagation parameter on "
+ current->GetName());
// Only add it if it is not yet there
if (find(elements[current]->begin(), elements[current]->end(),
propName) == elements[current]->end())
elements[current]->push_back(propName);
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Current property List:\n");
for (StringArray::iterator i = elements[current]->begin();
i != elements[current]->end(); ++i)
MessageInterface::ShowMessage(" %s\n", i->c_str());
#endif
return true;
}
return false;
}
//------------------------------------------------------------------------------
// bool SetProperty(std::string propName, Integer index)
//------------------------------------------------------------------------------
/**
* Identifies a propagation property for an object referenced by index
*
* @param propName The name of the property
* @param index The index of the object that has the property
*
* @return true if the property was saved for the current object; false if not
* (or if there is no current object)
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::SetProperty(std::string propName, Integer index)
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Entered SetProperty(%s, %d)\n",
propName.c_str(), index);
#endif
if ((index < 0) || (index >= (Integer)objects.size()))
throw PropagatorException("Index out of bounds specifying a prop object "
"in a propagation state manager\n");
GmatBase *obj = objects[index];
if (obj)
{
// Validate that the property can be propagated
if (obj->SetPropItem(propName) == Gmat::UNKNOWN_STATE)
throw PropagatorException(propName
+ " is not a known propagation parameter on "
+ obj->GetName());
if (find(elements[obj]->begin(), elements[obj]->end(), propName) ==
elements[obj]->end())
elements[obj]->push_back(propName);
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Current property List:\n");
for (StringArray::iterator i = elements[obj]->begin();
i != elements[obj]->end(); ++i)
MessageInterface::ShowMessage(" %s\n", i->c_str());
#endif
return true;
}
return false;
}
//------------------------------------------------------------------------------
// bool SetProperty(std::string propName, GmatBase *forObject)
//------------------------------------------------------------------------------
/**
* Adds a propagation parameter associated with an object to the state
* definition
*
* @param propName The name of the parameter
* @param forObject The associated object
*
* @return true on success
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::SetProperty(std::string propName,
GmatBase *forObject)
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Entered SetProperty(%s, %s)\n",
propName.c_str(), forObject->GetName().c_str());
#endif
if (find(objects.begin(), objects.end(), forObject) == objects.end())
throw PropagatorException("Prop object " + forObject->GetName() +
" not found in a propagation state manager\n");
if (forObject)
{
// Validate that the property can be propagated
if (forObject->SetPropItem(propName) == Gmat::UNKNOWN_STATE)
throw PropagatorException(propName
+ " is not a known propagation parameter on "
+ forObject->GetName());
if (find(elements[forObject]->begin(), elements[forObject]->end(),
propName) == elements[forObject]->end())
elements[forObject]->push_back(propName);
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Current property List:\n");
for (StringArray::iterator i = elements[forObject]->begin();
i != elements[forObject]->end(); ++i)
MessageInterface::ShowMessage(" %s\n", i->c_str());
#endif
return true;
}
return false;
}
//------------------------------------------------------------------------------
// bool BuildState()
//------------------------------------------------------------------------------
/**
* Collects the data needed and fills in state data
*
* @return true on success
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::BuildState()
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Entered BuildState()\n");
MessageInterface::ShowMessage("StateMap:\n");
for (Integer index = 0; index < stateSize; ++index)
{
MessageInterface::ShowMessage(" %s.%s",
stateMap[index]->objectName.c_str(),
stateMap[index]->elementName.c_str());
}
#endif
// Determine the size of the propagation state vector
stateSize = SortVector();
std::map<std::string,Integer> associateMap;
// Build the associate map
std::string name;
for (Integer index = 0; index < stateSize; ++index)
{
name = stateMap[index]->objectName;
if (associateMap.find(name) == associateMap.end())
associateMap[name] = index;
}
state.SetSize(stateSize);
for (Integer index = 0; index < stateSize; ++index)
{
name = stateMap[index]->objectName;
std::stringstream sel("");
sel << stateMap[index]->subelement;
state.SetElementProperties(index, stateMap[index]->elementID,
name + "." + stateMap[index]->elementName + "." + sel.str(),
associateMap[stateMap[index]->associateName]);
}
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage(
"Propagation state vector has %d elements:\n", stateSize);
StringArray props = state.GetElementDescriptions();
for (Integer index = 0; index < stateSize; ++index)
MessageInterface::ShowMessage(" %d: %s --> associate: %d\n", index,
props[index].c_str(), state.GetAssociateIndex(index));
#endif
#ifdef DUMP_STATE
MapObjectsToVector();
for (Integer i = 0; i < stateSize; ++i)
MessageInterface::ShowMessage("State[%02d] = %.12lf, %s %d\n", i, state[i],
"RefState start =", state.GetAssociateIndex(i));
#endif
return true;
}
//------------------------------------------------------------------------------
// bool MapObjectsToVector()
//------------------------------------------------------------------------------
/**
* Retrieves data from the objects that are to be propagated, and sets those
* data in the propagation state vector
*
* @return true on success, false on failure
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::MapObjectsToVector()
{
#ifdef DEBUG_OBJECT_UPDATES
MessageInterface::ShowMessage("Mapping objects to vector\n");
// Look at state data before
MessageInterface::ShowMessage("O -> V: Real object data before: [");
for (Integer index = 0; index < stateSize; ++index)
if (stateMap[index]->parameterType == Gmat::REAL_TYPE)
MessageInterface::ShowMessage(" %lf ",
(stateMap[index]->object)->GetRealParameter(
stateMap[index]->parameterID));
MessageInterface::ShowMessage("]\n");
#endif
Real value;
// Refresh formation data
for (UnsignedInt i = 0; i < objects.size(); ++i)
{
if (objects[i]->IsOfType(Gmat::FORMATION))
{
// Refresh the formation state data from the formation members
((FormationInterface*)(objects[i]))->UpdateState();
}
}
for (Integer index = 0; index < stateSize; ++index)
{
switch (stateMap[index]->parameterType)
{
case Gmat::REAL_TYPE:
value = stateMap[index]->object->GetRealParameter(
stateMap[index]->parameterID);
if (GmatMathUtil::IsNaN(value))
throw PropagatorException("Value for parameter " +
stateMap[index]->object->GetParameterText(
stateMap[index]->parameterID) + " on object " +
stateMap[index]->object->GetName() +
" is not a number");
if (GmatMathUtil::IsInf(value))
throw PropagatorException("Value for parameter " +
stateMap[index]->object->GetParameterText(
stateMap[index]->parameterID) + " on object " +
stateMap[index]->object->GetName() +
" is infinite");
state[index] = value;
break;
case Gmat::RVECTOR_TYPE:
value = stateMap[index]->object->GetRealParameter(
stateMap[index]->parameterID, stateMap[index]->rowIndex);
if (GmatMathUtil::IsNaN(value))
throw PropagatorException("Value for array parameter " +
stateMap[index]->object->GetParameterText(
stateMap[index]->parameterID) + " on object " +
stateMap[index]->object->GetName() +
" is not a number");
if (GmatMathUtil::IsInf(value))
throw PropagatorException("Value for array parameter " +
stateMap[index]->object->GetParameterText(
stateMap[index]->parameterID) + " on object " +
stateMap[index]->object->GetName() +
" is infinite");
state[index] = value;
break;
case Gmat::RMATRIX_TYPE:
value = stateMap[index]->object->GetRealParameter(
stateMap[index]->parameterID, stateMap[index]->rowIndex,
stateMap[index]->colIndex);
if (GmatMathUtil::IsNaN(value))
throw PropagatorException("Value for array parameter " +
stateMap[index]->object->GetParameterText(
stateMap[index]->parameterID) + " on object " +
stateMap[index]->object->GetName() +
" is not a number");
if (GmatMathUtil::IsInf(value))
throw PropagatorException("Value for array parameter " +
stateMap[index]->object->GetParameterText(
stateMap[index]->parameterID) + " on object " +
stateMap[index]->object->GetName() +
" is infinite");
state[index] = value;
break;
default:
std::stringstream sel("");
sel << stateMap[index]->subelement;
std::string label = stateMap[index]->objectName + "." +
stateMap[index]->elementName + "." + sel.str();
MessageInterface::ShowMessage(
"%s not set; Element type not handled\n",label.c_str());
}
}
// Manage epoch
if (ObjectEpochsMatch() == false)
MessageInterface::ShowMessage("Epochs do not match\n");
if (objects.size() > 0)
{
state.SetEpoch(objects[0]->GetRealParameter(epochIDs[0]));
state.SetEpochGT(objects[0]->GetGmatTimeParameter(epochIDs[0]));
}
#ifdef DEBUG_OBJECT_UPDATES
MessageInterface::ShowMessage(
"After mapping %d objects to vector, contents are\n"
" Epoch = %.12lf\n", objects.size(), state.GetEpoch());
for (Integer index = 0; index < stateSize; ++index)
{
std::stringstream msg("");
msg << stateMap[index]->subelement;
std::string lbl = stateMap[index]->objectName + "." +
stateMap[index]->elementName + "." + msg.str() + " = ";
MessageInterface::ShowMessage(" %d: %s%.12lf\n", index, lbl.c_str(),
state[index]);
}
// Look at state data after
MessageInterface::ShowMessage("Real object data after: [");
for (Integer index = 0; index < stateSize; ++index)
if (stateMap[index]->parameterType == Gmat::REAL_TYPE)
MessageInterface::ShowMessage(" %lf ",
(stateMap[index]->object)->GetRealParameter(
stateMap[index]->parameterID));
MessageInterface::ShowMessage("]\n");
#endif
return true;
}
//------------------------------------------------------------------------------
// bool PropagationStateManager::MapVectorToObjects()
//------------------------------------------------------------------------------
/**
* Sets data from the propagation state vector into the objects that manage
* those data
*
* @return true on success, false on failure
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::MapVectorToObjects()
{
#ifdef DEBUG_OBJECT_UPDATES
if (state.HasPrecisionTime())
MessageInterface::ShowMessage("Mapping vector to objects\n"
" EpochGT = %s\n", state.GetEpochGT().ToString().c_str());
else
MessageInterface::ShowMessage("Mapping vector to objects\n"
" Epoch = %.12lf\n", state.GetEpoch());
// Look at state data before
MessageInterface::ShowMessage("V -> O: Real object data before: [");
for (Integer index = 0; index < stateSize; ++index)
if (stateMap[index]->parameterType == Gmat::REAL_TYPE)
MessageInterface::ShowMessage(" %lf ",
(stateMap[index]->object)->GetRealParameter(
stateMap[index]->parameterID));
MessageInterface::ShowMessage("]\n");
#endif
for (Integer index = 0; index < stateSize; ++index)
{
#ifdef DEBUG_OBJECT_UPDATES
std::stringstream msg("");
msg << stateMap[index]->subelement;
std::string lbl = stateMap[index]->objectName + "." +
stateMap[index]->elementName + "." + msg.str() + " = ";
MessageInterface::ShowMessage(" %d: %s%.12lf\n", index, lbl.c_str(),
state[index]);
#endif
switch (stateMap[index]->parameterType)
{
case Gmat::REAL_TYPE:
(stateMap[index]->object)->SetRealParameter(
stateMap[index]->parameterID, state[index]);
break;
case Gmat::RVECTOR_TYPE:
stateMap[index]->object->SetRealParameter(
stateMap[index]->parameterID, state[index],
stateMap[index]->rowIndex);
break;
case Gmat::RMATRIX_TYPE:
stateMap[index]->object->SetRealParameter(
stateMap[index]->parameterID, state[index],
stateMap[index]->rowIndex, stateMap[index]->colIndex);
break;
default:
std::stringstream sel("");
sel << stateMap[index]->subelement;
std::string label = stateMap[index]->objectName + "." +
stateMap[index]->elementName + "." + sel.str();
MessageInterface::ShowMessage(
"%s not set; Element type not handled\n",label.c_str());
}
}
GmatTime theEpochGT = state.GetEpochGT();
GmatEpoch theEpoch = state.GetEpoch();
if (state.HasPrecisionTime())
theEpoch = theEpochGT.GetMjd();
for (UnsignedInt i = 0; i < objects.size(); ++i)
{
objects[i]->SetRealParameter(epochIDs[i], theEpoch);
if (state.HasPrecisionTime())
objects[i]->SetGmatTimeParameter(epochIDs[i], theEpochGT);
else
objects[i]->SetGmatTimeParameter(epochIDs[i], GmatTime(theEpoch));
}
#ifdef DEBUG_OBJECT_UPDATES
// Look at object data after
MessageInterface::ShowMessage("Real object data after: [");
for (Integer index = 0; index < stateSize; ++index)
if (stateMap[index]->parameterType == Gmat::REAL_TYPE)
MessageInterface::ShowMessage(" %lf ",
(stateMap[index]->object)->GetRealParameter(
stateMap[index]->parameterID));
MessageInterface::ShowMessage("]\n");
#endif
return true;
}
//------------------------------------------------------------------------------
// bool RequiresCompletion()
//------------------------------------------------------------------------------
/**
* Flags if additional steps are needed for derivatives after superposition
*
* Returns true if there is a post-superposition step required in the
* propagation state vector. This case occurs, for example, for the orbit STM
* and A-Matrix in order to fill in the upper half of the matrices, and (for the
* STM) to apply \Phi\dot = A \Phi.
*
* @return true if a final "completion" step is needed, false if not.
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::RequiresCompletion()
{
return hasPostSuperpositionMember;
}
//------------------------------------------------------------------------------
// bool ObjectEpochsMatch()
//------------------------------------------------------------------------------
/**
* Tests to see if the object epochs match
*
* @return true is the eopchs match, false if not
*/
//------------------------------------------------------------------------------
bool PropagationStateManager::ObjectEpochsMatch()
{
bool retval = true;
if (objects.size() > 0)
{
if (((SpacePoint*)objects[0])->HasPrecisionTime())
{
GmatTime theEpochGT = objects[0]->GetGmatTimeParameter(epochIDs[0]);
Real diff = 0.0, dt;
for (UnsignedInt i = 1; i < objects.size(); ++i)
{
#ifdef DEBUG_OBJECT_UPDATES
MessageInterface::ShowMessage(" Epochs are %s for %s and "
"%s for %s\n", theEpochGT.ToString().c_str(), objects[0]->GetName().c_str(),
objects[i]->GetGmatTimeParameter(epochIDs[i]).ToString().c_str(),
objects[i]->GetName().c_str());
#endif
dt = fabs((theEpochGT - objects[i]->GetGmatTimeParameter(epochIDs[i])).GetTimeInSec());
if (dt > IDENTICAL_TIME_TOLERANCE)
{
retval = false;
}
diff = (diff > dt ? diff : dt);
}
}
else
{
GmatEpoch theEpoch = objects[0]->GetRealParameter(epochIDs[0]);
Real diff = 0.0, dt;
for (UnsignedInt i = 1; i < objects.size(); ++i)
{
#ifdef DEBUG_OBJECT_UPDATES
MessageInterface::ShowMessage(" Epochs are %.12lf for %s and "
"%.12lf for %s\n", theEpoch, objects[0]->GetName().c_str(),
objects[i]->GetRealParameter(epochIDs[i]),
objects[i]->GetName().c_str());
#endif
dt = fabs(theEpoch - objects[i]->GetRealParameter(epochIDs[i]));
if (dt > IDENTICAL_TIME_TOLERANCE)
{
retval = false;
}
diff = (diff > dt ? diff : dt);
}
}
// Here's how we'll warn if needed:
// if (retval && (diff != 0.0))
// MessageInterface::ShowMessage("Spacecraft epochs do not match in a "
// "Propagator used in the Propagate command, but are within "
// "tolerance (%le sec) acceptable for propagation\n",
// IDENTICAL_TIME_TOLERANCE * 86400.0);
}
return retval;
}
//------------------------------------------------------------------------------
// Integer GetCompletionCount()
//------------------------------------------------------------------------------
/**
* Obtains the number of objects that need to complete updates
*
* @return The number of completion indices registered
*/
//------------------------------------------------------------------------------
Integer PropagationStateManager::GetCompletionCount()
{
return completionIndexList.size();
}
//------------------------------------------------------------------------------
// Integer GetCompletionIndex(Integer start)
//------------------------------------------------------------------------------
/**
* Describe the method here
*
* @param which Index of the beginning of the element that needs completion
*
* @return
*/
//------------------------------------------------------------------------------
Integer PropagationStateManager::GetCompletionIndex(const Integer which)
{
return completionIndexList[which];
}
//------------------------------------------------------------------------------
// Integer GetCompletionSize(Integer start)
//------------------------------------------------------------------------------
/**
* Describe the method here
*
* @param which Index of the beginning of the element that needs completion
*
* @return
*/
//------------------------------------------------------------------------------
Integer PropagationStateManager::GetCompletionSize(const Integer which)
{
return completionSizeList[which];
}
//------------------------------------------------------------------------------
// Integer GetSTMIndex(Integer forParameterID)
//------------------------------------------------------------------------------
/**
* Finds the STM row/column index for the ID'd parameter
*
* @param forParameterID The ID of the parameter
*
* @return The STM row, or -1 if not in the STM
*/
//------------------------------------------------------------------------------
Integer PropagationStateManager::GetSTMIndex(Integer forParameterID)
{
Integer retval = -1;
for (UnsignedInt i = 0; i < stmRowMap.size(); ++i)
{
if (stmRowMap[i] == forParameterID)
{
retval = i;
break;
}
}
return retval;
}
//------------------------------------------------------------------------------
// Integer PropagationStateManager::SortVector()
//------------------------------------------------------------------------------
/**
* Arranges the propagation state vector for use, and determines the size of the
* vector
*
* @return The size of the state vector
*/
//------------------------------------------------------------------------------
Integer PropagationStateManager::SortVector()
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage(
"Entered PropagationStateManager::SortVector()\n");
#endif
StringArray *propList;
std::vector<Integer> order;
std::vector<Gmat::StateElementId> idList;
ObjectArray owners;
StringArray property;
std::vector<Integer>::iterator oLoc;
Gmat::StateElementId id;
Integer size, loc = 0, val;
stateSize = 0;
// Initially assume there is no post superposition member
hasPostSuperpositionMember = false;
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Element list:\n");
Integer k = 0;
for (std::map<GmatBase*, StringArray*>::iterator i = elements.begin();
i != elements.end(); ++i)
{
current = i->first;
propList = i->second;
MessageInterface::ShowMessage(" %d: %s ->\n", ++k,
current->GetName().c_str());
for (UnsignedInt j = 0; j < propList->size(); ++j)
{
MessageInterface::ShowMessage(" %s\n", (*propList)[j].c_str());
}
}
#endif
// Sync up the STMs that are propagated
StringArray stmEntries;
for (UnsignedInt q = 0; q < objects.size(); ++q)
{
if (objects[q]->IsOfType(Gmat::SPACECRAFT))
{
StringArray currentSTMEntries = objects[q]->GetStringArrayParameter("StmElementNames");
for (UnsignedInt i = 0; i < currentSTMEntries.size(); ++i)
{
if (find(stmEntries.begin(), stmEntries.end(), currentSTMEntries[i]) == stmEntries.end())
stmEntries.push_back(currentSTMEntries[i]);
}
}
}
for (UnsignedInt q = 0; q < objects.size(); ++q)
{
for (UnsignedInt p = 0; p < stmEntries.size(); ++p)
objects[q]->SetStringParameter("StmElementNames", stmEntries[p]);
}
// First build a list of the property IDs and objects, measuring state size
// at the same time
for (UnsignedInt q = 0; q < objects.size(); ++q)
{
current = objects[q];
propList = elements[current];
for (StringArray::iterator j = propList->begin();
j != propList->end(); ++j)
{
id = (Gmat::StateElementId)current->SetPropItem(*j);
if (id == Gmat::UNKNOWN_STATE)
throw PropagatorException("Unknown state element: " + (*j) +
" on object " + current->GetName() + ", a " +
current->GetTypeName());
size = current->GetPropItemSize(id);
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("%s has size %d; ", j->c_str(), size);
#endif
if (size <= 0)
throw PropagatorException("State element " + (*j) +
" has size set less than or equal to 0; unable to continue.");
stateSize += size;
for (Integer k = 0; k < size; ++k)
{
idList.push_back(id);
if (current->PropItemNeedsFinalUpdate(id))
hasPostSuperpositionMember = true;
owners.push_back(current);
property.push_back(*j);
// Put this item in the ordering list
oLoc = order.begin();
while (oLoc != order.end())
{
val = idList[*oLoc];
if (id < val)
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("Inserting; id = %d, z = %d,"
" loc = %d\n", id, (*oLoc), loc);
#endif
order.insert(oLoc, loc);
break;
}
++oLoc;
}
if (oLoc == order.end())
order.push_back(loc);
++loc;
}
}
}
ListItem *newItem;
val = 0;
completionIndexList.clear();
completionSizeList.clear();
stmRowMap.clear();
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage(
"State size is %d\n", stateSize);
#endif
// Next build the state
for (Integer i = 0; i < stateSize; ++i)
{
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("%d <- %d: %d %s.%s gives ", i, order[i],
idList[order[i]], owners[order[i]]->GetName().c_str(),
property[order[i]].c_str());
#endif
newItem = new ListItem;
newItem->objectName = owners[order[i]]->GetName();
newItem->elementName = property[order[i]];
if (owners[order[i]]->HasAssociatedStateObjects())
newItem->associateName = owners[order[i]]->GetAssociateName(val);
else
newItem->associateName = owners[order[i]]->GetName();
newItem->object = owners[order[i]];
newItem->elementID = idList[order[i]];
newItem->subelement = ++val;
newItem->parameterID =
owners[order[i]]->GetParameterID(property[order[i]]);
newItem->parameterType =
owners[order[i]]->GetParameterType(newItem->parameterID);
newItem->dynamicObjectProperty =
newItem->object->ParameterAffectsDynamics(newItem->parameterID);
if (newItem->parameterType == Gmat::REAL_TYPE)
newItem->parameterID += val - 1;
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("[%s, %s, %s, %d, %d, %d, %d, %s]\n",
newItem->objectName.c_str(),
newItem->elementName.c_str(),
newItem->associateName.c_str(),
newItem->elementID,
newItem->subelement,
newItem->parameterID,
newItem->parameterType,
(newItem->dynamicObjectProperty ? "dynamic" : "static"));
#endif
if (newItem->parameterType == Gmat::RVECTOR_TYPE)
{
const Rvector vec =
owners[order[i]]->GetRvectorParameter(property[order[i]]);
newItem->rowLength = vec.GetSize();
newItem->rowIndex = val - 1;
}
if (newItem->parameterType == Gmat::RMATRIX_TYPE)
{
const Rmatrix mat =
owners[order[i]]->GetRmatrixParameter(property[order[i]]);
newItem->rowLength = mat.GetNumColumns();
newItem->colIndex = (val-1) % newItem->rowLength;
newItem->rowIndex = (Integer)((val - 1) / newItem->rowLength);
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage(
"RowLen = %d, %d -> row %2d col %2d\n", newItem->rowLength,
val, newItem->rowIndex, newItem->colIndex);
#endif
// While we're here, grab the STM mapping if this is STM
if ((newItem->elementID == Gmat::ORBIT_STATE_TRANSITION_MATRIX) &&
(newItem->rowIndex == 0))
{
stmRowMap.push_back(owners[order[i]]->GetStmRowId(newItem->colIndex));
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage(" STM column for %d\n",
stmRowMap[newItem->colIndex]);
#endif
}
}
newItem->nonzeroInit = owners[order[i]]->
ParameterDvInitializesNonzero(newItem->parameterID,
newItem->rowIndex, newItem->colIndex);
if (newItem->nonzeroInit)
{
newItem->initialValue = owners[order[i]]->
ParameterDvInitialValue(newItem->parameterID,
newItem->rowIndex, newItem->colIndex);
}
if (newItem->object->PropItemNeedsFinalUpdate(newItem->elementID))
{
completionIndexList.push_back(newItem->elementID);
completionSizeList.push_back(1); // Or count sizes?
}
newItem->postDerivativeUpdate = owners[order[i]]->
ParameterUpdatesAfterSuperposition(newItem->parameterID);
newItem->length = owners[order[i]]->GetPropItemSize(idList[order[i]]);
if (val == newItem->length)
val = 0;
stateMap.push_back(newItem);
}
#ifdef DEBUG_STATE_CONSTRUCTION
MessageInterface::ShowMessage("State map contents:\n");
for (std::vector<ListItem*>::iterator i = stateMap.begin();
i != stateMap.end(); ++i)
MessageInterface::ShowMessage(" %s %s %d %d of %d, id = %d\n",
(*i)->objectName.c_str(), (*i)->elementName.c_str(),
(*i)->elementID, (*i)->subelement, (*i)->length,
(*i)->parameterID);
MessageInterface::ShowMessage(
"Finished PropagationStateManager::SortVector()\n");
#endif
return stateSize;
}
| 35.728829 | 101 | 0.527119 | saichikine |
44b3a4c9a71b5fd346f9c831e744f5c97b44d0f9 | 16,880 | cpp | C++ | Eudora71/DirectoryServices/DirectoryServicesUI/src/DSListCtrlImpl.cpp | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 10 | 2018-05-23T10:43:48.000Z | 2021-12-02T17:59:48.000Z | Windows/Eudora71/DirectoryServices/DirectoryServicesUI/src/DSListCtrlImpl.cpp | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 1 | 2019-03-19T03:56:36.000Z | 2021-05-26T18:36:03.000Z | Windows/Eudora71/DirectoryServices/DirectoryServicesUI/src/DSListCtrlImpl.cpp | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 11 | 2018-05-23T10:43:53.000Z | 2021-12-27T15:42:58.000Z | //////////////////////////////////////////////////////////////////////////////
// DSListCtrlImpl.cpp
//
//
// Created: 09/13/97 smohanty
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#define __DS_LIST_CTRL_INTERFACE_IMPLEMENTATION_
#include "DSListCtrlImpl.h"
#include "DebugNewHelpers.h"
IMPLEMENT_DYNCREATE(DSListCtrl, C3DFormView)
BEGIN_MESSAGE_MAP(DSListCtrl, C3DFormView)
ON_WM_SIZE()
ON_WM_DESTROY()
ON_NOTIFY(LVN_COLUMNCLICK, IDD_NDS_LC_RESULTS_TOC, OnColumnClick)
ON_WM_KEYUP()
// ON_NOTIFY(NM_CLICK, IDD_NDS_LC_RESULTS_TOC, OnResultsTocClk)
END_MESSAGE_MAP()
DSListCtrl::DSListCtrl()
: C3DFormView(IDD_NDS_DIRSERV_RESULTS_LIST), customToc(0), m_cxChar(0),
widths(0), sizeCustomTable(0), sizeDefTable(0), pDS(0), shiftDown(FALSE),
nCurHeight(INT_MIN)
{
sizeCustomTable = sizeof(fieldTbl) / sizeof(fieldTbl[0]);
widths = DEBUG_NEW int[sizeCustomTable];
for (UINT i = 0; i < sizeCustomTable; i++) {
widths[i] = -1;
}
sizeDefTable = sizeof(m_pszText) / sizeof(m_pszText[0]);
}
DSListCtrl::~DSListCtrl()
{
if (widths) {
delete [] widths;
widths = 0;
}
}
BOOL
DSListCtrl::SerializeSerializables()
{
BOOL bWritten = FALSE;
// Write the widht of the right pane.
CRString dsSect(IDS_NDS_DIRSERV_SECTION);
char buffer[32] = { '\0' };
const char *section = dsSect;
const char *topPaneY = "TopPaneY";
const char *itoaBuf = ::itoa(nCurHeight, buffer, 10);
const char *iniPath = INIPath;
if (section && topPaneY && itoaBuf && iniPath) {
bWritten = ::WritePrivateProfileString(section, topPaneY, itoaBuf,
iniPath);
}
return bWritten;
}
void
DSListCtrl::PrepareForDestruction()
{
ASSERT(m_LC_ResultsToc.m_hWnd);
int iCount = m_LC_ResultsToc.GetItemCount();
IDSPRecord *pRec = NULL;
for (int i = 0; i < iCount; i++) {
pRec = (IDSPRecord *)
GetListItemLPARAM(i);
if (pRec) {
pRec->Release();
}
}
}
void
DSListCtrl::Reset()
{
int iCount = m_LC_ResultsToc.GetItemCount();
IDSPRecord *pRec = NULL;
for (int i = 0; i < iCount; i++) {
pRec = (IDSPRecord *)
GetListItemLPARAM(i);
if (pRec) {
pRec->Release();
}
}
m_LC_ResultsToc.DeleteAllItems();
// Apprise the parent that items have changed.
m_LC_ResultsToc.AppriseChangeView();
UINT idx = 0;
if (customToc == 0) {
for (idx = 0; idx < sizeDefTable; idx++) {
TocSetColumnWidth(idx, (m_cxChar * strlen(m_pszText[idx])) + 20);
}
}
else {
for (UINT i = 0; i < sizeCustomTable; i++) {
if (widths[i] != -1) {
TocSetColumnWidth(idx, widths[i]);
idx++;
}
}
}
}
void
DSListCtrl::DoDataExchange(CDataExchange *pDX)
{
C3DFormView::DoDataExchange(pDX);
// Results
DDX_Control(pDX, IDD_NDS_LC_RESULTS_TOC, m_LC_ResultsToc);
}
void
DSListCtrl::OnInitialUpdate()
{
C3DFormView::OnInitialUpdate();
SetScaleToFitSize(CSize(1, 1));
RECT rect;
GetClientRect(&rect);
OnSize(SIZE_RESTORED, rect.right - rect.left, rect.bottom - rect.top);
TEXTMETRIC tm;
CClientDC dc(&m_LC_ResultsToc);
dc.GetTextMetrics(&tm);
m_cxChar = tm.tmAveCharWidth;
customToc = IsCustomToc();
if (customToc == 0) {
SetupDefaultColumns();
}
else {
SetupCustomColumns();
}
}
void
DSListCtrl::OnResultsTocClk(NMHDR *pNMHDR, LRESULT *pResult)
{
// m_LC_ResultsToc.OnResultsTocClk(pNMHDR, pResult);
}
void
DSListCtrl::OnKeyUp(UINT nChar, UINT x, UINT y)
{
m_LC_ResultsToc.OnKeyUp(nChar, x, y);
}
int
DSListCtrl::TocInsertColumn(UINT mask, int fmt, int cx, LPTSTR pszText,
int item, int iSubItem)
{
LV_COLUMN lvc;
memset(&lvc, 0, sizeof(LV_COLUMN));
lvc.mask = mask;
lvc.fmt = fmt;
lvc.cx = cx;
lvc.pszText = pszText;
lvc.iSubItem = iSubItem;
return(m_LC_ResultsToc.InsertColumn(item, &lvc));
}
void
DSListCtrl::SetupCustomColumns()
{
UINT mask = LVCF_FMT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_TEXT;
int fmt = LVCFMT_LEFT;
int cx = 100;
UINT keyVal = 0;
UINT idx = 0;
for (UINT i = 0; i < sizeCustomTable; i++) {
UINT defKeyVal = 0;
if (!strcmp(fieldTbl[i], "Name") || !strcmp(fieldTbl[i], "Email") ||
!strcmp(fieldTbl[i], "Database")) {
defKeyVal = 1;
}
keyVal = GetPrivateProfileInt("DirectoryServicesResultsToc",
fieldTbl[i], defKeyVal, INIPath);
if (keyVal == 1) {
TocInsertColumn(mask, fmt, cx, fieldTbl[i], idx, 0);
widths[i] = (m_cxChar * strlen(fieldTbl[i])) + 20;
TocSetColumnWidth(idx, widths[i]);
idx++;
}
}
}
void
DSListCtrl::SetupDefaultColumns()
{
static bool bSetup = false;
UINT mask = LVCF_FMT|LVCF_WIDTH|LVCF_SUBITEM|
LVCF_TEXT;
int fmt = LVCFMT_LEFT;
int cx = 100;
int iSubItem = 0;
if (bSetup == false) {
bSetup = true;
for (UINT idx = 0; idx < sizeDefTable; idx++) {
TocInsertColumn(mask, fmt, cx, m_pszText[idx], idx, iSubItem);
TocSetColumnWidth(idx, (m_cxChar * strlen(m_pszText[idx])) + 20);
}
}
}
BOOL
DSListCtrl::TocSetColumnWidth(int idx, int width)
{
return(SetColumnWidth(idx, width));
}
UINT
DSListCtrl::IsCustomToc()
{
return(GetPrivateProfileInt("DirectoryServicesResultsToc", "CustomToc",
0, INIPath));
}
void
DSListCtrl::InitTOCImageList(CImgCache *imgCache)
{
static bool visited = false;
if (visited == false) {
visited = true;
if (imgCache) {
ListView_SetImageList(GetDlgItem(IDD_NDS_LC_RESULTS_TOC)->m_hWnd,
imgCache->GetImageList(), LVSIL_SMALL);
}
}
}
void
DSListCtrl::InitResultsTOC(DSBM *pDSBM, CImgCache *)
{
m_LC_ResultsToc.InitResultsTOC(pDSBM);
}
void
DSListCtrl::OnSize(UINT nType, int cx, int cy)
{
C3DFormView::OnSize(nType, cx, cy);
// Don't resize if the controls aren't created yet, or the window
// is being minimized.
if ((m_LC_ResultsToc.m_hWnd == NULL) || (nType == SIZE_MINIMIZED ||
cx == -1 || cy == -1)) {
return;
}
// Size the TOC
CRect rectLCResultsToc;
rectLCResultsToc.TopLeft().x = 0;
rectLCResultsToc.TopLeft().y = 0;
rectLCResultsToc.BottomRight().x = cx;
rectLCResultsToc.BottomRight().y = cy;
m_LC_ResultsToc.MoveWindow(rectLCResultsToc);
if (::ShouldUpdateIni() && (nType != SIZE_MINIMIZED)) {
nCurHeight = cy;
SerializeSerializables();
}
}
////////////////////////////////////////////////////////////////////////
// OnDestroy [protected]
//
////////////////////////////////////////////////////////////////////////
void
DSListCtrl::OnDestroy()
{
PrepareForDestruction();
C3DFormView::OnDestroy();
}
LPARAM
DSListCtrl::GetListItemLPARAM(int nItem)
{
return m_LC_ResultsToc.GetListItemLPARAM(nItem);
}
LPARAM
DSListCtrl::GetListFocusedItemLPARAM()
{
int idx = -1;
if ((idx = m_LC_ResultsToc.GetNextItem(-1, LVNI_FOCUSED)) != -1) {
return(GetListItemLPARAM(idx));
}
return(0);
}
void
DSListCtrl::InsertDefaultTocItems(int item, char **table)
{
UINT idx;
for (idx = 0; idx < sizeDefTable; idx++) {
if (table[idx] != 0) {
if (idx != 3) {
m_LC_ResultsToc.SetItemText(item, idx, table[idx]);
}
else {
if (table[idx][0] != '\0') {
m_LC_ResultsToc.SetItemText(item, idx, table[idx]);
}
}
TocSetColumnWidth(idx, LVSCW_AUTOSIZE);
}
}
}
int
DSListCtrl::InsertItem(char **table, HBITMAP hBit, CImgCache *imgCache,
IDSPRecord *pRecord)
{
LV_ITEM lvi;
memset(&lvi, 0, sizeof(LV_ITEM));
if (hBit != NULL && imgCache) {
lvi.iImage = imgCache->Add(hBit);
lvi.mask |= LVIF_IMAGE;
}
lvi.mask |= LVIF_TEXT;
lvi.pszText = "";
lvi.mask |= LVIF_PARAM;
lvi.lParam = (LPARAM)(pRecord);
pRecord->AddRef();
lvi.iItem = m_LC_ResultsToc.GetItemCount();
lvi.iSubItem = 0;
int item = m_LC_ResultsToc.InsertItem(&lvi);
if (item != -1) {
if (customToc == 0) {
InsertDefaultTocItems(item, table);
}
else {
}
}
return(item);
}
void
DSListCtrl::AllocDBEntryAscii(char **buf, DBRECENT *pEnt)
{
int nLen = pEnt->dwSize;
*buf = DEBUG_NEW char[nLen + 1];
strncpy(*buf, (char *)(pEnt->data), nLen);
(*buf)[nLen] = '\0';
}
void
DSListCtrl::AllocDBEntryAsciiZ(char **buf, DBRECENT *pEnt)
{
int nLen = strlen((char *)(pEnt->data));
*buf = DEBUG_NEW char[nLen + 1];
strncpy(*buf, (char *)(pEnt->data), nLen + 1);
}
void
DSListCtrl::SetupDSBuffer(char **buf, DBRECENT *pEnt)
{
switch(pEnt->nType) {
case DST_ASCII:
AllocDBEntryAscii(buf, pEnt);
break;
case DST_ASCIIZ:
AllocDBEntryAsciiZ(buf, pEnt);
break;
}
}
// This function breaks the generalization of Toc items.
// Will come back post 4.0 and make it general.
bool
DSListCtrl::GetResultsTocEmailList(int item, CStringList& curEmailList)
{
bool retVal = false;
IDSPRecord *pRecord = (IDSPRecord *) GetListItemLPARAM(item);
DBRECENT *pDRec = pRecord->GetRecordList();
if (pDRec) {
DBRECENT *pTmp = pDRec;
while (pTmp) {
if (pTmp->nName == DS_EMAIL) {
CString tmpStr((char *)(pTmp->data));
if (!tmpStr.IsEmpty()) {
retVal = true;
}
curEmailList.AddTail(tmpStr);
}
pTmp = pTmp->pNext;
}
}
return(retVal);
}
void
DSListCtrl::GetDefaultTocItems(IDSPRecord *pRecord, char **table)
{
// A hit may have more than one name, work-phone, or work-email.
// We just show the first one we encounter in the results hit.
bool nameVisited = false;
bool emailVisited = false;
bool phoneVisited = false;
DBRECENT *pDRec = pRecord->GetRecordList();
if (pDRec) {
DBRECENT *pTmp = pDRec;
while (pTmp) {
if (pTmp->nName == DS_NAME) {
if (nameVisited == false) {
nameVisited = true;
}
else {
pTmp = pTmp->pNext;
continue;
}
SetupDSBuffer(&(table[0]), pTmp);
}
else if (pTmp->nName == DS_EMAIL) {
if (emailVisited == false) {
emailVisited = true;
}
else {
pTmp = pTmp->pNext;
continue;
}
SetupDSBuffer(&(table[1]), pTmp);
}
else if (pTmp->nName == DS_PHONE) {
if (phoneVisited == false) {
phoneVisited = true;
}
else {
pTmp = pTmp->pNext;
continue;
}
SetupDSBuffer(&(table[2]), pTmp);
}
pTmp = pTmp->pNext;
}
}
}
IDSDatabase *
DSListCtrl::GetDatabaseFromRecord(IDSPRecord *pRecord)
{
char *szDatabaseID = pRecord->GetDatabaseID();
if (szDatabaseID) {
return(pDS->pDirServ->FindDatabase(szDatabaseID));
}
else {
return(0);
}
}
void
DSListCtrl::InitializeDatabaseName(IDSDatabase *pDatabase, char *buf, int size)
{
HRESULT hErr;
hErr = pDatabase->GetName(buf, size);
if (FAILED(hErr)) {
memset(buf, '\0', size);
}
}
HBITMAP
DSListCtrl::GetBitmapFromRecord(IDSPRecord *pRecord)
{
HBITMAP hBit = NULL;
IDSDatabase *pDatabase = GetDatabaseFromRecord(pRecord);
if (pDatabase) {
hBit = pDatabase->GetProtocolImage(IMG_SMALL);
pDatabase->Release();
}
return(hBit);
}
void
DSListCtrl::GetDefaultTocItemsFromRecord(IDSPRecord *pRecord, char ***table)
{
*table = DEBUG_NEW char *[sizeDefTable * sizeof(char *)];
for (UINT i = 0; i < sizeDefTable; i++) {
(*table)[i] = 0;
}
GetDefaultTocItems(pRecord, *table);
IDSDatabase *pDatabase = GetDatabaseFromRecord(pRecord);
if (pDatabase) {
(*table)[3] = DEBUG_NEW char[128];
InitializeDatabaseName(pDatabase, (*table)[3], 128);
pDatabase->Release();
}
}
int
DSListCtrl::InsertDefaultItem(IDSPRecord *pRecord,
CImgCache *imgCache, AHCB addHitCB,
void *data)
{
HBITMAP hBit = NULL;
char **table;
int item;
GetDefaultTocItemsFromRecord(pRecord, &table);
hBit = GetBitmapFromRecord(pRecord);
if (table[0]) {
item = InsertItem(table, hBit, imgCache, pRecord);
}
else {
char szBuf[128];
IDSDatabase *pDatabase = GetDatabaseFromRecord(pRecord);
pDatabase->GetProtocolName(szBuf, 128);
if (strcmp(szBuf, "Finger") == 0) { // Is it from finger?
CString csText;
csText.LoadString(IDS_DIRSERV_SEEDETAILS);
table[0] = DEBUG_NEW char[csText.GetLength() + 1];
strcpy(table[0], csText.GetBuffer(100));
csText.ReleaseBuffer();
}
item = InsertItem(table, hBit, imgCache, pRecord);
}
DeleteDefaultResultsItemTocMemory(table);
// if this is the first item, splat the contents to the
// details window.
if (m_LC_ResultsToc.GetItemCount() == 1) {
m_LC_ResultsToc.SplatContents(pRecord, data);
}
// Call the AddHit callback.
if (addHitCB) {
(*addHitCB)(data);
}
return(item);
}
int
DSListCtrl::InsertItem(_DS *pDSIn, IDSPRecord *pRecord, CImgCache *imgCache,
AHCB addHitCB, void *data)
{
ASSERT(pDSIn);
pDS = pDSIn;
if (customToc == 0) {
return(InsertDefaultItem(pRecord, imgCache, addHitCB, data));
}
else {
return(0);
}
}
BOOL
DSListCtrl::SetItemText(int nItem, int nSubItem, LPTSTR lpszTxt)
{
return(m_LC_ResultsToc.SetItemText(nItem, nSubItem, lpszTxt));
}
BOOL
DSListCtrl::SetColumnWidth(int nCol, int cx)
{
return(m_LC_ResultsToc.SetColumnWidth(nCol, cx));
}
int
DSListCtrl::ImageList_Add(HBITMAP hBit)
{
return(::ImageList_Add(hilResultsTOC_Entry, hBit, NULL));
}
int
DSListCtrl::GetItemCount()
{
return(m_LC_ResultsToc.GetItemCount());
}
void
DSListCtrl::SelectFirstItem()
{
m_LC_ResultsToc.SetItemState(0, LVIS_SELECTED|LVIS_FOCUSED,
LVIS_SELECTED|LVIS_FOCUSED);
}
CString
DSListCtrl::GetItemText(int iItem, int iSubItem)
{
return(m_LC_ResultsToc.GetItemText(iItem, iSubItem));
}
int
DSListCtrl::GetItemText(int iItem, int iSubItem, LPTSTR lpszText, int nLen)
{
return(m_LC_ResultsToc.GetItemText(iItem, iSubItem, lpszText, nLen));
}
void
DSListCtrl::OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
{
NM_LISTVIEW *nLV = (NM_LISTVIEW *) pNMHDR;
_DS_Composite dsc;
shiftDown = ShiftDown();
dsc.pDSLC = this;
dsc.subItem = nLV->iSubItem;
m_LC_ResultsToc.SortItems(CompareFunc, (DWORD)(&dsc));
*pResult = 0;
}
int CALLBACK
DSListCtrl::CompareFunc(LPARAM one, LPARAM two, LPARAM data)
{
_DS_Composite *pDSC = (_DS_Composite *) data;
if (pDSC->pDSLC->customToc == 0) {
return(DefaultCompareFunc(one, two, pDSC));
}
else {
return(0);
}
}
int
DSListCtrl::DefaultCompareFunc(LPARAM one, LPARAM two, _DS_Composite *pDSC)
{
int retVal;
char **table1, **table2;
IDSPRecord *pRecOne = (IDSPRecord *) one;
IDSPRecord *pRecTwo = (IDSPRecord *) two;
pDSC->pDSLC->GetDefaultTocItemsFromRecord(pRecOne, &table1);
pDSC->pDSLC->GetDefaultTocItemsFromRecord(pRecTwo, &table2);
int column = pDSC->subItem;
// it is possible that the one of the two items is empty, or
// that both are empty.
if (table1[column] == 0 && table2[column] == 0) {
retVal = 0;
goto theend;
}
else if (table1[column] == 0) {
retVal = 1;
goto theend;
}
else if (table2[column] == 0) {
retVal = -1;
goto theend;
}
retVal = strcmp(table1[column], table2[column]);
switch(column) {
case 0:
// comparison by name.
if (retVal == 0) { // do an additional comparison by email.
if (table1[1] && table2[1]) {
retVal = strcmp(table1[1], table2[1]);
}
}
break;
case 1: case 2: case 3:
// comparison by email, or phone or database.
if (retVal == 0) { // do an additional comparison by name.
if (table1[0] && table2[0]) {
retVal = strcmp(table1[0], table2[0]);
}
}
break;
default:
ASSERT(0);
break;
}
theend:
pDSC->pDSLC->DeleteDefaultResultsItemTocMemory(table1);
pDSC->pDSLC->DeleteDefaultResultsItemTocMemory(table2);
if (pDSC->pDSLC->shiftDown == TRUE) {
if (retVal > 0) {
retVal = -1;
}
else if (retVal < 0) {
retVal = 1;
}
}
return(retVal);
}
void
DSListCtrl::DeleteDefaultResultsItemTocMemory(char **table)
{
for (UINT i = 0; i < sizeDefTable; i++) {
if (table[i]) {
delete [] table[i];
table[i] = 0;
}
}
if (table) {
delete [] table;
table = 0;
}
}
LRESULT
DSListCtrl::WindowProc(UINT wMessage, WPARAM wParam, LPARAM lParam)
{
switch (wMessage) {
case WM_GETDLGCODE:
return(DLGC_WANTALLKEYS);
case WM_CHAR:
case WM_SYSCHAR:
if (ShouldPropagateMessageToParent(wMessage, wParam, lParam)) {
::SendMessage(GetParent()->m_hWnd, wMessage, wParam, lParam);
return(0);
}
break;
default:
break;
}
return(C3DFormView::WindowProc(wMessage, wParam, lParam));
}
| 22.18134 | 79 | 0.620557 | dusong7 |
44b4cf21105a0973debcbae5eb91cee293babbf4 | 836 | cpp | C++ | src/jk/cog/vm/unit-test/heap_test.cpp | jdmclark/gorc | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | [
"Apache-2.0"
] | 97 | 2015-02-24T05:09:24.000Z | 2022-01-23T12:08:22.000Z | src/jk/cog/vm/unit-test/heap_test.cpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 8 | 2015-03-27T23:03:23.000Z | 2020-12-21T02:34:33.000Z | src/jk/cog/vm/unit-test/heap_test.cpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 10 | 2016-03-24T14:32:50.000Z | 2021-11-13T02:38:53.000Z | #include "jk/cog/vm/heap.hpp"
#include "test/test.hpp"
using namespace gorc;
using namespace gorc::cog;
begin_suite(heap_test);
test_case(default_heap)
{
heap h;
assert_eq(h.size(), size_t(0));
}
test_case(initialized_heap)
{
heap h(512);
assert_eq(h.size(), size_t(512));
}
test_case(access_grows)
{
heap h;
h[127];
assert_eq(h.size(), size_t(128));
}
test_case(const_access_does_not_grow)
{
heap const h(0);
h[127];
assert_eq(h.size(), size_t(0));
}
test_case(round_trip)
{
heap h;
for(size_t i = 0; i < 16; ++i) {
h[i] = value(static_cast<int>(i));
}
heap const &g = h;
for(size_t i = 0; i < 16; ++i) {
assert_eq(static_cast<int>(g[i]), static_cast<int>(i));
}
assert_eq(g[16].get_type(), value_type::nothing);
}
end_suite(heap_test);
| 15.2 | 63 | 0.606459 | jdmclark |
44b4e5cd65748fb0963011a3c0c2d3364d7088e8 | 4,330 | cc | C++ | snapshot/fuchsia/exception_snapshot_fuchsia.cc | rovarma/crashpad | 42b57efa554a47745cb84860ead46bc9f32b77a9 | [
"Apache-2.0"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | snapshot/fuchsia/exception_snapshot_fuchsia.cc | rovarma/crashpad | 42b57efa554a47745cb84860ead46bc9f32b77a9 | [
"Apache-2.0"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | snapshot/fuchsia/exception_snapshot_fuchsia.cc | rovarma/crashpad | 42b57efa554a47745cb84860ead46bc9f32b77a9 | [
"Apache-2.0"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/fuchsia/exception_snapshot_fuchsia.h"
#include "base/numerics/safe_conversions.h"
#include "snapshot/fuchsia/cpu_context_fuchsia.h"
#include "snapshot/fuchsia/process_reader_fuchsia.h"
namespace crashpad {
namespace internal {
ExceptionSnapshotFuchsia::ExceptionSnapshotFuchsia() = default;
ExceptionSnapshotFuchsia::~ExceptionSnapshotFuchsia() = default;
void ExceptionSnapshotFuchsia::Initialize(
ProcessReaderFuchsia* process_reader,
zx_koid_t thread_id,
const zx_exception_report_t& exception_report) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
exception_ = exception_report.header.type;
thread_id_ = thread_id;
// TODO(scottmg): Not sure whether these values for exception_info_ are
// helpful or correct. Other values in the structures are stored below into
// Codes() in case they are useful.
#if defined(ARCH_CPU_X86_64)
DCHECK(base::IsValueInRangeForNumericType<uint32_t>(
exception_report.context.arch.u.x86_64.err_code));
exception_info_ = exception_report.context.arch.u.x86_64.err_code;
#elif defined(ARCH_CPU_ARM64)
exception_info_ = exception_report.context.arch.u.arm_64.esr;
#endif
codes_.push_back(exception_);
codes_.push_back(exception_info_);
#if defined(ARCH_CPU_X86_64)
codes_.push_back(exception_report.context.arch.u.x86_64.vector);
codes_.push_back(exception_report.context.arch.u.x86_64.cr2);
#elif defined(ARCH_CPU_ARM64)
codes_.push_back(exception_report.context.arch.u.arm_64.far);
#endif
for (const auto& t : process_reader->Threads()) {
if (t.id == thread_id) {
#if defined(ARCH_CPU_X86_64)
context_.architecture = kCPUArchitectureX86_64;
context_.x86_64 = &context_arch_;
// TODO(scottmg): Float context, once Fuchsia has a debug API to capture
// floating point registers. ZX-1750 upstream.
InitializeCPUContextX86_64(t.general_registers, context_.x86_64);
#elif defined(ARCH_CPU_ARM64)
context_.architecture = kCPUArchitectureARM64;
context_.arm64 = &context_arch_;
// TODO(scottmg): Implement context capture for arm64.
#else
#error Port.
#endif
}
}
if (context_.InstructionPointer() != 0 &&
(exception_ == ZX_EXCP_UNDEFINED_INSTRUCTION ||
exception_ == ZX_EXCP_SW_BREAKPOINT ||
exception_ == ZX_EXCP_HW_BREAKPOINT)) {
exception_address_ = context_.InstructionPointer();
} else {
#if defined(ARCH_CPU_X86_64)
exception_address_ = exception_report.context.arch.u.x86_64.cr2;
#elif defined(ARCH_CPU_ARM64)
exception_address_ = exception_report.context.arch.u.arm_64.far;
#endif
}
INITIALIZATION_STATE_SET_VALID(initialized_);
}
const CPUContext* ExceptionSnapshotFuchsia::Context() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return &context_;
}
uint64_t ExceptionSnapshotFuchsia::ThreadID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return thread_id_;
}
uint32_t ExceptionSnapshotFuchsia::Exception() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return exception_;
}
uint32_t ExceptionSnapshotFuchsia::ExceptionInfo() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return exception_info_;
}
uint64_t ExceptionSnapshotFuchsia::ExceptionAddress() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return exception_address_;
}
const std::vector<uint64_t>& ExceptionSnapshotFuchsia::Codes() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return codes_;
}
std::vector<const MemorySnapshot*> ExceptionSnapshotFuchsia::ExtraMemory()
const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return std::vector<const MemorySnapshot*>();
}
} // namespace internal
} // namespace crashpad
| 33.307692 | 78 | 0.775289 | rovarma |
44b52f84f594dde5edadef2bcc5790279abe2f30 | 513 | cpp | C++ | Game/Source/PerformanceTimer.cpp | Memory-Leakers/Platformer2D_Grup99 | fe2e24d3f1affb11502add56e2de090cf5a8bf1a | [
"MIT"
] | 4 | 2021-10-20T12:15:53.000Z | 2022-01-30T16:15:35.000Z | Game/Source/PerformanceTimer.cpp | Memory-Leakers/Platformer2D_Grup99 | fe2e24d3f1affb11502add56e2de090cf5a8bf1a | [
"MIT"
] | null | null | null | Game/Source/PerformanceTimer.cpp | Memory-Leakers/Platformer2D_Grup99 | fe2e24d3f1affb11502add56e2de090cf5a8bf1a | [
"MIT"
] | null | null | null | #include "PerformanceTimer.h"
#include "SDL\include\SDL_timer.h"
uint64 PerformanceTimer::frequency = 0;
PerformanceTimer::PerformanceTimer()
{
Start();
frequency = SDL_GetPerformanceFrequency();
}
void PerformanceTimer::Start()
{
startTimer = SDL_GetPerformanceCounter();
}
double PerformanceTimer::ReadMs() const
{
return 1000.0 * (double(SDL_GetPerformanceCounter() - startTimer) / double(frequency));
}
uint64 PerformanceTimer::ReadTicks() const
{
return SDL_GetPerformanceCounter() - startTimer;
} | 19.730769 | 88 | 0.766082 | Memory-Leakers |
44b79e9bc120cde24bd06b4f3476f1434e7fc033 | 2,729 | cpp | C++ | DolorEditor/EntityManager.cpp | Helgust/GameEnginePractice-2021 | 34fd0576fb3b0fb9c7ffcf121424a27f48d233e1 | [
"MIT"
] | null | null | null | DolorEditor/EntityManager.cpp | Helgust/GameEnginePractice-2021 | 34fd0576fb3b0fb9c7ffcf121424a27f48d233e1 | [
"MIT"
] | null | null | null | DolorEditor/EntityManager.cpp | Helgust/GameEnginePractice-2021 | 34fd0576fb3b0fb9c7ffcf121424a27f48d233e1 | [
"MIT"
] | null | null | null | #include "EntityManager.h"
EntityManager::EntityManager(RenderEngine* pRenderEngine, ScriptSystem* pScriptSystem) :
m_pRenderEngine(pRenderEngine),
m_pScriptSystem(pScriptSystem)
{
m_sLevelName = "";
}
EntityManager::~EntityManager()
{
m_entityQueue.clear();
}
//void EntityManager::CreateEntity(std::string strScriptName)
//{
// flecs::entity newEntity = m_pEcs->entity();
// uint32_t nIndex = GetNewIndex();
//
// ScriptNode* pScriptNode = m_pScriptSystem->CreateScriptNode(strScriptName, newEntity);
//
// Ogre::String strMeshName = pScriptNode->GetMeshName();
// RenderNode* pRenderNode = new RenderNode(nIndex, strMeshName);
//
// newEntity.set(EntityIndex{ nIndex })
// .set(RenderNodeComponent{ pRenderNode }));
//
// m_pRenderEngine->GetRT()->RC_CreateSceneNode(pRenderNode);
//
// Entity entity;
// entity.pRenderNode = pRenderNode;
// entity.scriptName = pScriptNode;
//
// entity.idx = nIndex;
//
// m_entityQueue[nIndex] = entity;
//}
void EntityManager::ClearRenderNodes()
{
m_sLevelName = "";
m_entityQueue.clear();
}
void EntityManager::CreateEntity(const EntityInfo &fromSave)
{
//flecs::entity newEntity = m_pEcs->entity();
uint32_t nIndex = GetNewIndex();
Ogre::String strMeshName = fromSave.meshName;
Ogre::String strObjName = fromSave.objName;
RenderNode* pRenderNode = new RenderNode(nIndex, strMeshName, strObjName);
pRenderNode->SetPosition(fromSave.position);
pRenderNode->SetOrientation(fromSave.rotation);
m_pRenderEngine->GetRT()->RC_CreateSceneNode(pRenderNode);
Entity entity;
entity.pRenderNode = pRenderNode;
entity.scriptName = fromSave.scriptName;
entity.position = fromSave.position;
entity.rotation = fromSave.rotation;
entity.idx = nIndex;
m_entityQueue[nIndex] = entity;
}
//void EntityManager::ReloadScripts(FileSystem* m_pFileSystem)
//{
// for (auto x : m_entityQueue)
// {
// std::string file_path = x.second.pScriptNode->GetPath();
// auto file_last_time = m_pFileSystem->m_mapFileReport[file_path];
// if (std::filesystem::last_write_time(file_path) != file_last_time)
// {
// //ScriptNode* temp = x.second.pScriptNode;
// //x.second.pScriptNode = m_pScriptSystem->CreateScriptNode(std::filesystem::path,);
// x.second.pScriptNode->ReloadScript();
// m_pFileSystem->m_mapFileReport[file_path] = std::filesystem::last_write_time(file_path);
// }
// }
//}
uint32_t EntityManager::GetNewIndex() const
{
return m_entityQueue.size();
}
std::unordered_map<uint32_t, Entity> EntityManager::GetEntityQueue() const
{
return m_entityQueue;
}
void EntityManager::SetNewScriptName(std::string newName, uint32_t id)
{
m_entityQueue[id].scriptName = newName;
}
void EntityManager::SetNameOfLevel(std::string newName)
{
m_sLevelName = newName;
} | 26.240385 | 93 | 0.745694 | Helgust |
44b87e0a3aff8163027f6f7dd865347a4b10b939 | 151 | cpp | C++ | sorting_algorithms/merge_sort.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | sorting_algorithms/merge_sort.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | sorting_algorithms/merge_sort.cpp | M1NH42/learn-dsa | 70b5011a83dd5c29d39b754ed856cb9e023511f3 | [
"MIT"
] | null | null | null | /* In this program we will implement the most important divide and conquer sorting technique */
// TODO: Write the code for the sorting technique below | 75.5 | 95 | 0.788079 | M1NH42 |
44c17c79adc2eb594df78b01041660a3b3346d40 | 651 | cpp | C++ | Core/ShaderProgram.cpp | NinjaDanz3r/NinjaOctopushBurgersOfDoom | 3b89f02d13504e4790fd655889b0cba261d4dbc6 | [
"MIT"
] | 1 | 2016-05-23T18:31:29.000Z | 2016-05-23T18:31:29.000Z | Core/ShaderProgram.cpp | NinjaDanz3r/NinjaOctopushBurgersOfDoom | 3b89f02d13504e4790fd655889b0cba261d4dbc6 | [
"MIT"
] | 25 | 2015-01-03T01:17:45.000Z | 2015-03-23T09:37:52.000Z | Core/ShaderProgram.cpp | NinjaDanz3r/NinjaOctopushBurgersOfDoom | 3b89f02d13504e4790fd655889b0cba261d4dbc6 | [
"MIT"
] | null | null | null | #include "ShaderProgram.h"
#include "Shader.h"
ShaderProgram::ShaderProgram(std::initializer_list<const Shader*> shaders) {
shaderProgram = glCreateProgram();
for (auto shader : shaders)
glAttachShader(shaderProgram, shader->shaderID());
glLinkProgram(shaderProgram);
}
ShaderProgram::~ShaderProgram() {
glDeleteProgram(shaderProgram);
}
void ShaderProgram::use() const {
glUseProgram(shaderProgram);
}
GLuint ShaderProgram::attributeLocation(const char* name) const {
return glGetAttribLocation(shaderProgram, name);
}
GLuint ShaderProgram::uniformLocation(const char* name) const {
return glGetUniformLocation(shaderProgram, name);
} | 24.111111 | 76 | 0.780338 | NinjaDanz3r |
44c3d3c4a50864e7c5778d33c7044d6cb5328025 | 2,803 | cpp | C++ | cpp-projects/exvr-designer/flow/remove_flow_element.cpp | BlankeLab/ExVR | 3a50769c1d11a175b906ddb9c7415f69502cdafd | [
"MIT"
] | null | null | null | cpp-projects/exvr-designer/flow/remove_flow_element.cpp | BlankeLab/ExVR | 3a50769c1d11a175b906ddb9c7415f69502cdafd | [
"MIT"
] | null | null | null | cpp-projects/exvr-designer/flow/remove_flow_element.cpp | BlankeLab/ExVR | 3a50769c1d11a175b906ddb9c7415f69502cdafd | [
"MIT"
] | null | null | null |
/***********************************************************************************
** exvr-designer **
** MIT License **
** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] **
** 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 "remove_flow_element.hpp"
using namespace tool::ex;
RemoveFlowElement::RemoveFlowElement() : remove(std::make_unique<Element>(Element::Type::RemoveElement, "remove")) {
name = remove->name();
type = remove->type;
key = ElementKey{remove->key()};
m_selected = remove->is_selected();
m_insideLoopsID = remove->insideLoopsID;
colors = display::Colors::flowElements.at(type);
}
void RemoveFlowElement::draw(QPainter &painter, qreal zoomLevel){
// draw rectangle
QPen pen;
pen.setWidthF(zoomLevel*1.1);
pen.setColor(colors.selectedLineBoxColor);
painter.setPen(pen);
painter.setBrush(colors.selectedFillBoxColor);
painter.drawRoundedRect(uiElemRect, zoomLevel*4.,zoomLevel*4., Qt::AbsoluteSize);
// draw name
pen.setColor(colors.selectedTextColor);
painter.setPen(pen);
painter.drawText(uiElemRect, Qt::AlignCenter, "X");
}
| 52.886792 | 116 | 0.543703 | BlankeLab |
44c41413c7ea613c911882bf7d4618d3f1a85656 | 61,403 | cpp | C++ | src/conformance/framework/graphics_plugin_opengl.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/framework/graphics_plugin_opengl.cpp | JoeLudwig/OpenXR-CTS | 144c94e8982fe76986019abc9bf2b016740536df | [
"Apache-2.0",
"BSD-3-Clause",
"Unlicense",
"MIT"
] | null | null | null | src/conformance/framework/graphics_plugin_opengl.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 "graphics_plugin.h"
#ifdef XR_USE_GRAPHICS_API_OPENGL
#include "report.h"
#include "swapchain_parameters.h"
#include "xr_dependencies.h"
#include "conformance_framework.h"
#include "Geometry.h"
#include <catch2/catch.hpp>
#include <openxr/openxr_platform.h>
#include <openxr/openxr.h>
#include <thread>
// Why was this needed? hello_xr doesn't need these #defines
//#include "graphics_plugin_opengl_loader.h"
#include "gfxwrapper_opengl.h"
#include "xr_linear.h"
// clang-format off
// Note: mapping of OpenXR usage flags to OpenGL
//
// XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT: can be bound to a framebuffer as color
// XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT: can be bound to a framebuffer as depth (or stencil-only GL_STENCIL_INDEX8)
// XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT: image load/store and core since 4.2.
// List of supported formats is in https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_image_load_store.txt
// XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT & XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT: must be compatible format with glCopyTexImage* calls
// XR_SWAPCHAIN_USAGE_SAMPLED_BIT: can be sampled in a shader
// XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT: all GL formats are typed, but some can be reinterpreted with a different view.
// OpenGL 4.2 / 4.3 with MSAA. Only for color formats and compressed ones
// List with compatible textures: https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_view.txt
// Note: no GL formats are "mutableFormats" in the sense of SwapchainCreateTestParameters as this is intended for TYPELESS,
// however, some are "supportsMutableFormat"
// For now don't test XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT on GL since the semantics are unclear and some runtimes don't support this flag.
#define XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT 0
#define XRC_ALL_CREATE_FLAGS \
{ \
0, XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT, XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT, XR_SWAPCHAIN_CREATE_PROTECTED_CONTENT_BIT | XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT \
}
// the app might request any combination of flags
#define XRC_COLOR_UA_COPY_SAMPLED_MUTABLE_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
}
#define XRC_COLOR_UA_SAMPLED_MUTABLE_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_UNORDERED_ACCESS_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
}
#define XRC_COLOR_COPY_SAMPLED_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
}
#define XRC_COLOR_COPY_SAMPLED_MUTABLE_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
}
#define XRC_COLOR_SAMPLED_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, \
XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
}
#define XRC_DEPTH_COPY_SAMPLED_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_SRC_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
}
#define XRC_DEPTH_SAMPLED_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, \
XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
}
#define XRC_COMPRESSED_SAMPLED_MUTABLE_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, \
}
#define XRC_COMPRESSED_SAMPLED_USAGE_FLAGS \
{ \
XR_SWAPCHAIN_USAGE_SAMPLED_BIT, \
}
#define ADD_GL_COLOR_UA_COPY_SAMPLED_MUTABLE_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, true, true, false, FORMAT, XRC_COLOR_UA_COPY_SAMPLED_MUTABLE_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_COLOR_UA_COPY_SAMPLED_MUTABLE_FORMAT(X) ADD_GL_COLOR_UA_COPY_SAMPLED_MUTABLE_FORMAT2(X, #X)
#define ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, true, true, false, FORMAT, XRC_COLOR_UA_SAMPLED_MUTABLE_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(X) ADD_GL_COLOR_UA_COPY_SAMPLED_MUTABLE_FORMAT2(X, #X)
#define ADD_GL_COLOR_COPY_SAMPLED_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, false, true, false, FORMAT, XRC_COLOR_COPY_SAMPLED_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_COLOR_COPY_SAMPLED_FORMAT(X) ADD_GL_COLOR_COPY_SAMPLED_FORMAT2(X, #X)
#define ADD_GL_COLOR_COPY_SAMPLED_MUTABLE_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, true, true, false, FORMAT, XRC_COLOR_COPY_SAMPLED_MUTABLE_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_COLOR_COPY_SAMPLED_MUTABLE_FORMAT(X) ADD_GL_COLOR_COPY_SAMPLED_MUTABLE_FORMAT2(X, #X)
#define ADD_GL_COLOR_SAMPLED_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, false, true, false, FORMAT, XRC_COLOR_SAMPLED_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_COLOR_SAMPLED_FORMAT(X) ADD_GL_COLOR_SAMPLED_FORMAT2(X, #X)
#define ADD_GL_DEPTH_COPY_SAMPLED_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, false, false, false, FORMAT, XRC_DEPTH_COPY_SAMPLED_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_DEPTH_COPY_SAMPLED_FORMAT(X) ADD_GL_DEPTH_COPY_SAMPLED_FORMAT2(X, #X)
#define ADD_GL_DEPTH_SAMPLED_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, false, false, false, FORMAT, XRC_DEPTH_SAMPLED_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_DEPTH_SAMPLED_FORMAT(X) ADD_GL_DEPTH_SAMPLED_FORMAT2(X, #X)
#define ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, true, true, true, FORMAT, XRC_COMPRESSED_SAMPLED_MUTABLE_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(X) ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT2(X, #X)
#define ADD_GL_COMPRESSED_SAMPLED_FORMAT2(FORMAT, NAME) \
{ \
{FORMAT}, \
{ \
NAME, false, false, true, true, FORMAT, XRC_COMPRESSED_SAMPLED_USAGE_FLAGS, XRC_ALL_CREATE_FLAGS, {}, {}, \
{ \
} \
} \
}
#define ADD_GL_COMPRESSED_SAMPLED_FORMAT(X) ADD_GL_COMPRESSED_SAMPLED_FORMAT2(X, #X)
// clang-format off
namespace Conformance
{
std::string glResultString(GLenum err)
{
switch (err) {
case GL_NO_ERROR:
return "GL_NO_ERROR";
case GL_INVALID_ENUM:
return "GL_INVALID_ENUM";
case GL_INVALID_VALUE:
return "GL_INVALID_VALUE";
case GL_INVALID_OPERATION:
return "GL_INVALID_OPERATION";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "GL_INVALID_FRAMEBUFFER_OPERATION";
case GL_OUT_OF_MEMORY:
return "GL_OUT_OF_MEMORY";
case GL_STACK_UNDERFLOW:
return "GL_STACK_UNDERFLOW";
case GL_STACK_OVERFLOW:
return "GL_STACK_OVERFLOW";
}
return "<unknown " + std::to_string(err) + ">";
}
[[noreturn]] inline void ThrowGLResult(GLenum res, const char* originator = nullptr, const char* sourceLocation = nullptr)
{
Throw("GL failure " + glResultString(res), originator, sourceLocation);
}
inline GLenum CheckThrowGLResult(GLenum res, const char* originator = nullptr, const char* sourceLocation = nullptr)
{
if ((res) != GL_NO_ERROR) {
ThrowGLResult(res, originator, sourceLocation);
}
return res;
}
#define XRC_THROW_GL(res, cmd) ThrowGLResult(res, #cmd, XRC_FILE_AND_LINE)
#define XRC_CHECK_THROW_GLCMD(cmd) CheckThrowGLResult(((cmd), glGetError()), #cmd, XRC_FILE_AND_LINE)
#define XRC_CHECK_THROW_GLRESULT(res, cmdStr) CheckThrowGLResult(res, cmdStr, XRC_FILE_AND_LINE)
constexpr float DarkSlateGray[] = {0.184313729f, 0.309803933f, 0.309803933f, 1.0f};
static const char* VertexShaderGlsl = R"_(
#version 410
in vec3 VertexPos;
in vec3 VertexColor;
out vec3 PSVertexColor;
uniform mat4 ModelViewProjection;
void main() {
gl_Position = ModelViewProjection * vec4(VertexPos, 1.0);
PSVertexColor = VertexColor;
}
)_";
static const char* FragmentShaderGlsl = R"_(
#version 410
in vec3 PSVertexColor;
out vec4 FragColor;
void main() {
FragColor = vec4(PSVertexColor, 1);
}
)_";
struct OpenGLGraphicsPlugin : public IGraphicsPlugin
{
OpenGLGraphicsPlugin(const std::shared_ptr<IPlatformPlugin>& /*unused*/);
~OpenGLGraphicsPlugin() override;
OpenGLGraphicsPlugin(const OpenGLGraphicsPlugin&) = delete;
OpenGLGraphicsPlugin& operator=(const OpenGLGraphicsPlugin&) = delete;
OpenGLGraphicsPlugin(OpenGLGraphicsPlugin&&) = delete;
OpenGLGraphicsPlugin& operator=(OpenGLGraphicsPlugin&&) = delete;
bool Initialize() override;
bool IsInitialized() const override;
void Shutdown() override;
std::string DescribeGraphics() const override;
std::vector<std::string> GetInstanceExtensions() const override;
void CheckState(const char* file_line) const override;
void MakeCurrent(bool bindToThread) override;
bool InitializeDevice(XrInstance instance, XrSystemId systemId, bool checkGraphicsRequirements,
uint32_t deviceCreationFlags) override;
void DebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message) const;
void InitializeResources();
void CheckFramebuffer(GLuint fb) const;
void CheckShader(GLuint shader) const;
void CheckProgram(GLuint prog) const;
void ShutdownDevice() override;
const XrBaseInStructure* GetGraphicsBinding() const override;
void CopyRGBAImage(const XrSwapchainImageBaseHeader* swapchainImage, int64_t imageFormat, uint32_t arraySlice,
const RGBAImage& image) override;
std::string GetImageFormatName(int64_t imageFormat) const override;
bool IsImageFormatKnown(int64_t imageFormat) const override;
bool GetSwapchainCreateTestParameters(XrInstance instance, XrSession session, XrSystemId systemId, int64_t imageFormat,
SwapchainCreateTestParameters* swapchainTestParameters) override;
bool ValidateSwapchainImages(int64_t imageFormat, const SwapchainCreateTestParameters* tp, XrSwapchain swapchain,
uint32_t* imageCount) const override;
bool ValidateSwapchainImageState(XrSwapchain swapchain, uint32_t index, int64_t imageFormat) const override;
int64_t SelectColorSwapchainFormat(const int64_t* imageFormatArray, size_t count) const override;
int64_t SelectDepthSwapchainFormat(const int64_t* imageFormatArray, size_t count) const override;
// Format required by RGBAImage type.
int64_t GetRGBA8Format(bool sRGB) const override;
std::shared_ptr<SwapchainImageStructs> AllocateSwapchainImageStructs(size_t size,
const XrSwapchainCreateInfo& swapchainCreateInfo) override;
void ClearImageSlice(const XrSwapchainImageBaseHeader* colorSwapchainImage, uint32_t imageArrayIndex,
int64_t colorSwapchainFormat) override;
void RenderView(const XrCompositionLayerProjectionView& layerView, const XrSwapchainImageBaseHeader* colorSwapchainImage,
int64_t colorSwapchainFormat, const std::vector<Cube>& cubes) override;
protected:
struct SwapchainImageContext : public IGraphicsPlugin::SwapchainImageStructs
{
// A packed array of XrSwapchainImageOpenGLKHR's for xrEnumerateSwapchainImages
std::vector<XrSwapchainImageOpenGLKHR> swapchainImages;
XrSwapchainCreateInfo createInfo{};
class ArraySliceState
{
public:
ArraySliceState() : depthBuffer(0)
{
}
ArraySliceState(const ArraySliceState&)
{
ReportF("ArraySliceState copy ctor called");
}
GLuint depthBuffer;
};
std::vector<ArraySliceState> slice;
SwapchainImageContext() = default;
~SwapchainImageContext()
{
Reset();
}
std::vector<XrSwapchainImageBaseHeader*> Create(uint32_t capacity, const XrSwapchainCreateInfo& swapchainCreateInfo)
{
createInfo = swapchainCreateInfo;
swapchainImages.resize(capacity);
std::vector<XrSwapchainImageBaseHeader*> bases(capacity);
for (uint32_t i = 0; i < capacity; ++i) {
swapchainImages[i] = {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR};
bases[i] = reinterpret_cast<XrSwapchainImageBaseHeader*>(&swapchainImages[i]);
}
slice.resize(swapchainCreateInfo.arraySize);
return bases;
}
void Reset()
{
swapchainImages.clear();
createInfo = {};
for (const auto& s : slice) {
if (s.depthBuffer) {
XRC_CHECK_THROW_GLCMD(glDeleteTextures(1, &s.depthBuffer));
}
}
slice.clear();
}
GLuint GetDepthTexture(GLuint level)
{
if (!slice[level].depthBuffer) {
XRC_CHECK_THROW_GLCMD(glGenTextures(1, &slice[level].depthBuffer));
XRC_CHECK_THROW_GLCMD(glBindTexture(GL_TEXTURE_2D, slice[level].depthBuffer));
XRC_CHECK_THROW_GLCMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
XRC_CHECK_THROW_GLCMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
XRC_CHECK_THROW_GLCMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
XRC_CHECK_THROW_GLCMD(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
XRC_CHECK_THROW_GLCMD(glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, createInfo.width, createInfo.height, 0,
GL_DEPTH_COMPONENT, GL_FLOAT, nullptr));
}
return slice[level].depthBuffer;
}
};
private:
bool initialized = false;
bool deviceInitialized = false;
void deleteGLContext();
XrVersion OpenGLVersionOfContext = 0;
ksGpuWindow window{};
#if defined(XR_USE_PLATFORM_WIN32)
XrGraphicsBindingOpenGLWin32KHR graphicsBinding{XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR};
#endif
#if defined(XR_USE_PLATFORM_XLIB)
XrGraphicsBindingOpenGLXlibKHR graphicsBinding{XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR};
#endif
std::map<const XrSwapchainImageBaseHeader*, std::shared_ptr<SwapchainImageContext>> m_swapchainImageContextMap;
GLuint m_swapchainFramebuffer{0};
GLuint m_program{0};
GLint m_modelViewProjectionUniformLocation{0};
GLint m_vertexAttribCoords{0};
GLint m_vertexAttribColor{0};
GLuint m_vao{0};
GLuint m_cubeVertexBuffer{0};
GLuint m_cubeIndexBuffer{0};
};
OpenGLGraphicsPlugin::OpenGLGraphicsPlugin(const std::shared_ptr<IPlatformPlugin>& /*unused*/)
{
}
OpenGLGraphicsPlugin::~OpenGLGraphicsPlugin()
{
ShutdownDevice();
Shutdown();
}
bool OpenGLGraphicsPlugin::Initialize()
{
if (initialized) {
return false;
}
initialized = true;
return initialized;
}
bool OpenGLGraphicsPlugin::IsInitialized() const
{
return initialized;
}
void OpenGLGraphicsPlugin::Shutdown()
{
if (initialized) {
initialized = false;
}
}
std::string OpenGLGraphicsPlugin::DescribeGraphics() const
{
return std::string("OpenGL");
}
std::vector<std::string> OpenGLGraphicsPlugin::GetInstanceExtensions() const
{
return {XR_KHR_OPENGL_ENABLE_EXTENSION_NAME};
}
const XrBaseInStructure* OpenGLGraphicsPlugin::GetGraphicsBinding() const
{
if (deviceInitialized) {
return reinterpret_cast<const XrBaseInStructure*>(&graphicsBinding);
}
return nullptr;
}
void OpenGLGraphicsPlugin::deleteGLContext()
{
if (deviceInitialized) {
//ReportF("Destroying window");
ksGpuWindow_Destroy(&window);
}
deviceInitialized = false;
}
bool OpenGLGraphicsPlugin::InitializeDevice(XrInstance instance, XrSystemId systemId, bool checkGraphicsRequirements,
uint32_t /*deviceCreationFlags*/)
{
XrGraphicsRequirementsOpenGLKHR graphicsRequirements{XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR};
graphicsRequirements.minApiVersionSupported = XR_MAKE_VERSION(3, 2, 0);
graphicsRequirements.maxApiVersionSupported = XR_MAKE_VERSION(4, 6, 0);
// optional check to get the graphics requirements:
if (checkGraphicsRequirements) {
auto xrGetOpenGLGraphicsRequirementsKHR =
GetInstanceExtensionFunction<PFN_xrGetOpenGLGraphicsRequirementsKHR>(instance, "xrGetOpenGLGraphicsRequirementsKHR");
XrResult result = xrGetOpenGLGraphicsRequirementsKHR(instance, systemId, &graphicsRequirements);
CHECK(ValidateResultAllowed("xrGetOpenGLGraphicsRequirementsKHR", result));
if (XR_FAILED(result)) {
// Log result?
return false;
}
}
// In contrast to DX, OpenGL on Windows needs a window to render:
if (deviceInitialized == true) {
// a context exists, this function has been called before!
if (OpenGLVersionOfContext >= graphicsRequirements.minApiVersionSupported) {
// no test for max version as using a higher (compatible) version is allowed!
return true;
}
// delete the context to make a new one:
deleteGLContext();
}
ksDriverInstance driverInstance{};
ksGpuQueueInfo queueInfo{};
ksGpuSurfaceColorFormat colorFormat{KS_GPU_SURFACE_COLOR_FORMAT_B8G8R8A8};
ksGpuSurfaceDepthFormat depthFormat{KS_GPU_SURFACE_DEPTH_FORMAT_D24};
ksGpuSampleCount sampleCount{KS_GPU_SAMPLE_COUNT_1};
if (!ksGpuWindow_Create(&window, &driverInstance, &queueInfo, 0, colorFormat, depthFormat, sampleCount, 640, 480, false)) {
XRC_THROW("Unable to create GL context");
}
//ReportF("Created window");
#if defined(XR_USE_PLATFORM_WIN32)
graphicsBinding.hDC = window.context.hDC;
graphicsBinding.hGLRC = window.context.hGLRC;
#endif // XR_USE_PLATFORM_WIN32
#ifdef XR_USE_PLATFORM_XLIB
REQUIRE(window.context.xDisplay != nullptr);
graphicsBinding.xDisplay = window.context.xDisplay;
graphicsBinding.visualid = window.context.visualid;
graphicsBinding.glxFBConfig = window.context.glxFBConfig;
graphicsBinding.glxDrawable = window.context.glxDrawable;
graphicsBinding.glxContext = window.context.glxContext;
#endif
GLenum error = glGetError();
CHECK(error == GL_NO_ERROR);
GLint major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
error = glGetError();
if (error != GL_NO_ERROR) {
// Query for the GL version based on ints was added in OpenGL 3.1
// this error means we would have to use the old way and parse a string (with implementation defined content!)
// ( const GLubyte* versionString = glGetString(GL_VERSION); )
// for now, the conformance tests require at least 3.1...
deleteGLContext();
return false;
}
OpenGLVersionOfContext = XR_MAKE_VERSION(major, minor, 0);
if (OpenGLVersionOfContext < graphicsRequirements.minApiVersionSupported) {
// OpenGL version of the conformance tests is lower than what the runtime requests -> can not be tested
deleteGLContext();
return false;
}
#if !defined(NDEBUG)
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(
[](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) {
((OpenGLGraphicsPlugin*)userParam)->DebugMessageCallback(source, type, id, severity, length, message);
},
this);
#endif
InitializeResources();
deviceInitialized = true;
return true;
}
void OpenGLGraphicsPlugin::DebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
const GLchar* message) const
{
(void)source;
(void)type;
(void)id;
(void)length;
const char* sev = "<unknown>";
switch (severity) {
case GL_DEBUG_SEVERITY_NOTIFICATION:
sev = "INFO";
break;
case GL_DEBUG_SEVERITY_LOW:
sev = "LOW";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
sev = "MED";
break;
case GL_DEBUG_SEVERITY_HIGH:
sev = "HIGH";
break;
}
if (severity == GL_DEBUG_SEVERITY_NOTIFICATION)
return;
ReportF("GL %s (0x%x): %s", sev, id, message);
}
void OpenGLGraphicsPlugin::CheckState(const char* file_line) const
{
static std::string last_file_line;
GLenum err = glGetError();
if (err != GL_NO_ERROR) {
ReportF("CheckState got %s at %s, last good check at %s", glResultString(err).c_str(), file_line, last_file_line.c_str());
}
last_file_line = file_line;
}
void OpenGLGraphicsPlugin::MakeCurrent(bool bindToThread)
{
#if defined(OS_WINDOWS)
if (!window.context.hGLRC) {
return;
}
#elif defined(OS_LINUX_XLIB) || defined(OS_LINUX_XCB_GLX)
if (!window.context.xDisplay) {
return;
}
#else
#error "Platform not (yet) supported."
#endif
if (bindToThread) {
ksGpuContext_SetCurrent(&window.context);
}
else {
ksGpuContext_UnsetCurrent(&window.context);
}
}
void OpenGLGraphicsPlugin::InitializeResources()
{
#if !defined(NDEBUG)
XRC_CHECK_THROW_GLCMD(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS));
#endif
XRC_CHECK_THROW_GLCMD(glGenFramebuffers(1, &m_swapchainFramebuffer));
//ReportF("Got fb %d", m_swapchainFramebuffer);
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &VertexShaderGlsl, nullptr);
glCompileShader(vertexShader);
CheckShader(vertexShader);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &FragmentShaderGlsl, nullptr);
glCompileShader(fragmentShader);
CheckShader(fragmentShader);
m_program = glCreateProgram();
glAttachShader(m_program, vertexShader);
glAttachShader(m_program, fragmentShader);
glLinkProgram(m_program);
CheckProgram(m_program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
m_modelViewProjectionUniformLocation = glGetUniformLocation(m_program, "ModelViewProjection");
m_vertexAttribCoords = glGetAttribLocation(m_program, "VertexPos");
m_vertexAttribColor = glGetAttribLocation(m_program, "VertexColor");
XRC_CHECK_THROW_GLCMD(glGenBuffers(1, &m_cubeVertexBuffer));
XRC_CHECK_THROW_GLCMD(glBindBuffer(GL_ARRAY_BUFFER, m_cubeVertexBuffer));
XRC_CHECK_THROW_GLCMD(
glBufferData(GL_ARRAY_BUFFER, sizeof(Geometry::c_cubeVertices), &Geometry::c_cubeVertices[0], GL_STATIC_DRAW));
XRC_CHECK_THROW_GLCMD(glGenBuffers(1, &m_cubeIndexBuffer));
XRC_CHECK_THROW_GLCMD(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_cubeIndexBuffer));
XRC_CHECK_THROW_GLCMD(
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Geometry::c_cubeIndices), &Geometry::c_cubeIndices[0], GL_STATIC_DRAW));
XRC_CHECK_THROW_GLCMD(glGenVertexArrays(1, &m_vao));
XRC_CHECK_THROW_GLCMD(glBindVertexArray(m_vao));
XRC_CHECK_THROW_GLCMD(glEnableVertexAttribArray(m_vertexAttribCoords));
XRC_CHECK_THROW_GLCMD(glEnableVertexAttribArray(m_vertexAttribColor));
XRC_CHECK_THROW_GLCMD(glBindBuffer(GL_ARRAY_BUFFER, m_cubeVertexBuffer));
XRC_CHECK_THROW_GLCMD(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_cubeIndexBuffer));
XRC_CHECK_THROW_GLCMD(glVertexAttribPointer(m_vertexAttribCoords, 3, GL_FLOAT, GL_FALSE, sizeof(Geometry::Vertex), nullptr));
XRC_CHECK_THROW_GLCMD(glVertexAttribPointer(m_vertexAttribColor, 3, GL_FLOAT, GL_FALSE, sizeof(Geometry::Vertex),
reinterpret_cast<const void*>(sizeof(XrVector3f))));
}
void OpenGLGraphicsPlugin::CheckFramebuffer(GLuint fb) const
{
GLenum st = glCheckNamedFramebufferStatus(fb, GL_FRAMEBUFFER);
if (st == GL_FRAMEBUFFER_COMPLETE)
return;
std::string status;
switch (st) {
case GL_FRAMEBUFFER_COMPLETE:
status = "COMPLETE";
break;
case GL_FRAMEBUFFER_UNDEFINED:
status = "UNDEFINED";
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
status = "INCOMPLETE_ATTACHMENT";
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
status = "INCOMPLETE_MISSING_ATTACHMENT";
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
status = "INCOMPLETE_DRAW_BUFFER";
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
status = "INCOMPLETE_READ_BUFFER";
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
status = "UNSUPPORTED";
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
status = "INCOMPLETE_MULTISAMPLE";
break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
status = "INCOMPLETE_LAYER_TARGETS";
break;
default:
status = "<unknown " + std::to_string(st) + ">";
break;
}
XRC_THROW("CheckFramebuffer " + std::to_string(fb) + " is " + status);
}
void OpenGLGraphicsPlugin::CheckShader(GLuint shader) const
{
GLint r = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &r);
if (r == GL_FALSE) {
GLchar msg[4096] = {};
GLsizei length;
glGetShaderInfoLog(shader, sizeof(msg), &length, msg);
XRC_CHECK_THROW_MSG(r, msg);
}
}
void OpenGLGraphicsPlugin::CheckProgram(GLuint prog) const
{
GLint r = 0;
glGetProgramiv(prog, GL_LINK_STATUS, &r);
if (r == GL_FALSE) {
GLchar msg[4096] = {};
GLsizei length;
glGetProgramInfoLog(prog, sizeof(msg), &length, msg);
XRC_CHECK_THROW_MSG(r, msg);
}
}
void OpenGLGraphicsPlugin::ShutdownDevice()
{
if (m_swapchainFramebuffer != 0) {
glDeleteFramebuffers(1, &m_swapchainFramebuffer);
}
if (m_program != 0) {
glDeleteProgram(m_program);
}
if (m_vao != 0) {
glDeleteVertexArrays(1, &m_vao);
}
if (m_cubeVertexBuffer != 0) {
glDeleteBuffers(1, &m_cubeVertexBuffer);
}
if (m_cubeIndexBuffer != 0) {
glDeleteBuffers(1, &m_cubeIndexBuffer);
}
// Reset the swapchains to avoid calling Vulkan functions in the dtors after
// we've shut down the device.
for (auto& ctx : m_swapchainImageContextMap) {
ctx.second->Reset();
}
m_swapchainImageContextMap.clear();
deleteGLContext();
}
// Only texture formats which are in OpenGL core and which are either color or depth renderable or
// of a specific compressed format are listed below. Runtimes can support additional formats, but those
// will not get tested.
typedef std::map<int64_t, SwapchainCreateTestParameters> SwapchainTestMap;
SwapchainTestMap openGLSwapchainTestMap{
ADD_GL_COLOR_UA_COPY_SAMPLED_MUTABLE_FORMAT(GL_RGBA8),
ADD_GL_COLOR_UA_COPY_SAMPLED_MUTABLE_FORMAT(GL_RGBA16),
ADD_GL_COLOR_UA_COPY_SAMPLED_MUTABLE_FORMAT(GL_RGB10_A2),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R8),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R16),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG8),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG16),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGB10_A2UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R16F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG16F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGB16F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA16F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R32F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG32F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA32F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R11F_G11F_B10F),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R8I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R8UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R16I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R16UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R32I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_R32UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG8I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG8UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG16I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG16UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG32I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RG32UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA8I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA8UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA16I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA16UI),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA32I),
ADD_GL_COLOR_UA_SAMPLED_MUTABLE_FORMAT(GL_RGBA32UI),
ADD_GL_COLOR_COPY_SAMPLED_FORMAT(GL_RGBA4),
ADD_GL_COLOR_COPY_SAMPLED_FORMAT(GL_RGB5_A1),
ADD_GL_COLOR_COPY_SAMPLED_MUTABLE_FORMAT(GL_SRGB8),
ADD_GL_COLOR_COPY_SAMPLED_MUTABLE_FORMAT(GL_SRGB8_ALPHA8),
ADD_GL_COLOR_SAMPLED_FORMAT(GL_RGB565),
ADD_GL_DEPTH_COPY_SAMPLED_FORMAT(GL_DEPTH_COMPONENT16),
ADD_GL_DEPTH_COPY_SAMPLED_FORMAT(GL_DEPTH_COMPONENT24),
ADD_GL_DEPTH_SAMPLED_FORMAT(GL_DEPTH_COMPONENT32F),
ADD_GL_DEPTH_SAMPLED_FORMAT(GL_DEPTH24_STENCIL8),
ADD_GL_DEPTH_SAMPLED_FORMAT(GL_DEPTH32F_STENCIL8),
ADD_GL_DEPTH_SAMPLED_FORMAT(GL_STENCIL_INDEX8),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_RED_RGTC1),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_SIGNED_RED_RGTC1),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_RG_RGTC2),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_SIGNED_RG_RGTC2),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_RGBA_BPTC_UNORM),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT),
ADD_GL_COMPRESSED_SAMPLED_MUTABLE_FORMAT(GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_RGB8_ETC2),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_SRGB8_ETC2),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_RGBA8_ETC2_EAC),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_R11_EAC),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_SIGNED_R11_EAC),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_RG11_EAC),
ADD_GL_COMPRESSED_SAMPLED_FORMAT(GL_COMPRESSED_SIGNED_RG11_EAC),
};
std::string OpenGLGraphicsPlugin::GetImageFormatName(int64_t imageFormat) const
{
SwapchainTestMap::const_iterator it = openGLSwapchainTestMap.find(imageFormat);
if (it != openGLSwapchainTestMap.end()) {
return it->second.imageFormatName;
}
return std::string("unknown");
}
bool OpenGLGraphicsPlugin::IsImageFormatKnown(int64_t imageFormat) const
{
SwapchainTestMap::const_iterator it = openGLSwapchainTestMap.find(imageFormat);
return (it != openGLSwapchainTestMap.end());
}
bool OpenGLGraphicsPlugin::GetSwapchainCreateTestParameters(XrInstance /*instance*/, XrSession /*session*/, XrSystemId /*systemId*/,
int64_t imageFormat, SwapchainCreateTestParameters* swapchainTestParameters)
{
// Swapchain image format support by the runtime is specified by the xrEnumerateSwapchainFormats function.
// Runtimes should support R8G8B8A8 and R8G8B8A8 sRGB formats if possible.
SwapchainTestMap::iterator it = openGLSwapchainTestMap.find(imageFormat);
// Verify that the image format is known. If it's not known then this test needs to be
// updated to recognize new OpenGL formats.
CAPTURE(imageFormat);
CHECK_MSG(it != openGLSwapchainTestMap.end(), "Unknown OpenGL image format.");
if (it == openGLSwapchainTestMap.end()) {
return false;
}
// We may now proceed with creating swapchains with the format.
SwapchainCreateTestParameters& tp = it->second;
tp.arrayCountVector = {1, 2};
if (!tp.compressedFormat) {
tp.mipCountVector = {1, 2};
}
else {
tp.mipCountVector = {1};
}
*swapchainTestParameters = tp;
return true;
}
bool OpenGLGraphicsPlugin::ValidateSwapchainImages(int64_t imageFormat, const SwapchainCreateTestParameters* tp, XrSwapchain swapchain,
uint32_t* imageCount) const
{
*imageCount = 0; // Zero until set below upon success.
std::vector<XrSwapchainImageOpenGLKHR> swapchainImageVector;
uint32_t countOutput;
XrResult result = xrEnumerateSwapchainImages(swapchain, 0, &countOutput, nullptr);
CHECK(ValidateResultAllowed("xrEnumerateSwapchainImages", result));
REQUIRE(result == XR_SUCCESS);
REQUIRE(countOutput > 0);
swapchainImageVector.resize(countOutput, XrSwapchainImageOpenGLKHR{XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR, nullptr});
// Exercise XR_ERROR_SIZE_INSUFFICIENT
if (countOutput >= 2) { // Need at least two in order to exercise XR_ERROR_SIZE_INSUFFICIENT
result = xrEnumerateSwapchainImages(swapchain, 1, &countOutput,
reinterpret_cast<XrSwapchainImageBaseHeader*>(swapchainImageVector.data()));
CHECK(ValidateResultAllowed("xrEnumerateSwapchainImages", result));
CHECK(result == XR_ERROR_SIZE_INSUFFICIENT);
CHECK(countOutput == swapchainImageVector.size());
// Contents of swapchainImageVector is undefined, so nothing to validate about the output.
}
countOutput = (uint32_t)swapchainImageVector.size(); // Restore countOutput if it was (mistakenly) modified.
swapchainImageVector.clear(); // Who knows what the runtime may have mistakely written into our vector.
swapchainImageVector.resize(countOutput, XrSwapchainImageOpenGLKHR{XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR, nullptr});
result = xrEnumerateSwapchainImages(swapchain, countOutput, &countOutput,
reinterpret_cast<XrSwapchainImageBaseHeader*>(swapchainImageVector.data()));
CHECK(ValidateResultAllowed("xrEnumerateSwapchainImages", result));
REQUIRE(result == XR_SUCCESS);
REQUIRE(countOutput == swapchainImageVector.size());
REQUIRE(ValidateStructVectorType(swapchainImageVector, XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR));
for (const XrSwapchainImageOpenGLKHR& image : swapchainImageVector) {
CHECK(glGetError() == GL_NO_ERROR);
CHECK(glIsTexture(image.image));
CHECK(glGetError() == GL_NO_ERROR);
CHECK(imageFormat == tp->expectedCreatedImageFormat);
}
*imageCount = countOutput;
return true;
}
bool OpenGLGraphicsPlugin::ValidateSwapchainImageState(XrSwapchain /*swapchain*/, uint32_t /*index*/, int64_t /*imageFormat*/) const
{
// No resource state in OpenGL
return true;
}
int64_t OpenGLGraphicsPlugin::SelectColorSwapchainFormat(const int64_t* imageFormatArray, size_t count) const
{
// List of supported color swapchain formats.
const std::array<GLenum, 5> f{GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA16, GL_RGBA16F, GL_RGBA32F};
const int64_t* formatArrayEnd = imageFormatArray + count;
auto it = std::find_first_of(imageFormatArray, formatArrayEnd, f.begin(), f.end());
if (it == formatArrayEnd) {
assert(false); // Assert instead of throw as we need to switch to the big table which can't fail.
return imageFormatArray[0];
}
return *it;
}
int64_t OpenGLGraphicsPlugin::SelectDepthSwapchainFormat(const int64_t* imageFormatArray, size_t count) const
{
// List of supported depth swapchain formats.
const std::array<GLenum, 5> f{GL_DEPTH24_STENCIL8, GL_DEPTH32F_STENCIL8, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32F,
GL_DEPTH_COMPONENT16};
const int64_t* formatArrayEnd = imageFormatArray + count;
auto it = std::find_first_of(imageFormatArray, formatArrayEnd, f.begin(), f.end());
if (it == formatArrayEnd) {
assert(false); // Assert instead of throw as we need to switch to the big table which can't fail.
return imageFormatArray[0];
}
return *it;
}
int64_t OpenGLGraphicsPlugin::GetRGBA8Format(bool sRGB) const
{
return sRGB ? GL_SRGB8_ALPHA8 : GL_RGBA8;
}
std::shared_ptr<IGraphicsPlugin::SwapchainImageStructs>
OpenGLGraphicsPlugin::AllocateSwapchainImageStructs(size_t size, const XrSwapchainCreateInfo& swapchainCreateInfo)
{
auto derivedResult = std::make_shared<SwapchainImageContext>();
// Allocate and initialize the buffer of image structs (must be sequential in memory for xrEnumerateSwapchainImages).
// Return back an array of pointers to each swapchain image struct so the consumer doesn't need to know the type/size.
// Keep the buffer alive by adding it into the list of buffers.
std::vector<XrSwapchainImageBaseHeader*> bases = derivedResult->Create(uint32_t(size), swapchainCreateInfo);
for (auto& base : bases) {
// Set the generic vector of base pointers
derivedResult->imagePtrVector.push_back(base);
// Map every swapchainImage base pointer to this context
m_swapchainImageContextMap[base] = derivedResult;
}
// Cast our derived type to the caller-expected type.
std::shared_ptr<SwapchainImageStructs> result =
std::static_pointer_cast<SwapchainImageStructs, SwapchainImageContext>(derivedResult);
return result;
}
void OpenGLGraphicsPlugin::CopyRGBAImage(const XrSwapchainImageBaseHeader* swapchainImage, int64_t /*imageFormat*/, uint32_t arraySlice,
const RGBAImage& image)
{
auto swapchainContext = m_swapchainImageContextMap[swapchainImage];
const uint32_t colorTexture = reinterpret_cast<const XrSwapchainImageOpenGLKHR*>(swapchainImage)->image;
const GLint mip = 0;
const GLint x = 0;
const GLint z = arraySlice;
const GLsizei w = swapchainContext->createInfo.width;
const GLsizei h = swapchainContext->createInfo.height;
if (swapchainContext->createInfo.arraySize > 1) {
XRC_CHECK_THROW_GLCMD(glBindTexture(GL_TEXTURE_2D_ARRAY, colorTexture));
for (GLint y = 0; y < h; ++y) {
const void* pixels = &image.pixels[(h - 1 - y) * w];
XRC_CHECK_THROW_GLCMD(glTexSubImage3D(GL_TEXTURE_2D_ARRAY, mip, x, y, z, w, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
}
}
else {
XRC_CHECK_THROW_GLCMD(glBindTexture(GL_TEXTURE_2D, colorTexture));
for (GLint y = 0; y < h; ++y) {
const void* pixels = &image.pixels[(h - 1 - y) * w];
XRC_CHECK_THROW_GLCMD(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, y, w, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
}
}
}
void OpenGLGraphicsPlugin::ClearImageSlice(const XrSwapchainImageBaseHeader* colorSwapchainImage, uint32_t imageArrayIndex,
int64_t /*colorSwapchainFormat*/)
{
auto swapchainContext = m_swapchainImageContextMap[colorSwapchainImage];
XRC_CHECK_THROW_GLCMD(glBindFramebuffer(GL_FRAMEBUFFER, m_swapchainFramebuffer));
const uint32_t colorTexture = reinterpret_cast<const XrSwapchainImageOpenGLKHR*>(colorSwapchainImage)->image;
const uint32_t depthTexture = swapchainContext->GetDepthTexture(imageArrayIndex);
if (swapchainContext->createInfo.arraySize > 1) {
XRC_CHECK_THROW_GLCMD(glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorTexture, 0, imageArrayIndex));
}
else {
XRC_CHECK_THROW_GLCMD(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0));
}
XRC_CHECK_THROW_GLCMD(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0));
CheckFramebuffer(m_swapchainFramebuffer);
GLint x = 0;
GLint y = 0;
GLsizei w = swapchainContext->createInfo.width;
GLsizei h = swapchainContext->createInfo.height;
XRC_CHECK_THROW_GLCMD(glViewport(x, y, w, h));
XRC_CHECK_THROW_GLCMD(glScissor(x, y, w, h));
XRC_CHECK_THROW_GLCMD(glEnable(GL_SCISSOR_TEST));
// Clear swapchain and depth buffer.
XRC_CHECK_THROW_GLCMD(glClearColor(DarkSlateGray[0], DarkSlateGray[1], DarkSlateGray[2], DarkSlateGray[3]));
XRC_CHECK_THROW_GLCMD(glClearDepth(1.0f));
XRC_CHECK_THROW_GLCMD(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT));
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void OpenGLGraphicsPlugin::RenderView(const XrCompositionLayerProjectionView& layerView,
const XrSwapchainImageBaseHeader* colorSwapchainImage, int64_t /*colorSwapchainFormat*/,
const std::vector<Cube>& cubes)
{
auto swapchainContext = m_swapchainImageContextMap[colorSwapchainImage];
XRC_CHECK_THROW_GLCMD(glBindFramebuffer(GL_FRAMEBUFFER, m_swapchainFramebuffer));
GLint layer = layerView.subImage.imageArrayIndex;
const GLuint colorTexture = reinterpret_cast<const XrSwapchainImageOpenGLKHR*>(colorSwapchainImage)->image;
const GLuint depthTexture = swapchainContext->GetDepthTexture(layer);
if (swapchainContext->createInfo.arraySize > 1) {
XRC_CHECK_THROW_GLCMD(glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorTexture, 0, layer));
}
else {
XRC_CHECK_THROW_GLCMD(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0));
}
XRC_CHECK_THROW_GLCMD(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0));
CheckFramebuffer(m_swapchainFramebuffer);
GLint x = layerView.subImage.imageRect.offset.x;
GLint y = layerView.subImage.imageRect.offset.y;
GLsizei w = layerView.subImage.imageRect.extent.width;
GLsizei h = layerView.subImage.imageRect.extent.height;
XRC_CHECK_THROW_GLCMD(glViewport(x, y, w, h));
XRC_CHECK_THROW_GLCMD(glScissor(x, y, w, h));
XRC_CHECK_THROW_GLCMD(glEnable(GL_SCISSOR_TEST));
XRC_CHECK_THROW_GLCMD(glEnable(GL_DEPTH_TEST));
XRC_CHECK_THROW_GLCMD(glEnable(GL_CULL_FACE));
XRC_CHECK_THROW_GLCMD(glFrontFace(GL_CW));
XRC_CHECK_THROW_GLCMD(glCullFace(GL_BACK));
// Set shaders and uniform variables.
XRC_CHECK_THROW_GLCMD(glUseProgram(m_program));
const auto& pose = layerView.pose;
XrMatrix4x4f proj;
XrMatrix4x4f_CreateProjectionFov(&proj, GRAPHICS_OPENGL, layerView.fov, 0.05f, 100.0f);
XrMatrix4x4f toView;
XrVector3f scale{1.f, 1.f, 1.f};
XrMatrix4x4f_CreateTranslationRotationScale(&toView, &pose.position, &pose.orientation, &scale);
XrMatrix4x4f view;
XrMatrix4x4f_InvertRigidBody(&view, &toView);
XrMatrix4x4f vp;
XrMatrix4x4f_Multiply(&vp, &proj, &view);
// Set cube primitive data.
XRC_CHECK_THROW_GLCMD(glBindVertexArray(m_vao));
// Render each cube
for (const Cube& cube : cubes) {
// Compute the model-view-projection transform and set it..
XrMatrix4x4f model;
XrMatrix4x4f_CreateTranslationRotationScale(&model, &cube.Pose.position, &cube.Pose.orientation, &cube.Scale);
XrMatrix4x4f mvp;
XrMatrix4x4f_Multiply(&mvp, &vp, &model);
glUniformMatrix4fv(m_modelViewProjectionUniformLocation, 1, GL_FALSE, reinterpret_cast<const GLfloat*>(&mvp));
// Draw the cube.
glDrawElements(GL_TRIANGLES, GLsizei(Geometry::c_cubeIndices.size()), GL_UNSIGNED_SHORT, nullptr);
}
glBindVertexArray(0);
glUseProgram(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Swap our window every other eye for RenderDoc
static int everyOther = 0;
if ((everyOther++ & 1) != 0) {
ksGpuWindow_SwapBuffers(&window);
}
}
std::shared_ptr<IGraphicsPlugin> CreateGraphicsPlugin_OpenGL(std::shared_ptr<IPlatformPlugin> platformPlugin)
{
return std::make_shared<OpenGLGraphicsPlugin>(std::move(platformPlugin));
}
} // namespace Conformance
#endif // XR_USE_GRAPHICS_API_OPENGL
| 48.887739 | 237 | 0.660131 | JoeLudwig |
44c456e8c9618a58a75b6529cbf9582844d7ea91 | 5,587 | hpp | C++ | include/VROSC/AudioReactive/TranslateOnBeat.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/AudioReactive/TranslateOnBeat.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/AudioReactive/TranslateOnBeat.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: VROSC.AudioReactive.AudioReactiveBehaviour
#include "VROSC/AudioReactive/AudioReactiveBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: VROSC::AudioReactive
namespace VROSC::AudioReactive {
// Forward declaring type: TranslateEffect
class TranslateEffect;
}
// Completed forward declares
// Type namespace: VROSC.AudioReactive
namespace VROSC::AudioReactive {
// Forward declaring type: TranslateOnBeat
class TranslateOnBeat;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::AudioReactive::TranslateOnBeat);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::AudioReactive::TranslateOnBeat*, "VROSC.AudioReactive", "TranslateOnBeat");
// Type namespace: VROSC.AudioReactive
namespace VROSC::AudioReactive {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: VROSC.AudioReactive.TranslateOnBeat
// [TokenAttribute] Offset: FFFFFFFF
class TranslateOnBeat : public ::VROSC::AudioReactive::AudioReactiveBehaviour {
public:
// Writing base type padding for base size: 0x24 to desired offset: 0x28
char ___base_padding[0x4] = {};
public:
// private VROSC.AudioReactive.TranslateEffect _translateAnimation
// Size: 0x8
// Offset: 0x28
::VROSC::AudioReactive::TranslateEffect* translateAnimation;
// Field size check
static_assert(sizeof(::VROSC::AudioReactive::TranslateEffect*) == 0x8);
public:
// Get instance field reference: private VROSC.AudioReactive.TranslateEffect _translateAnimation
[[deprecated("Use field access instead!")]] ::VROSC::AudioReactive::TranslateEffect*& dyn__translateAnimation();
// public VROSC.AudioReactive.TranslateEffect get_TranslateAnimation()
// Offset: 0xA2D174
::VROSC::AudioReactive::TranslateEffect* get_TranslateAnimation();
// public System.Void .ctor()
// Offset: 0xA2D1F0
// Implemented from: VROSC.AudioReactive.AudioReactiveBehaviour
// Base method: System.Void AudioReactiveBehaviour::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TranslateOnBeat* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::AudioReactive::TranslateOnBeat::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TranslateOnBeat*, creationType>()));
}
// protected override System.Void Awake()
// Offset: 0xA2D17C
// Implemented from: VROSC.AudioReactive.AudioReactiveBehaviour
// Base method: System.Void AudioReactiveBehaviour::Awake()
void Awake();
// protected override System.Void OnBeat(System.Int32 beat)
// Offset: 0xA2D1B8
// Implemented from: VROSC.AudioReactive.AudioReactiveBehaviour
// Base method: System.Void AudioReactiveBehaviour::OnBeat(System.Int32 beat)
void OnBeat(int beat);
}; // VROSC.AudioReactive.TranslateOnBeat
#pragma pack(pop)
static check_size<sizeof(TranslateOnBeat), 40 + sizeof(::VROSC::AudioReactive::TranslateEffect*)> __VROSC_AudioReactive_TranslateOnBeatSizeCheck;
static_assert(sizeof(TranslateOnBeat) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::AudioReactive::TranslateOnBeat::get_TranslateAnimation
// Il2CppName: get_TranslateAnimation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::VROSC::AudioReactive::TranslateEffect* (VROSC::AudioReactive::TranslateOnBeat::*)()>(&VROSC::AudioReactive::TranslateOnBeat::get_TranslateAnimation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::AudioReactive::TranslateOnBeat*), "get_TranslateAnimation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::AudioReactive::TranslateOnBeat::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::AudioReactive::TranslateOnBeat::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::AudioReactive::TranslateOnBeat::*)()>(&VROSC::AudioReactive::TranslateOnBeat::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::AudioReactive::TranslateOnBeat*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::AudioReactive::TranslateOnBeat::OnBeat
// Il2CppName: OnBeat
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::AudioReactive::TranslateOnBeat::*)(int)>(&VROSC::AudioReactive::TranslateOnBeat::OnBeat)> {
static const MethodInfo* get() {
static auto* beat = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::AudioReactive::TranslateOnBeat*), "OnBeat", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{beat});
}
};
| 52.214953 | 222 | 0.751924 | v0idp |
44c65251bfecc98c2a3d3d56b7bd908186c7cf48 | 1,458 | cpp | C++ | FileTransfer/FileTransfer.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 7 | 2020-03-24T15:26:23.000Z | 2021-12-21T21:42:38.000Z | FileTransfer/FileTransfer.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 224 | 2020-03-05T17:40:39.000Z | 2022-03-23T13:18:56.000Z | FileTransfer/FileTransfer.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 52 | 2020-03-05T17:24:05.000Z | 2022-03-31T02:13:40.000Z | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 Metrological
*
* 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 "FileTransfer.h"
namespace WPEFramework {
namespace Plugin {
SERVICE_REGISTRATION(FileTransfer, 1, 0);
const string FileTransfer::Initialize(PluginHost::IShell* service)
{
Config config;
config.FromString(service->ConfigLine());
_logOutput.SetDestination(config.Destination.Binding.Value(), config.Destination.Port.Value());
_observer.Register(config.FilePath.Value(), &_fileUpdate, config.FullFile.Value());
return string();
}
void FileTransfer::Deinitialize(PluginHost::IShell* service)
{
_observer.Unregister();
}
string FileTransfer::Information() const
{
return string();
}
} // namespace Plugin
} // namespace WPEFramework
| 29.755102 | 103 | 0.709877 | Michal-Bugno |
44c6a1decbc7cb342252eb9bc9844e77a8605ba8 | 2,345 | hpp | C++ | StrumpackConfig.hpp | sarahorsak/STRUMPACK | 1c23ba83a07082b3bce5cf7092e990c71af0ee67 | [
"BSD-3-Clause-LBNL"
] | null | null | null | StrumpackConfig.hpp | sarahorsak/STRUMPACK | 1c23ba83a07082b3bce5cf7092e990c71af0ee67 | [
"BSD-3-Clause-LBNL"
] | null | null | null | StrumpackConfig.hpp | sarahorsak/STRUMPACK | 1c23ba83a07082b3bce5cf7092e990c71af0ee67 | [
"BSD-3-Clause-LBNL"
] | null | null | null | /*
* STRUMPACK -- STRUctured Matrices PACKage, Copyright (c) 2014, The
* Regents of the University of California, through Lawrence Berkeley
* National Laboratory (subject to receipt of any required approvals
* from the U.S. Dept. of Energy). All rights reserved.
*
* If you have questions about your rights to use or distribute this
* software, please contact Berkeley Lab's Technology Transfer
* Department at TTD@lbl.gov.
*
* NOTICE. This software is owned by the U.S. Department of Energy. As
* such, the U.S. Government has been granted for itself and others
* acting on its behalf a paid-up, nonexclusive, irrevocable,
* worldwide license in the Software to reproduce, prepare derivative
* works, and perform publicly and display publicly. Beginning five
* (5) years after the date permission to assert copyright is obtained
* from the U.S. Department of Energy, and subject to any subsequent
* five (5) year renewals, the U.S. Government is granted for itself
* and others acting on its behalf a paid-up, nonexclusive,
* irrevocable, worldwide license in the Software to reproduce,
* prepare derivative works, distribute copies to the public, perform
* publicly and display publicly, and to permit others to do so.
*
* Developers: Pieter Ghysels, Francois-Henry Rouet, Xiaoye S. Li.
* (Lawrence Berkeley National Lab, Computational Research
* Division).
*/
#ifndef STRUMPACK_CONFIG_HPP
#define STRUMPACK_CONFIG_HPP
#define STRUMPACK_USE_MPI
/* #undef STRUMPACK_USE_METIS */
/* #undef STRUMPACK_USE_PARMETIS */
/* #undef STRUMPACK_USE_SCOTCH */
/* #undef STRUMPACK_USE_PTSCOTCH */
#define STRUMPACK_USE_OPENMP
/* #undef STRUMPACK_USE_PAPI */
/* #undef STRUMPACK_USE_COMBBLAS */
/* #undef STRUMPACK_USE_BPACK */
/* #undef STRUMPACK_USE_ZFP */
/* #undef STRUMPACK_USE_CUBLAS */
/* #undef STRUMPACK_USE_SLATE_LAPACK */
/* #undef STRUMPACK_USE_SLATE_SCALAPACK */
/* #undef STRUMPACK_USE_MAGMA */
#define STRUMPACK_USE_GETOPT
/* #undef STRUMPACK_COUNT_FLOPS */
/* #undef STRUMPACK_TASK_TIMERS */
/* #undef STRUMPACK_DEV_TESTING */
#define STRUMPACK_USE_OPENMP_TASKLOOP
/* #undef STRUMPACK_USE_OPENMP_TASK_DEPEND */
#define STRUMPACK_PBLAS_BLOCKSIZE 32
#define STRUMPACK_VERSION_MAJOR 3
#define STRUMPACK_VERSION_MINOR 3
#define STRUMPACK_VERSION_PATCH 0
#endif // STRUMPACK_CONFIG_HPP
| 37.222222 | 70 | 0.763753 | sarahorsak |
44c8b602441aad741405c732bfb192e1e7db01e9 | 560 | cpp | C++ | hal/ESP32/gpio/gpio.cpp | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | null | null | null | hal/ESP32/gpio/gpio.cpp | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | null | null | null | hal/ESP32/gpio/gpio.cpp | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | null | null | null | #include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include "gpio.hpp"
using namespace hal;
gpio::gpio(uint8_t port, uint8_t pin, enum mode mode, bool state):
_port(port),
_pin(pin),
_mode(mode)
{
assert(_port < ports);
assert(_pin < pins);
set_mode(_mode, state);
}
gpio::~gpio()
{
}
void gpio::set(bool state) const
{
assert(_mode == mode::DO);
}
bool gpio::get() const
{
assert(_mode == mode::DI && _mode == mode::DO);
}
void gpio::toggle() const
{
assert(_mode == mode::DO);
}
void gpio::set_mode(enum mode mode, bool state)
{
}
| 13.658537 | 66 | 0.648214 | yhsb2k |
44ca29a6d61b1fd0616676ae7cb2956c47bf6371 | 33,749 | cpp | C++ | groups/bsl/bslalg/bslalg_autoarraydestructor.t.cpp | adambde/bde | a2efe118da642be42b25e81ca986a0fe56078305 | [
"Apache-2.0"
] | 26 | 2015-05-07T04:22:06.000Z | 2022-01-26T09:10:12.000Z | groups/bsl/bslalg/bslalg_autoarraydestructor.t.cpp | adambde/bde | a2efe118da642be42b25e81ca986a0fe56078305 | [
"Apache-2.0"
] | 3 | 2015-05-07T21:06:36.000Z | 2015-08-28T20:02:18.000Z | groups/bsl/bslalg/bslalg_autoarraydestructor.t.cpp | adambde/bde | a2efe118da642be42b25e81ca986a0fe56078305 | [
"Apache-2.0"
] | 12 | 2015-05-06T08:41:07.000Z | 2021-11-09T12:52:19.000Z | // bslalg_autoarraydestructor.t.cpp -*-C++-*-
#include <bslalg_autoarraydestructor.h>
#include <bslalg_scalarprimitives.h> // for testing only
#include <bslma_allocator.h> // for testing only
#include <bslma_deallocatorproctor.h> // for testing only
#include <bslma_autodestructor.h> // for testing only
#include <bslma_deallocatorproctor.h> // for testing only
#include <bslma_default.h> // for testing only
#include <bslma_testallocator.h> // for testing only
#include <bslma_testallocatorexception.h> // for testing only
#include <bslma_usesbslmaallocator.h> // for testing only
#include <bsls_alignmentutil.h> // for testing only
#include <bsls_assert.h> // for testing only
#include <bsls_asserttest.h> // for testing only
#include <bsls_stopwatch.h> // for testing only
#include <cstdio>
#include <cstdlib> // atoi()
#include <cstring> // strlen()
#include <ctype.h> // isalpha()
using namespace BloombergLP;
using namespace std;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// The component to be tested provides a proctor to help with exception-safety
// guarantees. The test sequence is very simple: we only have to ascertain
// that the index computation is correct and that the proctor does destroy its
// guarded range unless 'release has been called. We use a test type that
// monitors the number of constructions and destructions, and that allocates in
// order to take advantage of the standard 'bslma' exception test.
//-----------------------------------------------------------------------------
// [ 2] bslalg::AutoArrayDestructor(T *b, T *e);
// [ 2] ~AutoArrayDestructor();
// [ 2] T *moveBegin(ptrdiff_t ne = -1);
// [ 2] T *moveEnd(ptrdiff_t ne = 1);
// [ 3] void release();
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [ 4] USAGE EXAMPLE
//=============================================================================
// STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
int testStatus = 0;
namespace {
void aSsErT(int c, const char *s, int i)
{
if (c) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
} // close unnamed namespace
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
//=============================================================================
// STANDARD BDE LOOP-ASSERT TEST MACROS
//-----------------------------------------------------------------------------
// NOTE: This implementation of LOOP_ASSERT macros must use printf since
// cout uses new and be called during exception testing.
#define LOOP_ASSERT(I,X) { \
if (!(X)) { printf("%s: %d\n", #I, I); aSsErT(1, #X, __LINE__); } }
#define LOOP2_ASSERT(I,J,X) { \
if (!(X)) { printf("%s: %d\t%s: %d\n", #I, I, #J, J); \
aSsErT(1, #X, __LINE__); } }
#define LOOP3_ASSERT(I,J,K,X) { \
if (!(X)) { printf("%s: %d\t%s: %c\t%s: %c\n", #I, I, #J, J, #K, K); \
aSsErT(1, #X, __LINE__); } }
#define LOOP4_ASSERT(I,J,K,L,X) { \
if (!(X)) { printf("%s: %d\t%s: %d\t%s: %d\t%s: %d\n", \
#I, I, #J, J, #K, K, #L, L); aSsErT(1, #X, __LINE__); } }
//=============================================================================
// SEMI-STANDARD TEST OUTPUT MACROS
//-----------------------------------------------------------------------------
// #define P(X) cout << #X " = " << (X) << endl; // Print identifier and value.
#define Q(X) printf("<| " #X " |>\n"); // Quote identifier literally.
//#define P_(X) cout << #X " = " << (X) << ", " << flush; // P(X) without '\n'
#define L_ __LINE__ // current Line number
#define T_ printf("\t"); // Print a tab (w/o newline)
//=============================================================================
// SEMI-STANDARD NEGATIVE-TESTING MACROS
//-----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS/TYPES FOR TESTING
//-----------------------------------------------------------------------------
// TYPES
class TestType;
typedef TestType T; // uses 'bslma' allocators
// STATIC DATA
static int verbose, veryVerbose, veryVeryVerbose;
const int MAX_ALIGN = bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT;
static int numDefaultCtorCalls = 0;
static int numCharCtorCalls = 0;
static int numCopyCtorCalls = 0;
static int numAssignmentCalls = 0;
static int numDestructorCalls = 0;
bslma::TestAllocator *Z; // initialized at the start of main()
// ==============
// class TestType
// ==============
class TestType {
// This test type contains a 'char' in some allocated storage. It counts
// the number of default and copy constructions, assignments, and
// destructions. It has no traits other than using a 'bslma' allocator.
// It could have the bit-wise moveable traits but we defer that trait to
// the 'MoveableTestType'.
char *d_data_p;
bslma::Allocator *d_allocator_p;
public:
// CREATORS
explicit
TestType(bslma::Allocator *ba = 0)
: d_data_p(0)
, d_allocator_p(bslma::Default::allocator(ba))
{
++numDefaultCtorCalls;
d_data_p = (char *)d_allocator_p->allocate(sizeof(char));
*d_data_p = '?';
}
explicit
TestType(char c, bslma::Allocator *ba = 0)
: d_data_p(0)
, d_allocator_p(bslma::Default::allocator(ba))
{
++numCharCtorCalls;
d_data_p = (char *)d_allocator_p->allocate(sizeof(char));
*d_data_p = c;
}
TestType(const TestType& original, bslma::Allocator *ba = 0)
: d_data_p(0)
, d_allocator_p(bslma::Default::allocator(ba))
{
++numCopyCtorCalls;
if (&original != this) {
d_data_p = (char *)d_allocator_p->allocate(sizeof(char));
*d_data_p = *original.d_data_p;
}
}
~TestType()
{
++numDestructorCalls;
*d_data_p = '_';
d_allocator_p->deallocate(d_data_p);
d_data_p = 0;
}
// MANIPULATORS
TestType& operator=(const TestType& rhs)
{
++numAssignmentCalls;
if (&rhs != this) {
char *newData = (char *)d_allocator_p->allocate(sizeof(char));
*d_data_p = '_';
d_allocator_p->deallocate(d_data_p);
d_data_p = newData;
*d_data_p = *rhs.d_data_p;
}
return *this;
}
void setDatum(char c)
{
*d_data_p = c;
}
// ACCESSORS
char datum() const
{
return *d_data_p;
}
void print() const
{
if (d_data_p) {
ASSERT(isalpha(*d_data_p));
printf("%c (int: %d)\n", *d_data_p, (int)*d_data_p);
} else {
printf("VOID\n");
}
}
};
// TRAITS
namespace BloombergLP {
namespace bslma {
template <>
struct UsesBslmaAllocator<TestType> : bsl::true_type {};
} // close package namespace
} // close enterprise namespace
bool operator==(const TestType& lhs, const TestType& rhs)
{
ASSERT(isalpha(lhs.datum()));
ASSERT(isalpha(rhs.datum()));
return lhs.datum() == rhs.datum();
}
//=============================================================================
// USAGE EXAMPLE
//-----------------------------------------------------------------------------
///Usage
///-----
// In this section we show intended use of this component.
//
///Example 1: Managing an Array Under Construction
///- - - - - - - - - - - - - - - - - - - - - - - -
// In most instances, the use of a 'bslalg::AutoArrayDestructor' could be
// handled by a 'bslma::AutoDeallocator', but sometimes it is conceptually
// clearer to frame the problem in terms of a pair of pointers rather than a
// pointer and an offset.
//
// Suppose we have a class, 'UsageType' that allocates a block of memory upon
// construction, and whose constructor takes a char. Suppose we want to create
// an array of elements of such objects in an exception-safe manner.
//
// First, we create the type 'UsageType':
//..
// ===============
// class UsageType
// ===============
class UsageType {
// This test type contains a 'char' in some allocated storage. It has no
// traits other than using a 'bslma' allocator.
char *d_data_p; // managed single char
bslma::Allocator *d_allocator_p; // allocator (held, not owned)
public:
// CREATORS
explicit UsageType(char c, bslma::Allocator *basicAllocator = 0)
: d_data_p(0)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
{
d_data_p = (char *)d_allocator_p->allocate(sizeof(char));
*d_data_p = c;
}
~UsageType()
{
*d_data_p = '_';
d_allocator_p->deallocate(d_data_p);
d_data_p = 0;
}
// ACCESSORS
char datum() const
{
return *d_data_p;
}
};
namespace BloombergLP {
namespace bslma {
template <>
struct UsesBslmaAllocator<UsageType> : bsl::true_type {};
} // close package namespace
} // close enterprise namespace
//=============================================================================
// OBSOLETE USAGE EXAMPLE
//-----------------------------------------------------------------------------
// my_string.h
// ===============
// class my_String
// ===============
class my_String {
// DATA
char *d_string_p;
size_t d_length;
size_t d_size;
public:
// CREATORS
explicit
my_String(const char *string);
my_String(const my_String& original);
~my_String();
// ...
// ACCESSORS
inline
size_t length() const { return d_length; }
inline
operator const char *() const { return d_string_p; }
// ...
};
// FREE OPERATORS
inline
bool operator==(const my_String& lhs, const char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
// ...
// my_string.cpp
// ===============
// class my_String
// ===============
// CREATORS
my_String::my_String(const char *string)
: d_length(strlen(string))
{
ASSERT(string);
d_size = d_length + 1;
d_string_p = (char *) operator new(d_size);
memcpy(d_string_p, string, d_size);
}
my_String::my_String(const my_String& original)
: d_length(original.d_length)
, d_size(original.d_length + 1)
{
d_string_p = (char *) operator new(d_size);
memcpy(d_string_p, original.d_string_p, d_size);
}
my_String::~my_String()
{
ASSERT(d_string_p);
delete d_string_p;
}
// ...
// my_array.h
// ==============
// class my_Array
// ==============
template <class TYPE>
class my_Array {
// This extremely simple 'vector'-like class is merely to demonstrate that
// the usage example works properly. For better testing, it uses a
// test allocator.
// DATA
TYPE *d_array_p; // dynamically allocated array
int d_size; // physical capacity of this array
int d_length; // logical length of this array
bslma::Allocator *d_alloc_p;
private:
// PRIVATE TYPES
enum {
INITIAL_SIZE = 1, // initial physical capacity
GROW_FACTOR = 2 // multiplicative factor by which to grow
// 'd_size'
};
// CLASS METHODS
static int nextSize(int size, int newSize);
static void reallocate(TYPE **array,
int *size,
int newSize,
int length,
bslma::Allocator *allocator);
// PRIVATE MANIPULATORS
void increaseSize(int numElements);
public:
// CREATORS
explicit
my_Array(bslma::Allocator *allocator);
~my_Array();
// MANIPULATORS
void insert(int dstIndex, const TYPE& item, int numItems);
// ACCESSORS
inline
int length() const { return d_length; }
inline
const TYPE& operator[](int index) const { return d_array_p[index]; }
};
// --------------
// class my_Array
// --------------
// CLASS METHODS
template <class TYPE>
inline
int my_Array<TYPE>::nextSize(int size, int newSize)
{
while (size < newSize) {
size *= GROW_FACTOR;
}
return size;
}
template <class TYPE>
inline
void my_Array<TYPE>::reallocate(TYPE **array,
int *size,
int newSize,
int length,
bslma::Allocator *allocator)
// Reallocate memory in the specified 'array' and update the
// specified size to the specified 'newSize'. The specified 'length'
// number of leading elements are preserved. If 'allocator' should throw
// an exception, this function has no effect. The behavior is
// undefined unless 1 <= newSize, 0 <= length, and newSize <= length.
// Note that an "auto deallocator" is needed here to ensure that
// memory allocated for the new array is deallocated when an exception
// occurs.
{
ASSERT(size);
ASSERT(1 <= newSize);
ASSERT(0 <= length);
ASSERT(length <= *size); // sanity check
ASSERT(length <= newSize); // ensure class invariant
TYPE *newArray = (TYPE *) allocator->allocate(newSize * sizeof **array);
// 'autoDealloc' and 'autoDtor' are destroyed in reverse order
bslma::DeallocatorProctor<bslma::Allocator>
autoDealloc(newArray, allocator);
bslma::AutoDestructor<TYPE> autoDtor(newArray, 0);
int i;
for (i = 0; i < length; ++i, ++autoDtor) {
new(&newArray[i]) TYPE((*array)[i]);
}
autoDtor.release();
autoDealloc.release();
for (i = 0; i < length; ++i) {
(*array)[i].~TYPE();
}
allocator->deallocate((void *) *array);
*array = newArray;
*size = newSize;
}
// PRIVATE MANIPULATORS
template <class TYPE>
inline
void my_Array<TYPE>::increaseSize(int numElements)
{
reallocate(&d_array_p,
&d_size,
nextSize(d_size, d_size + numElements),
d_length,
d_alloc_p);
}
// CREATORS
template <class TYPE>
inline
my_Array<TYPE>::my_Array(bslma::Allocator *allocator)
: d_size(INITIAL_SIZE)
, d_length(0)
, d_alloc_p(allocator)
{
d_array_p = (TYPE *) d_alloc_p->allocate(d_size * sizeof *d_array_p);
}
template <class TYPE>
inline
my_Array<TYPE>::~my_Array()
{
for (int i = 0; i < d_length; ++i) {
d_array_p[i].~TYPE();
}
d_alloc_p->deallocate((void *) d_array_p); // delete all allocated memory
}
// MANIPULATORS
// as part of the usage example (below)
///Usage
///-----
// The usage example is nearly identical to that of 'bslma_autodestructor', so
// we will only quote and adapt a small portion of that usage example.
// Namely, we will focus on an array that supports arbitrary user-defined
// types, and suppose that we want to implement insertion of an arbitrary
// number of elements at some (intermediate) position in the array, taking care
// that if an element copy constructor or assignment operator throws, the whole
// array is left in a valid (but unspecified) state.
//
// Consider the implementation of the 'insert' method for a templatized array
// below. The proctor's *origin* is set (at construction) to refer to the
// 'numItems' position past 'array[length]'. Initially, the proctor manages no
// objects (i.e., its end is the same as its beginning).
//..
// 0 1 2 3 4 5 6 7
// _____ _____ _____ _____ _____ _____ _____ _____
// | "A" | "B" | "C" | "D" | "E" |xxxxx|xxxxx|xxxxx|
// `=====^=====^=====^=====^=====^=====^=====^====='
// my_Array ^----- AutoArrayDestructor
// (length = 5)
//
// Figure: Use of proctor for my_Array::insert
//..
// As each of the elements at index positions beyond the insertion position is
// shifted up by two index positions, the proctor's begin address is
// *decremented*. At the same time, the array's length is *decremented* to
// ensure that each array element is always being managed (during an allocation
// attempt) either by the proctor or the array itself, but not both.
//..
// 0 1 2 3 4 5 6 7
// _____ _____ _____ _____ _____ _____ _____ _____
// | "A" | "B" | "C" | "D" |xxxxx|xxxxx| "E" |xxxxx|
// `=====^=====^=====^=====^=====^=====^=====^====='
// my_Array ^ ^ AutoArrayDestructor::end
// (length = 4) `---- AutoArrayDestructor::begin
//
// Figure: Configuration after shifting up one element
//..
// After the required number of elements have been shifted, the hole is filled
// (backwards) by copies of the element to be inserted. The code for the
// templatized 'insert' method is as follows:
//..
// Assume no aliasing.
template <class TYPE>
inline
void my_Array<TYPE>::insert(int dstIndex, const TYPE& item, int numItems)
{
if (d_length >= d_size) {
this->increaseSize(numItems);
}
int origLen = d_length;
TYPE *src = &d_array_p[d_length];
TYPE *dest = &d_array_p[d_length + numItems];
bslalg::AutoArrayDestructor<TYPE> autoDtor(dest, dest);
for (int i = d_length; i > dstIndex; --i, --d_length) {
dest = autoDtor.moveBegin(-1); // decrement destination
new(dest) TYPE(*(--src)); // copy to new index
src->~TYPE(); // destroy original
}
for (int i = numItems; i > 0; --i) {
dest = autoDtor.moveBegin(-1); // decrement destination
new(dest) TYPE(item); // copy new value into hole
}
autoDtor.release();
d_length = origLen + numItems;
}
//..
// Note that in the 'insert' example above, we illustrate exception
// neutrality, but not alias safety (i.e., in the case when 'item' is a
// reference into the portion of the array at 'dstIndex' or beyond).
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
veryVeryVerbose = argc > 4;
setbuf(stdout, NULL); // Use unbuffered output
printf("TEST " __FILE__ " CASE %d\n", test);
bslma::TestAllocator testAllocator(veryVeryVerbose);
Z = &testAllocator;
switch (test) { case 0: // Zero is always the leading case.
case 5: {
// --------------------------------------------------------------------
// TESTING USAGE EXAMPLE
//
// Concerns: That the usage example compiles and runs as expected.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) printf("TESTING USAGE\n"
"=============\n");
// Then, we create a 'TestAllocator' to supply memory (and to verify that no
// memory is leaked):
bslma::TestAllocator ta;
// Next, we create the pointer for our array:
UsageType *array;
// Then, we declare a string of chars we will use to initialize the 'UsageType'
// objects in our array.
const char *DATA = "Hello";
const size_t DATA_LEN = std::strlen(DATA);
// Next, we verify that even right after exceptions have been thrown and
// caught, no memory is outstanding:
ASSERT(0 == ta.numBlocksInUse());
// Then, we allocate our array and create a guard to free it if a subsequent
// allocation throws an exception:
array = (UsageType *) ta.allocate(DATA_LEN * sizeof(UsageType));
bslma::DeallocatorProctor<bslma::Allocator> arrayProctor(array, &ta);
// Next, we establish an 'AutoArrayDestructor' on 'array' to destroy any valid
// elements in 'array' if an exception is thrown:
bslalg::AutoArrayDestructor<UsageType> arrayElementProctor(
array, array);
// Note that we pass 'arrayElementProctor' pointers to the beginning and end
// of the range to be guarded (we start with an empty range since no elements
// have been constructed yet).
//
// Then, we iterate through the valid chars in 'DATA' and use them to construct
// the elements of the array:
UsageType *resultElement = array;
for (const char *nextChar = DATA; *nextChar; ++nextChar) {
//..
// Next, construct the next element of 'array':
//..
new (resultElement++) UsageType(*nextChar, &ta);
//..
// Now, move the end of 'arrayElementProctor' to cover the most recently
// constructed element:
//..
arrayElementProctor.moveEnd(1);
}
// At this point, we have successfully created our array.
//
// Then, release the guards so they won't destroy our work when they go out of
// scope:
arrayProctor.release();
arrayElementProctor.release();
// Next, exit the exception testing block:
//
// Then, verify that the array we have created is as expected:
ASSERT('H' == array[0].datum());
ASSERT('e' == array[1].datum());
ASSERT('l' == array[2].datum());
ASSERT('l' == array[3].datum());
ASSERT('o' == array[4].datum());
// Finally, destroy & free our work and verify that no memory is leaked:
for (size_t i = 0; i < DATA_LEN; ++i) {
array[i].~UsageType();
}
ta.deallocate(array);
ASSERT(0 == ta.numBlocksInUse());
} break;
case 4: {
// --------------------------------------------------------------------
// TESTING OBSOLETE USAGE EXAMPLE
//
// Concerns: That the usage example compiles and runs as expected.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING OBSOLETE USAGE."
"\n======================\n");
if (verbose)
printf("Testing 'my_Array::insert' and 'my_Array::remove'.\n");
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator)
{
const char *DATA[] = { "A", "B", "C", "D", "E" };
const int NUM_ELEM = sizeof DATA / sizeof *DATA;
my_Array<my_String> mX(Z); const my_Array<my_String>& X = mX;
for (int i = 0; i < NUM_ELEM; ++i) {
my_String s(DATA[i]);
mX.insert(i, s, 1);
}
if (verbose)
printf("\tInsert two strings \"F\" at index position 2.\n");
my_String item("F");
mX.insert(2, item, 2);
ASSERT(NUM_ELEM + 2 == X.length());
ASSERT(X[0] == DATA[0]);
ASSERT(X[1] == DATA[1]);
ASSERT(X[2] == item);
ASSERT(X[2] == item);
for (int i = 4; i < X.length(); ++i) {
LOOP_ASSERT(i, X[i] == DATA[i - 2]);
}
}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
} break;
case 3: {
// --------------------------------------------------------------------
// TESTING 'release'
//
// Concerns: That the guard does not free guarded memory if 'release'
// has been called.
//
// Plan:
//
// Testing:
// void release();
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING 'release'."
"\n==================\n");
const int MAX_SIZE = 16;
static union {
char d_raw[MAX_SIZE * sizeof(T)];
bsls::AlignmentUtil::MaxAlignedType d_align;
} u;
T *buf = (T *) (void *) &u.d_raw[0];
if (verbose) printf("\tWith release.\n");
{
char c = 'a';
for (int i = 0; i < MAX_SIZE; ++i, ++c) {
new (&buf[i]) T(c, Z);
if (veryVerbose) { buf[i].print(); }
}
bslalg::AutoArrayDestructor<T> mG(&buf[0], &buf[0] + MAX_SIZE);
mG.release();
}
ASSERT(0 < testAllocator.numBytesInUse());
ASSERT(0 == testAllocator.numMismatches());
if (verbose) printf("\tWithout release.\n");
{
bslalg::AutoArrayDestructor<T> mG(&buf[0], &buf[0] + MAX_SIZE);
}
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == testAllocator.numMismatches());
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING 'class bslalg::AutoArrayDestructor'
//
// Concerns: That the guard frees guarded memory properly upon
// exceptions.
//
// Plan: After asserting that the interface behaves as intended and
// that the guard destruction indeed frees the memory, we set up an
// exception test that ensures that the guard indeed correctly guards
// a varying portion of an array.
//
// Testing:
// bslalg::AutoArrayDestructor(T *b, T *e);
// ~AutoArrayDestructor();
// T *moveBegin(ptrdiff_t offset = -1);
// T *moveEnd(ptrdiff_t offset = 1);
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING 'bslalg::AutoArrayDestructor'."
"\n======================================\n");
const int MAX_SIZE = 16;
static union {
char d_raw[MAX_SIZE * sizeof(T)];
bsls::AlignmentUtil::MaxAlignedType d_align;
} u;
T *buf = (T *) (void *) &u.d_raw[0];
if (verbose)
printf("\tSimple interface tests (from breathing test).\n");
{
char c = 'a';
for (int i = 0; i < MAX_SIZE; ++i, ++c) {
new (&buf[i]) T(c, Z);
if (veryVerbose) { buf[i].print(); }
}
bslalg::AutoArrayDestructor<T> mG(&buf[0], &buf[0]);
ASSERT(&buf[5] == mG.moveEnd(5));
ASSERT(&buf[3] == mG.moveBegin(3));
ASSERT(&buf[2] == mG.moveBegin(-1));
ASSERT(&buf[4] == mG.moveEnd(-1));
ASSERT(&buf[0] == mG.moveBegin(-2));
ASSERT(&buf[MAX_SIZE] == mG.moveEnd(MAX_SIZE - 4));
}
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == testAllocator.numMismatches());
if (verbose)
printf("\tException test.\n");
{
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(testAllocator)
{
bslalg::AutoArrayDestructor<T> mG(&buf[0], &buf[0]);
char c = 'a';
for (int i = 0; i < MAX_SIZE; ++i, ++c) {
new (&buf[i]) T(c, Z);
ASSERT(&buf[i + 1] == mG.moveEnd(1));
if (veryVerbose) { buf[i].print(); }
}
}
BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END
}
ASSERT(0 == testAllocator.numBytesInUse());
ASSERT(0 == testAllocator.numMismatches());
if(verbose) printf("\nNegative testing constructors\n");
{
bsls::AssertFailureHandlerGuard g(
bsls::AssertTest::failTestDriver);
ASSERT_SAFE_PASS(bslalg::AutoArrayDestructor<int>(0, 0));
int simpleArray[] = { 0, 1, 2, 3, 4 };
int * begin = simpleArray;
int * end = begin;
ASSERT_SAFE_FAIL(bslalg::AutoArrayDestructor<int>(0, begin));
ASSERT_SAFE_FAIL(bslalg::AutoArrayDestructor<int>(begin, 0));
ASSERT_SAFE_PASS(bslalg::AutoArrayDestructor<int>(begin, begin));
++begin; ++begin; // Advance begin by two to form an invalid range
++end;
ASSERT_SAFE_FAIL(bslalg::AutoArrayDestructor<int>(begin, end));
++end;
ASSERT(begin == end);
ASSERT_SAFE_PASS(bslalg::AutoArrayDestructor<int>(begin, end));
++end;
ASSERT_SAFE_PASS(bslalg::AutoArrayDestructor<int>(begin, end));
}
if(verbose) printf("\nNegative testing 'moveBegin' and 'moveEnd'\n");
{
bsls::AssertFailureHandlerGuard g(
bsls::AssertTest::failTestDriver);
bslalg::AutoArrayDestructor<int> emptyGuard(0, 0);
ASSERT_SAFE_PASS(emptyGuard.moveBegin(0));
ASSERT_SAFE_PASS(emptyGuard.moveEnd(0));
ASSERT_SAFE_FAIL(emptyGuard.moveBegin());
ASSERT_SAFE_FAIL(emptyGuard.moveEnd());
int simpleArray[] = { 0, 1, 2, 3, 4 };
int * begin = &simpleArray[2];
bslalg::AutoArrayDestructor<int> intGuard(begin, begin);
ASSERT_SAFE_PASS(intGuard.moveBegin(0));
ASSERT_SAFE_PASS(intGuard.moveEnd(0));
ASSERT_SAFE_FAIL(intGuard.moveBegin(1));
ASSERT_SAFE_FAIL(intGuard.moveEnd(-1));
ASSERT_SAFE_PASS(intGuard.moveBegin());
ASSERT_SAFE_PASS(intGuard.moveEnd(-1));
ASSERT_SAFE_PASS(intGuard.moveEnd());
ASSERT_SAFE_PASS(intGuard.moveBegin(1));
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
//
// Concerns:
//
// Plan:
//
// Testing:
// This test exercises the component but tests nothing.
// --------------------------------------------------------------------
if (verbose) printf("\nBREATHING TEST"
"\n==============\n");
if (verbose) printf("\nclass bslalg::AutoArrayDestructor"
"\n---------------------------------\n");
{
const int MAX_SIZE = 16;
static union {
char d_raw[MAX_SIZE * sizeof(T)];
bsls::AlignmentUtil::MaxAlignedType d_align;
} u;
T *buf = (T *) (void *) &u.d_raw[0];
char c = 'a';
for (int i = 0; i < MAX_SIZE; ++i, ++c) {
new (&buf[i]) T(c, Z);
if (veryVerbose) { buf[i].print(); }
}
bslalg::AutoArrayDestructor<T> mG(&buf[0], &buf[0]);
ASSERT(&buf[5] == mG.moveEnd(5));
ASSERT(&buf[3] == mG.moveBegin(3));
ASSERT(&buf[2] == mG.moveBegin(-1));
ASSERT(&buf[6] == mG.moveEnd(1));
ASSERT(&buf[0] == mG.moveBegin(-2));
ASSERT(&buf[MAX_SIZE] == mG.moveEnd(MAX_SIZE - 6));
} // deallocates buf
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 33.918593 | 79 | 0.512578 | adambde |
44caa5ea42960c0d671aff7481ca5293017f75d9 | 1,442 | cpp | C++ | 3.Stacks and Queues/Merge_overlapping_Intervals.cpp | suraj0803/DSA | 6ea21e452d7662e2351ee2a7b0415722e1bbf094 | [
"MIT"
] | null | null | null | 3.Stacks and Queues/Merge_overlapping_Intervals.cpp | suraj0803/DSA | 6ea21e452d7662e2351ee2a7b0415722e1bbf094 | [
"MIT"
] | null | null | null | 3.Stacks and Queues/Merge_overlapping_Intervals.cpp | suraj0803/DSA | 6ea21e452d7662e2351ee2a7b0415722e1bbf094 | [
"MIT"
] | null | null | null | #include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
struct Interval{
int start,end;
};
bool compareInterval(Interval i1, Interval i2){
return (i1.start < i2.start);
}
void mergeIntervals(Interval arr[] , int n)
{
// Test if the given set has one interval
if(n<=0)
return;
// Create an empty stack of intervals
stack<Interval> s;
sort(arr,arr+n,compareInterval);
// Push the first interval to stack
s.push(arr[0]);
// start from next interval and merge if necessary
for(int i=1; i<n; i++){
// get interval from stack top
Interval top = s.top();
// if the current element is not overlapping with stack top then push it to the stack
if(top.end<arr[i].end)
s.push(arr[i]);
// otherwise update the ending time of top if ending time of curr is more
else if(top.end < arr[i].end){
top.end = arr[i].end;
s.pop();
s.push(top);
}
}
// print content of stack
cout<<"The merged intervals are :";
while(!s.empty()){
Interval t = s.top();
cout << "[" << t.start << "," << t.end << "] ";
s.pop();
}
return;
}
int main()
{
Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} };
int n = sizeof(arr)/sizeof(arr[0]);
mergeIntervals(arr, n);
return 0;
} | 25.298246 | 94 | 0.533981 | suraj0803 |
44d03a7408f1433216b1318126966587056bb2be | 460 | cpp | C++ | intermediate/Pet.cpp | loiola0/course-cpp | 43ddf46da635980b5acb723496bba2c3f951293f | [
"MIT"
] | null | null | null | intermediate/Pet.cpp | loiola0/course-cpp | 43ddf46da635980b5acb723496bba2c3f951293f | [
"MIT"
] | null | null | null | intermediate/Pet.cpp | loiola0/course-cpp | 43ddf46da635980b5acb723496bba2c3f951293f | [
"MIT"
] | null | null | null | #include <iostream>
#include "Pet.h"
using namespace std;
Pet::Pet(){
}
Pet::~Pet(){
}
void Pet::setValue(double value){
this->value = value;
}
void Pet::setBathFrequency(int bathFreq){
this->bathFrequency = bathFreq;
}
void Pet::getValue(){
cout<<"This Pet costs "<<"R$ "<<this->value<<endl;
}
void Pet::getBathFrequency(){
cout<<"This Pet takes a bath "<<this->bathFrequency<<" in "<<this->bathFrequency<<" days."<<endl;
}
| 13.529412 | 101 | 0.623913 | loiola0 |
44d8a03cdf9771642c87ea8f248310f7a897d86e | 1,715 | cpp | C++ | Engine/Engine/System/Debug.cpp | PawsEngine/Engine | 8a44cdd24b17227fdc3a3b52f1687d15f9ffe6be | [
"MIT"
] | 7 | 2021-05-01T12:52:29.000Z | 2022-02-06T10:50:45.000Z | Engine/Engine/System/Debug.cpp | PawsEngine/Engine | 8a44cdd24b17227fdc3a3b52f1687d15f9ffe6be | [
"MIT"
] | null | null | null | Engine/Engine/System/Debug.cpp | PawsEngine/Engine | 8a44cdd24b17227fdc3a3b52f1687d15f9ffe6be | [
"MIT"
] | 1 | 2021-05-16T15:52:16.000Z | 2021-05-16T15:52:16.000Z | #include "Engine/System/Debug.h"
#include <cstdio>
namespace Engine {
void DebugPrintInfo(const u8char* message) {
std::printf("%s\n", reinterpret_cast<const char*>(message));
}
void DebugPrintWarn(const char* func, const char* file, int line, const u8char* message) {
std::printf("\033[93m[WARNING] %s:\033[39m %s\n \033[33mAt:\033[90m %s\033[39m::\033[90m%d\033[0m\n", func, reinterpret_cast<const char*>(message), file, line);
}
void DebugPrintError(const char* func, const char* file, int line, const u8char* message) {
std::printf("\033[91m[ ERROR ] %s:\033[39m %s\n \033[31mAt:\033[90m %s\033[39m::\033[90m%d\033[0m\n", func, reinterpret_cast<const char*>(message), file, line);
}
void DebugPrintErrorAssert(const char* func, const char* file, int line, const char* expr, const u8char* message, const char* action) {
std::printf("\033[91m[ ERROR ] %s:\033[39m Assertion \"%s\" failed: %s Executing \"%s\".\n \033[31mAt:\033[90m %s\033[39m::\033[90m%d\033[0m\n", func, expr, reinterpret_cast<const char*>(message), action, file, line);
}
void DebugPrintFatal(const char* func, const char* file, int line, const u8char* message) {
std::printf("\033[97;101m[ FATAL ] %s:\033[39;49m %s\n \033[37;41mAt:\033[90;49m %s\033[39m::\033[90m%d\033[0m\n", func, reinterpret_cast<const char*>(message), file, line);
}
void DebugPrintFatalAssert(const char* func, const char* file, int line, const char* expr, const u8char* message) {
std::printf("\033[97;101m[ FATAL ] %s:\033[39;49m Assertion \"%s\" failed: %s Crashing.\n \033[37;41mAt:\033[90;49m %s\033[39m::\033[90m%d\033[0m\n", func, expr, reinterpret_cast<const char*>(message), file, line);
}
} | 74.565217 | 228 | 0.672303 | PawsEngine |
44dabd16fb4f17f0afb47c5bd36daea427bba016 | 24,832 | cpp | C++ | test/test_log_manager.cpp | XingjZhang/braft | 4515147ea61822e181fe5f781063651d03de9170 | [
"Apache-2.0"
] | null | null | null | test/test_log_manager.cpp | XingjZhang/braft | 4515147ea61822e181fe5f781063651d03de9170 | [
"Apache-2.0"
] | null | null | null | test/test_log_manager.cpp | XingjZhang/braft | 4515147ea61822e181fe5f781063651d03de9170 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
// Author: Zhangyi Chen (chenzhangyi01@baidu.com)
// Date: 2015/11/24 16:30:49
#include <gtest/gtest.h>
#include <butil/memory/scoped_ptr.h>
#include <butil/string_printf.h>
#include <butil/macros.h>
#include <bthread/countdown_event.h>
#include "braft/log_manager.h"
#include "braft/configuration.h"
#include "braft/log.h"
class LogManagerTest : public testing::Test {
protected:
LogManagerTest() {}
void SetUp() { }
void TearDown() { }
};
class StuckClosure : public braft::LogManager::StableClosure {
public:
StuckClosure()
: _stuck(NULL)
, _expected_next_log_index(NULL)
{}
~StuckClosure() {}
void Run() {
while (_stuck && *_stuck) {
bthread_usleep(100);
}
ASSERT_TRUE(status().ok()) << status();
if (_expected_next_log_index) {
ASSERT_EQ((*_expected_next_log_index)++, _first_log_index);
}
delete this;
}
private:
bool* _stuck;
int64_t* _expected_next_log_index;
};
class SyncClosure : public braft::LogManager::StableClosure {
public:
SyncClosure() : _event(1) {}
~SyncClosure() {
}
void Run() {
_event.signal();
}
void reset() {
status().reset();
_event.reset();
}
void join() {
_event.wait();
}
private:
bthread::CountdownEvent _event;
};
TEST_F(LogManagerTest, get_should_be_ok_when_disk_thread_stucks) {
bool stuck = true;
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
const size_t N = 10000;
DEFINE_SMALL_ARRAY(braft::LogEntry*, saved_entries, N, 256);
int64_t expected_next_log_index = 1;
for (size_t i = 0; i < N; ++i) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
entry->id = braft::LogId(i + 1, 1);
StuckClosure* c = new StuckClosure;
c->_stuck = &stuck;
c->_expected_next_log_index = &expected_next_log_index;
std::string buf;
butil::string_printf(&buf, "hello_%lu", i);
entry->data.append(buf);
entry->AddRef();
saved_entries[i] = entry;
std::vector<braft::LogEntry*> entries;
entries.push_back(entry);
lm->append_entries(&entries, c);
}
for (size_t i = 0; i < N; ++i) {
braft::LogEntry *entry = lm->get_entry(i + 1);
ASSERT_TRUE(entry != NULL) << "i=" << i;
std::string exptected;
butil::string_printf(&exptected, "hello_%lu", i);
ASSERT_EQ(exptected, entry->data.to_string());
entry->Release();
}
stuck = false;
LOG(INFO) << "Stop and join disk thraad";
ASSERT_EQ(0, lm->stop_disk_thread());
lm->clear_memory_logs(braft::LogId(N, 1));
// After clear all the memory logs, all the saved entries should have no
// other reference
for (size_t i = 0; i < N; ++i) {
ASSERT_EQ(1u, saved_entries[i]->ref_count_);
saved_entries[i]->Release();
}
}
TEST_F(LogManagerTest, configuration_changes) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
const size_t N = 5;
DEFINE_SMALL_ARRAY(braft::LogEntry*, saved_entries, N, 256);
braft::ConfigurationEntry conf;
SyncClosure sc;
for (size_t i = 0; i < N; ++i) {
std::vector<braft::PeerId> peers;
for (size_t j = 0; j <= i; ++j) {
peers.push_back(braft::PeerId(butil::EndPoint(), j));
}
std::vector<braft::LogEntry*> entries;
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_CONFIGURATION;
entry->peers = new std::vector<braft::PeerId>(peers);
if (peers.size() > 1u) {
entry->old_peers = new std::vector<braft::PeerId>(
peers.begin() + 1, peers.end());
}
entry->AddRef();
entry->id = braft::LogId(i + 1, 1);
saved_entries[i] = entry;
entries.push_back(entry);
sc.reset();
lm->append_entries(&entries, &sc);
ASSERT_TRUE(lm->check_and_set_configuration(&conf));
ASSERT_EQ(i + 1, conf.conf.size());
ASSERT_EQ(i, conf.old_conf.size());
sc.join();
ASSERT_TRUE(sc.status().ok()) << sc.status();
}
braft::ConfigurationEntry new_conf;
ASSERT_TRUE(lm->check_and_set_configuration(&new_conf));
ASSERT_EQ(N, new_conf.conf.size());
ASSERT_EQ(N - 1, new_conf.old_conf.size());
lm->clear_memory_logs(braft::LogId(N, 1));
// After clear all the memory logs, all the saved entries should have no
// other reference
for (size_t i = 0; i < N; ++i) {
ASSERT_EQ(1u, saved_entries[i]->ref_count_) << "i=" << i;
saved_entries[i]->Release();
}
}
TEST_F(LogManagerTest, truncate_suffix_also_revert_configuration) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
const size_t N = 5;
DEFINE_SMALL_ARRAY(braft::LogEntry*, saved_entries, N, 256);
braft::ConfigurationEntry conf;
SyncClosure sc;
for (size_t i = 0; i < N; ++i) {
std::vector<braft::PeerId> peers;
for (size_t j = 0; j <= i; ++j) {
peers.push_back(braft::PeerId(butil::EndPoint(), j));
}
std::vector<braft::LogEntry*> entries;
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_CONFIGURATION;
entry->peers = new std::vector<braft::PeerId>(peers);
entry->AddRef();
entry->id = braft::LogId(i + 1, 1);
saved_entries[i] = entry;
entries.push_back(entry);
sc.reset();
lm->append_entries(&entries, &sc);
ASSERT_TRUE(lm->check_and_set_configuration(&conf));
ASSERT_EQ(i + 1, conf.conf.size());
sc.join();
ASSERT_TRUE(sc.status().ok()) << sc.status();
}
braft::ConfigurationEntry new_conf;
ASSERT_TRUE(lm->check_and_set_configuration(&new_conf));
ASSERT_EQ(N, new_conf.conf.size());
lm->unsafe_truncate_suffix(2);
ASSERT_TRUE(lm->check_and_set_configuration(&new_conf));
ASSERT_EQ(2u, new_conf.conf.size());
lm->clear_memory_logs(braft::LogId(N, 1));
// After clear all the memory logs, all the saved entries should have no
// other reference
for (size_t i = 0; i < N; ++i) {
ASSERT_EQ(1u, saved_entries[i]->ref_count_) << "i=" << i;
saved_entries[i]->Release();
}
}
TEST_F(LogManagerTest, append_with_the_same_index) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
const size_t N = 1000;
std::vector<braft::LogEntry*> entries0;
for (size_t i = 0; i < N; ++i) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
std::string buf;
butil::string_printf(&buf, "hello_%lu", i);
entry->data.append(buf);
entry->id = braft::LogId(i + 1, 1);
entries0.push_back(entry);
entry->AddRef();
}
std::vector<braft::LogEntry*> saved_entries0(entries0);
SyncClosure sc;
lm->append_entries(&entries0, &sc);
sc.join();
ASSERT_TRUE(sc.status().ok()) << sc.status();
ASSERT_EQ(N, lm->last_log_index());
// Append the same logs, should be ok
std::vector<braft::LogEntry*> entries1;
for (size_t i = 0; i < N; ++i) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
std::string buf;
butil::string_printf(&buf, "hello_%lu", i);
entry->data.append(buf);
entry->id = braft::LogId(i + 1, 1);
entries1.push_back(entry);
entry->AddRef();
}
std::vector<braft::LogEntry*> saved_entries1(entries1);
sc.reset();
lm->append_entries(&entries1, &sc);
sc.join();
ASSERT_TRUE(sc.status().ok()) << sc.status();
ASSERT_EQ(N, lm->last_log_index());
for (size_t i = 0; i < N; ++i) {
ASSERT_EQ(3u, saved_entries0[i]->ref_count_ + saved_entries1[i]->ref_count_);
}
// new term should overwrite the old ones
std::vector<braft::LogEntry*> entries2;
for (size_t i = 0; i < N; ++i) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
std::string buf;
butil::string_printf(&buf, "hello_%lu", (i + 1) * 10);
entry->data.append(buf);
entry->id = braft::LogId(i + 1, 2);
entries2.push_back(entry);
entry->AddRef();
}
std::vector<braft::LogEntry*> saved_entries2(entries2);
sc.reset();
lm->append_entries(&entries2, &sc);
sc.join();
ASSERT_TRUE(sc.status().ok()) << sc.status();
ASSERT_EQ(N, lm->last_log_index());
for (size_t i = 0; i < N; ++i) {
ASSERT_EQ(1u, saved_entries0[i]->ref_count_);
ASSERT_EQ(1u, saved_entries1[i]->ref_count_);
ASSERT_EQ(2u, saved_entries2[i]->ref_count_);
}
for (size_t i = 0; i < N; ++i) {
braft::LogEntry* entry = lm->get_entry(i + 1);
ASSERT_TRUE(entry != NULL);
std::string buf;
butil::string_printf(&buf, "hello_%lu", (i + 1) * 10);
ASSERT_EQ(buf, entry->data.to_string());
ASSERT_EQ(braft::LogId(i + 1, 2), entry->id);
entry->Release();
}
lm->set_applied_id(braft::LogId(N, 2));
usleep(100 * 1000l);
for (size_t i = 0; i < N; ++i) {
ASSERT_EQ(1u, saved_entries0[i]->ref_count_);
ASSERT_EQ(1u, saved_entries1[i]->ref_count_);
ASSERT_EQ(1u, saved_entries2[i]->ref_count_);
}
for (size_t i = 0; i < N; ++i) {
braft::LogEntry* entry = lm->get_entry(i + 1);
ASSERT_TRUE(entry != NULL);
std::string buf;
butil::string_printf(&buf, "hello_%lu", (i + 1) * 10);
ASSERT_EQ(buf, entry->data.to_string());
ASSERT_EQ(braft::LogId(i + 1, 2), entry->id);
entry->Release();
}
for (size_t i = 0; i < N; ++i) {
saved_entries0[i]->Release();
saved_entries1[i]->Release();
saved_entries2[i]->Release();
}
}
TEST_F(LogManagerTest, pipelined_append) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
const size_t N = 1000;
braft::ConfigurationEntry conf;
std::vector<braft::LogEntry*> entries0;
for (size_t i = 0; i < N - 1; ++i) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
std::string buf;
butil::string_printf(&buf, "hello_%lu", 0lu);
entry->data.append(buf);
entry->id = braft::LogId(i + 1, 1);
entries0.push_back(entry);
entry->AddRef();
}
{
std::vector<braft::PeerId> peers;
peers.push_back(braft::PeerId("127.0.0.1:1234"));
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_CONFIGURATION;
entry->id = braft::LogId(N, 1);
entry->peers = new std::vector<braft::PeerId>(peers);
entries0.push_back(entry);
}
SyncClosure sc0;
lm->append_entries(&entries0, &sc0);
ASSERT_TRUE(lm->check_and_set_configuration(&conf));
ASSERT_EQ(braft::LogId(N, 1), conf.id);
ASSERT_EQ(1u, conf.conf.size());
ASSERT_EQ(N, lm->last_log_index());
// entries1 overwrites entries0
std::vector<braft::LogEntry*> entries1;
for (size_t i = 0; i < N - 1; ++i) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
std::string buf;
butil::string_printf(&buf, "hello_%lu", i + 1);
entry->data.append(buf);
entry->id = braft::LogId(i + 1, 2);
entries1.push_back(entry);
entry->AddRef();
}
{
std::vector<braft::PeerId> peers;
peers.push_back(braft::PeerId("127.0.0.2:1234"));
peers.push_back(braft::PeerId("127.0.0.2:2345"));
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_CONFIGURATION;
entry->id = braft::LogId(N, 2);
entry->peers = new std::vector<braft::PeerId>(peers);
entries1.push_back(entry);
}
SyncClosure sc1;
lm->append_entries(&entries1, &sc1);
ASSERT_TRUE(lm->check_and_set_configuration(&conf));
ASSERT_EQ(braft::LogId(N, 2), conf.id);
ASSERT_EQ(2u, conf.conf.size());
ASSERT_EQ(N, lm->last_log_index());
// entries2 is next to entries1
ASSERT_EQ(2, lm->get_term(N));
std::vector<braft::LogEntry*> entries2;
for (size_t i = N; i < 2 * N; ++i) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
std::string buf;
butil::string_printf(&buf, "hello_%lu", i + 1);
entry->data.append(buf);
entry->id = braft::LogId(i + 1, 2);
entries2.push_back(entry);
entry->AddRef();
}
SyncClosure sc2;
lm->append_entries(&entries2, &sc2);
ASSERT_FALSE(lm->check_and_set_configuration(&conf));
ASSERT_EQ(braft::LogId(N, 2), conf.id);
ASSERT_EQ(2u, conf.conf.size());
ASSERT_EQ(2 * N, lm->last_log_index());
LOG(INFO) << conf.conf;
// It's safe to get entry when disk thread is still running
for (size_t i = 0; i < 2 * N; ++i) {
braft::LogEntry* entry = lm->get_entry(i + 1);
ASSERT_TRUE(entry != NULL);
if (entry->type == braft::ENTRY_TYPE_DATA) {
std::string buf;
butil::string_printf(&buf, "hello_%lu", i + 1);
ASSERT_EQ(buf, entry->data.to_string());
}
ASSERT_EQ(braft::LogId(i + 1, 2), entry->id);
entry->Release();
}
sc0.join();
ASSERT_TRUE(sc0.status().ok()) << sc0.status();
sc1.join();
ASSERT_TRUE(sc1.status().ok()) << sc1.status();
sc2.join();
ASSERT_TRUE(sc2.status().ok()) << sc2.status();
// Wait set_disk_id to be called
usleep(100 * 1000l);
// Wrong applied id doesn't change _logs_in_memory
lm->set_applied_id(braft::LogId(N * 2, 1));
ASSERT_EQ(N * 2, lm->_logs_in_memory.size());
lm->set_applied_id(braft::LogId(N * 2, 2));
ASSERT_EQ(0u, lm->_logs_in_memory.size())
<< "last_log_id=" << lm->last_log_id(true);
// We can still get the right data from storage
for (size_t i = 0; i < 2 * N; ++i) {
braft::LogEntry* entry = lm->get_entry(i + 1);
ASSERT_TRUE(entry != NULL);
if (entry->type == braft::ENTRY_TYPE_DATA) {
std::string buf;
butil::string_printf(&buf, "hello_%lu", i + 1);
ASSERT_EQ(buf, entry->data.to_string());
}
ASSERT_EQ(braft::LogId(i + 1, 2), entry->id);
entry->Release();
}
}
TEST_F(LogManagerTest, set_snapshot) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
braft::SnapshotMeta meta;
meta.set_last_included_index(1000);
meta.set_last_included_term(2);
lm->set_snapshot(&meta, meta.last_included_index());
ASSERT_EQ(braft::LogId(1000, 2), lm->last_log_id(false));
}
int on_new_log(void* arg, int /*error_code*/) {
SyncClosure* sc = (SyncClosure*)arg;
sc->Run();
return 0;
}
int append_entry(braft::LogManager* lm, butil::StringPiece data, int64_t index, int64_t term = 1) {
braft::LogEntry* entry = new braft::LogEntry;
entry->AddRef();
entry->type = braft::ENTRY_TYPE_DATA;
entry->data.append(data.data(), data.size());
entry->id = braft::LogId(index, term);
SyncClosure sc;
std::vector<braft::LogEntry*> entries;
entries.push_back(entry);
lm->append_entries(&entries, &sc);
sc.join();
return sc.status().error_code();
}
TEST_F(LogManagerTest, wait) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
SyncClosure sc;
braft::LogManager::WaitId wait_id =
lm->wait(lm->last_log_index(), on_new_log, &sc);
ASSERT_NE(0, wait_id);
ASSERT_EQ(0, lm->remove_waiter(wait_id));
ASSERT_EQ(0, append_entry(lm.get(), "hello", 1));
wait_id = lm->wait(0, on_new_log, &sc);
ASSERT_EQ(0, wait_id);
sc.join();
sc.reset();
wait_id = lm->wait(lm->last_log_index(), on_new_log, &sc);
ASSERT_NE(0, wait_id);
ASSERT_EQ(0, append_entry(lm.get(), "hello", 2));
sc.join();
ASSERT_NE(0, lm->remove_waiter(wait_id));
}
TEST_F(LogManagerTest, flush_and_get_last_id) {
system("rm -rf ./data");
{
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
braft::SnapshotMeta meta;
meta.set_last_included_index(100);
meta.set_last_included_term(100);
lm->set_snapshot(&meta, meta.last_included_index());
ASSERT_EQ(braft::LogId(100, 100), lm->last_log_id(false));
ASSERT_EQ(braft::LogId(100, 100), lm->last_log_id(true));
}
// Load from disk again
{
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
braft::SnapshotMeta meta;
meta.set_last_included_index(100);
meta.set_last_included_term(100);
lm->set_snapshot(&meta, meta.last_included_index());
ASSERT_EQ(braft::LogId(100, 100), lm->last_log_id(false));
ASSERT_EQ(braft::LogId(100, 100), lm->last_log_id(true));
}
}
TEST_F(LogManagerTest, check_consistency) {
system("rm -rf ./data");
{
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
butil::Status st;
st = lm->check_consistency();
ASSERT_TRUE(st.ok()) << st;
braft::SnapshotMeta meta;
for (int i = 1; i < 1001; ++i) {
append_entry(lm.get(), "dummy", i);
}
st = lm->check_consistency();
ASSERT_TRUE(st.ok()) << st;
meta.set_last_included_index(100);
meta.set_last_included_term(1);
lm->set_snapshot(&meta, meta.last_included_index());
st = lm->check_consistency();
ASSERT_TRUE(st.ok()) << st;
lm->clear_bufferred_logs();
st = lm->check_consistency();
ASSERT_TRUE(st.ok()) << st;
}
{
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
butil::Status st;
st = lm->check_consistency();
LOG(INFO) << "st : " << st;
ASSERT_FALSE(st.ok()) << st;
}
}
TEST_F(LogManagerTest, truncate_suffix_to_last_snapshot) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
butil::Status st;
ASSERT_TRUE(st.ok()) << st;
braft::SnapshotMeta meta;
meta.set_last_included_index(1000);
meta.set_last_included_term(2);
lm->set_snapshot(&meta, meta.last_included_index());
ASSERT_EQ(braft::LogId(1000, 2), lm->last_log_id(true));
ASSERT_EQ(0, append_entry(lm.get(), "dummy2", 1001, 2));
ASSERT_EQ(0, append_entry(lm.get(), "dummy3", 1001, 3));
ASSERT_EQ(braft::LogId(1001, 3), lm->last_log_id(true));
}
TEST_F(LogManagerTest, set_snapshot_and_get_log_term) {
system("rm -rf ./data");
scoped_ptr<braft::ConfigurationManager> cm(
new braft::ConfigurationManager);
scoped_ptr<braft::SegmentLogStorage> storage(
new braft::SegmentLogStorage("./data"));
scoped_ptr<braft::LogManager> lm(new braft::LogManager());
braft::LogManagerOptions opt;
opt.log_storage = storage.get();
opt.configuration_manager = cm.get();
ASSERT_EQ(0, lm->init(opt));
const int N = 10;
for (int i = 0; i < N; ++i) {
append_entry(lm.get(), "test", i + 1, 1);
}
braft::SnapshotMeta meta;
meta.set_last_included_index(N - 1);
meta.set_last_included_term(1);
lm->set_snapshot(&meta, meta.last_included_index());
lm->set_snapshot(&meta, meta.last_included_index());
ASSERT_EQ(braft::LogId(N, 1), lm->last_log_id());
ASSERT_EQ(1L, lm->get_term(N - 1));
LOG(INFO) << "Last_index=" << lm->last_log_index();
}
| 36.304094 | 99 | 0.596207 | XingjZhang |
44dfbdaa5b90596cd9d29c0b8e73bc1338e6e159 | 1,834 | cpp | C++ | communicating_socket.cpp | tvaleev/simple-udp-server-client | 52685c7e808e89ed52e7017dfc6226ce3500a097 | [
"BSD-2-Clause"
] | null | null | null | communicating_socket.cpp | tvaleev/simple-udp-server-client | 52685c7e808e89ed52e7017dfc6226ce3500a097 | [
"BSD-2-Clause"
] | null | null | null | communicating_socket.cpp | tvaleev/simple-udp-server-client | 52685c7e808e89ed52e7017dfc6226ce3500a097 | [
"BSD-2-Clause"
] | null | null | null | #include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "communicating_socket.h"
#include "socket_utils.h"
typedef void raw_type;
CommunicatingSocket::CommunicatingSocket(int type, int protocol)
: Socket(type, protocol) {
}
CommunicatingSocket::CommunicatingSocket(int newConnSD) : Socket(newConnSD) {
}
void CommunicatingSocket::connect(const std::string &foreignAddress,
unsigned short foreignPort) {
// Get the address of the requested host
sockaddr_in destAddr;
fillAddr(foreignAddress, foreignPort, destAddr);
// Try to connect to the given port
if (::connect(getSocketDescriptor(), (sockaddr *) &destAddr, sizeof(destAddr)) < 0) {
throw SocketException("Connect failed", true);
}
}
void CommunicatingSocket::send(const void *buffer, int bufferLen) {
if (::send(getSocketDescriptor(), (raw_type *) buffer, bufferLen, 0) < 0) {
throw SocketException("Send failed", true);
}
}
int CommunicatingSocket::recv(void *buffer, int bufferLen) {
int rtn;
if ((rtn = ::recv(getSocketDescriptor(), (raw_type *) buffer, bufferLen, 0)) < 0) {
throw SocketException("Received failed", true);
}
return rtn;
}
std::string CommunicatingSocket::getForeignAddress() {
sockaddr_in addr;
unsigned int addr_len = sizeof(addr);
if (getpeername(getSocketDescriptor(), (sockaddr *) &addr,(socklen_t *) &addr_len) < 0) {
throw SocketException("Fetch of foreign address failed", true);
}
return inet_ntoa(addr.sin_addr);
}
unsigned short CommunicatingSocket::getForeignPort() {
sockaddr_in addr;
unsigned int addr_len = sizeof(addr);
if (getpeername(getSocketDescriptor(), (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
throw SocketException("Fetch of foreign port failed", true);
}
return ntohs(addr.sin_port);
} | 29.580645 | 92 | 0.706107 | tvaleev |
44e1f222268f4c1b12c62d74546ba35da97f3aa8 | 2,079 | cc | C++ | modules/prediction/common/junction_analyzer_test.cc | ghdawn/apollo | 002eba4a1635d6af7f1ebd2118464bca6f86b106 | [
"Apache-2.0"
] | 2 | 2019-01-15T08:34:59.000Z | 2019-01-15T08:35:00.000Z | modules/prediction/common/junction_analyzer_test.cc | thomasgui76/apollo | 808f1d20a08efea23b718b4e423d6619c9d4b412 | [
"Apache-2.0"
] | null | null | null | modules/prediction/common/junction_analyzer_test.cc | thomasgui76/apollo | 808f1d20a08efea23b718b4e423d6619c9d4b412 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/common/junction_analyzer.h"
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
namespace apollo {
namespace prediction {
class JunctionAnalyzerTest : public KMLMapBasedTest {};
TEST_F(JunctionAnalyzerTest, SingleLane) {
JunctionAnalyzer::Init("j2");
EXPECT_NEAR(JunctionAnalyzer::ComputeJunctionRange(), 74.0306, 0.001);
const JunctionFeature& junction_feature =
JunctionAnalyzer::GetJunctionFeature("l61");
EXPECT_EQ(junction_feature.junction_id(), "j2");
EXPECT_EQ(junction_feature.enter_lane().lane_id(), "l61");
EXPECT_GT(junction_feature.junction_exit_size(), 0);
JunctionAnalyzer::Clear();
}
TEST_F(JunctionAnalyzerTest, MultiLane) {
JunctionAnalyzer::Init("j2");
const JunctionFeature& merged_junction_feature =
JunctionAnalyzer::GetJunctionFeature(
std::vector<std::string> {"l35", "l61", "l114", "l162"});
EXPECT_EQ(merged_junction_feature.junction_id(), "j2");
EXPECT_EQ(merged_junction_feature.junction_exit_size(), 3);
JunctionAnalyzer::Clear();
}
} // namespace prediction
} // namespace apollo
| 36.473684 | 79 | 0.700818 | ghdawn |
44e58eb4b426b3c9c9c34b4da22c5f0ce60e24c5 | 414 | hpp | C++ | src/stan/lang/ast/fun/fun_name_exists.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2019-07-05T01:40:40.000Z | 2019-07-05T01:40:40.000Z | src/stan/lang/ast/fun/fun_name_exists.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | null | null | null | src/stan/lang/ast/fun/fun_name_exists.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2020-07-14T11:36:09.000Z | 2020-07-14T11:36:09.000Z | #ifndef STAN_LANG_AST_FUN_FUN_NAME_EXISTS_HPP
#define STAN_LANG_AST_FUN_FUN_NAME_EXISTS_HPP
#include <string>
namespace stan {
namespace lang {
/**
* Return true if the function name has been declared as a
* built-in or by the user.
*
* @param name name of function
* @return true if it has been declared
*/
bool fun_name_exists(const std::string& name);
}
}
#endif
| 19.714286 | 62 | 0.681159 | drezap |
44e67034d3523b25984223ad8cdf52146528a34d | 1,290 | cpp | C++ | Fw/Port/OutputPortBase.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 9,182 | 2017-07-06T15:51:35.000Z | 2022-03-30T11:20:33.000Z | Fw/Port/OutputPortBase.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 719 | 2017-07-14T17:56:01.000Z | 2022-03-31T02:41:35.000Z | Fw/Port/OutputPortBase.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 1,216 | 2017-07-12T15:41:08.000Z | 2022-03-31T21:44:37.000Z | #include <FpConfig.hpp>
#include <Fw/Port/OutputPortBase.hpp>
#include <Fw/Types/BasicTypes.hpp>
#include <Os/Log.hpp>
#include <cstdio>
#include <Fw/Types/Assert.hpp>
namespace Fw {
OutputPortBase::OutputPortBase() : PortBase()
#if FW_PORT_SERIALIZATION == 1
,m_serPort(nullptr)
#endif
{
}
OutputPortBase::~OutputPortBase() {
}
void OutputPortBase::init() {
PortBase::init();
}
#if FW_PORT_SERIALIZATION == 1
void OutputPortBase::registerSerialPort(InputPortBase* port) {
FW_ASSERT(port);
this->m_connObj = port;
this->m_serPort = port;
}
SerializeStatus OutputPortBase::invokeSerial(SerializeBufferBase &buffer) {
FW_ASSERT(this->m_serPort);
return this->m_serPort->invokeSerial(buffer);
}
#endif
#if FW_OBJECT_TO_STRING == 1
void OutputPortBase::toString(char* buffer, NATIVE_INT_TYPE size) {
#if FW_OBJECT_NAMES == 1
FW_ASSERT(size > 0);
if (snprintf(buffer, size, "OutputPort: %s %s->(%s)", this->m_objName, this->isConnected() ? "C" : "NC",
this->isConnected() ? this->m_connObj->getObjName() : "None") < 0) {
buffer[0] = 0;
}
#else
(void)snprintf(buffer,size,"%s","OutputPort");
#endif
}
#endif
}
| 22.631579 | 112 | 0.624031 | AlperenCetin0 |
44e7bc0d2fc90dab6eef82e6871b38b1ca0c562f | 974 | hpp | C++ | clammbon/include/test_tool.hpp | tnct-spc/procon2014 | c2df3257675db2adb9caa882b9026145801c6e4d | [
"MIT"
] | 1 | 2016-11-02T08:42:05.000Z | 2016-11-02T08:42:05.000Z | clammbon/include/test_tool.hpp | tnct-spc/procon2014 | c2df3257675db2adb9caa882b9026145801c6e4d | [
"MIT"
] | null | null | null | clammbon/include/test_tool.hpp | tnct-spc/procon2014 | c2df3257675db2adb9caa882b9026145801c6e4d | [
"MIT"
] | null | null | null | #ifndef CLAMMBON_TEST_TOOL_HPP
#define CLAMMBON_TEST_TOOL_HPP
#include <vector>
#include <iostream>
#include <boost/noncopyable.hpp>
#include "data_type.hpp"
namespace test_tool
{
class emulator : boost::noncopyable
{
public:
typedef std::vector<std::vector<point_type>> locate_type;
struct return_type
{
int cost;
int wrong;
};
emulator(question_data const& question);
virtual ~emulator() = default;
auto start(answer_type const& answer) -> return_type;
private:
// 識別子(U,D,R,L)と基準位置(reference)から,対象となる交換先を見つける
point_type target_point(char const identifier, point_type const& reference) const;
auto emulate_movement(answer_type const& answer) -> locate_type;
int count_cost(answer_type const& answer);
int count_correct(locate_type const& locate);
question_data const question_;
};
} // namespace test_tool
#endif
| 23.756098 | 90 | 0.664271 | tnct-spc |
44e8aa8a193f9093e0f5d90943c3bb41b4007f19 | 9,047 | cpp | C++ | source/MaterialXTest/MaterialXCore/Look.cpp | muenstc/MaterialX | b8365086a738fddae683065d78f65410aacd0dc4 | [
"BSD-3-Clause"
] | null | null | null | source/MaterialXTest/MaterialXCore/Look.cpp | muenstc/MaterialX | b8365086a738fddae683065d78f65410aacd0dc4 | [
"BSD-3-Clause"
] | null | null | null | source/MaterialXTest/MaterialXCore/Look.cpp | muenstc/MaterialX | b8365086a738fddae683065d78f65410aacd0dc4 | [
"BSD-3-Clause"
] | null | null | null | //
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXTest/Catch/catch.hpp>
#include <MaterialXCore/Document.h>
#include <MaterialXFormat/XmlIo.h>
namespace mx = MaterialX;
TEST_CASE("Look", "[look]")
{
mx::DocumentPtr doc = mx::createDocument();
// Create a material and look.
mx::NodePtr shaderNode = doc->addNode("standard_surface", "", "surfaceshader");
mx::NodePtr materialNode = doc->addMaterialNode("", shaderNode);
mx::LookPtr look = doc->addLook();
// Bind the material to a geometry string.
mx::MaterialAssignPtr matAssign1 = look->addMaterialAssign("matAssign1", materialNode->getName());
matAssign1->setGeom("/robot1");
REQUIRE(matAssign1->getReferencedMaterial() == materialNode);
REQUIRE(getGeometryBindings(materialNode, "/robot1").size() == 1);
REQUIRE(getGeometryBindings(materialNode, "/robot2").size() == 0);
// Bind the material to a geometric collection.
mx::MaterialAssignPtr matAssign2 = look->addMaterialAssign("matAssign2", materialNode->getName());
mx::CollectionPtr collection = doc->addCollection();
collection->setIncludeGeom("/robot2");
collection->setExcludeGeom("/robot2/left_arm");
matAssign2->setCollection(collection);
REQUIRE(getGeometryBindings(materialNode, "/robot2").size() == 1);
REQUIRE(getGeometryBindings(materialNode, "/robot2/right_arm").size() == 1);
REQUIRE(getGeometryBindings(materialNode, "/robot2/left_arm").size() == 0);
// Create a property assignment.
mx::PropertyAssignPtr propertyAssign = look->addPropertyAssign();
propertyAssign->setProperty("twosided");
propertyAssign->setGeom("/robot1");
propertyAssign->setValue(true);
REQUIRE(propertyAssign->getProperty() == "twosided");
REQUIRE(propertyAssign->getGeom() == "/robot1");
REQUIRE(propertyAssign->getValue()->isA<bool>());
REQUIRE(propertyAssign->getValue()->asA<bool>() == true);
// Create a property set assignment.
mx::PropertySetPtr propertySet = doc->addPropertySet();
propertySet->setPropertyValue("matte", false);
REQUIRE(propertySet->getPropertyValue("matte")->isA<bool>());
REQUIRE(propertySet->getPropertyValue("matte")->asA<bool>() == false);
mx::PropertySetAssignPtr propertySetAssign = look->addPropertySetAssign();
propertySetAssign->setPropertySet(propertySet);
propertySetAssign->setGeom("/robot1");
REQUIRE(propertySetAssign->getPropertySet() == propertySet);
REQUIRE(propertySetAssign->getGeom() == "/robot1");
// Create a variant set.
mx::VariantSetPtr variantSet = doc->addVariantSet("damageVars");
variantSet->addVariant("original");
variantSet->addVariant("damaged");
REQUIRE(variantSet->getVariants().size() == 2);
// Create a visibility element.
mx::VisibilityPtr visibility = look->addVisibility();
REQUIRE(visibility->getVisible() == false);
visibility->setVisible(true);
REQUIRE(visibility->getVisible() == true);
visibility->setGeom("/robot2");
REQUIRE(visibility->getGeom() == "/robot2");
visibility->setCollection(collection);
REQUIRE(visibility->getCollection() == collection);
// Create an inherited look.
mx::LookPtr look2 = doc->addLook();
look2->setInheritsFrom(look);
REQUIRE(look2->getActivePropertySetAssigns().size() == 1);
REQUIRE(look2->getActiveVisibilities().size() == 1);
// Create and detect an inheritance cycle.
look->setInheritsFrom(look2);
REQUIRE(!doc->validate());
look->setInheritsFrom(nullptr);
REQUIRE(doc->validate());
// Disconnect the inherited look.
look2->setInheritsFrom(nullptr);
REQUIRE(look2->getActivePropertySetAssigns().empty());
REQUIRE(look2->getActiveVisibilities().empty());
}
TEST_CASE("LookGroup", "[look]")
{
mx::DocumentPtr doc = mx::createDocument();
mx::LookGroupPtr lookGroup = doc->addLookGroup("lookgroup1");
std::vector<mx::LookGroupPtr> lookGroups = doc->getLookGroups();
REQUIRE(lookGroups.size() == 1);
mx::StringMap mergeMap;
const std::string looks = "look1,look2,look3,look4,look5";
mx::StringVec looksVec = mx::splitString(looks, mx::ARRAY_VALID_SEPARATORS);
for (const std::string& lookName : looksVec)
{
mx::LookPtr look = doc->addLook(lookName);
look->addMaterialAssign("matA", "materialA");
look->addMaterialAssign("matB", "materialB");
look->addMaterialAssign("matC", "materialC");
if (lookName != "look1")
{
mergeMap[lookName + "_matA"] = "materialA";
mergeMap[lookName + "_matB"] = "materialB";
mergeMap[lookName + "_matC"] = "materialC";
}
else
{
mergeMap["matA"] = "materialA";
mergeMap["matB"] = "materialB";
mergeMap["matC"] = "materialC";
}
REQUIRE(look != nullptr);
}
lookGroup->setLooks(looks);
const std::string& looks2 = lookGroup->getLooks();
mx::StringVec looksVec2 = mx::splitString(looks2, mx::ARRAY_VALID_SEPARATORS);
REQUIRE(looksVec.size() == looksVec2.size());
REQUIRE(lookGroup->getEnabledLooksString().empty());
lookGroup->setEnabledLooks("look1");
REQUIRE(lookGroup->getEnabledLooksString() == "look1");
mx::LookGroupPtr copyLookGroup = doc->addLookGroup("lookgroup1_copy");
copyLookGroup->copyContentFrom(lookGroup);
mx::writeToXmlFile(doc, "looks_test.mtlx");
// Combine looks in lookgroup test
lookGroup->setEnabledLooks(looks);
mx::LookPtr mergedLook = lookGroup->combineLooks();
REQUIRE(mergedLook->getMaterialAssigns().size() == 15);
for (auto ma : mergedLook->getMaterialAssigns())
{
REQUIRE(mergeMap.find(ma->getName()) != mergeMap.end());
REQUIRE(mergeMap[ma->getName()] == ma->getMaterial());
}
mx::writeToXmlFile(doc, "looks_test_merged.mtlx");
doc->removeLook(mergedLook->getName());
REQUIRE(doc->getLooks().size() == 5);
doc->removeLookGroup(lookGroup->getName());
// Combine lookgroups test
mx::LookGroupPtr lookGroup2 = doc->addLookGroup("lookgroup2");
std::string lookGroup2_looks = "lookA,look1,lookC,look3,lookE";
looksVec2 = mx::splitString(lookGroup2_looks, mx::ARRAY_VALID_SEPARATORS);
for (const std::string& lookName2 : looksVec2)
{
// Skip duplcates
if (doc->getLook(lookName2))
{
continue;
}
mx::LookPtr look = doc->addLook(lookName2);
look->addMaterialAssign("matA", "materialA");
look->addMaterialAssign("matB", "materialB");
look->addMaterialAssign("matC", "materialC");
}
lookGroup2->setLooks(lookGroup2_looks);
lookGroup2->setEnabledLooks("lookA,look3,lookE");
// Append check
mx::LookGroupPtr mergedCopyLookGroup = doc->addLookGroup("lookgroup1_copy_merged");
mergedCopyLookGroup->copyContentFrom(copyLookGroup);
mergedCopyLookGroup->appendLookGroup(lookGroup2);
mx::writeToXmlFile(doc, "lookgroup_test_merged.mtlx");
REQUIRE(mergedCopyLookGroup->getLooks() == std::string("look1, look2, look3, look4, look5, lookA, lookC, lookE"));
REQUIRE(mergedCopyLookGroup->getEnabledLooksString() == std::string("look1, lookA, look3, lookE"));
// Insert check
mx::LookGroupPtr mergedCopyLookGroup2 = doc->addLookGroup("lookgroup1_copy_merged2");
mergedCopyLookGroup2->copyContentFrom(copyLookGroup);
mergedCopyLookGroup2->appendLookGroup(lookGroup2, std::string("look2"));
mx::writeToXmlFile(doc, "lookgroup_test_merged2.mtlx");
REQUIRE(mergedCopyLookGroup2->getLooks() == std::string("look1, look2, lookA, lookC, lookE, look3, look4, look5"));
REQUIRE(mergedCopyLookGroup2->getEnabledLooksString() == std::string("look1, lookA, look3, lookE"));
mx::LookGroupPtr mergedCopyLookGroup3 = doc->addLookGroup("lookgroup1_copy_merged3");
mergedCopyLookGroup3->copyContentFrom(copyLookGroup);
mergedCopyLookGroup3->appendLookGroup(lookGroup2, std::string("not found"));
mx::writeToXmlFile(doc, "lookgroup_test_merge3.mtlx");
REQUIRE(mergedCopyLookGroup2->getLooks() == std::string("look1, look2, lookA, lookC, lookE, look3, look4, look5"));
REQUIRE(mergedCopyLookGroup2->getEnabledLooksString() == std::string("look1, lookA, look3, lookE"));
doc->addLook("look6");
mergedCopyLookGroup2->appendLook("look6", "lookC");
REQUIRE(mergedCopyLookGroup2->getLooks() == std::string("look1, look2, lookA, lookC, look6, lookE, look3, look4, look5"));
REQUIRE(mergedCopyLookGroup2->getEnabledLooksString() == std::string("look1, lookA, look3, lookE, look6"));
doc->removeLookGroup(lookGroup2->getName());
doc->removeLookGroup(copyLookGroup->getName());
doc->removeLookGroup(mergedCopyLookGroup->getName());
doc->removeLookGroup(mergedCopyLookGroup2->getName());
doc->removeLookGroup(mergedCopyLookGroup3->getName());
lookGroups = doc->getLookGroups();
REQUIRE(lookGroups.size() == 0);
}
| 42.275701 | 126 | 0.687631 | muenstc |
44e91b6f7a2492eba19372cf36601d39c7fe88cc | 119 | cpp | C++ | private/sources/kqueue/kqueue_async_service.cpp | rnichollx/rpnx-core | 9c7e3e54a729eafad4dba2bdc730ec2b88b8927c | [
"MIT"
] | 4 | 2020-11-23T23:27:32.000Z | 2022-03-06T03:46:51.000Z | private/sources/kqueue/kqueue_async_service.cpp | rpnx-net/rpnx-core | d579c3a159b624ee9115cb0633879ce716401ca1 | [
"MIT"
] | 20 | 2021-04-12T23:47:37.000Z | 2021-06-08T02:06:18.000Z | private/sources/kqueue/kqueue_async_service.cpp | rpnx-net/rpnx-core | d579c3a159b624ee9115cb0633879ce716401ca1 | [
"MIT"
] | null | null | null | // This file is an async_service implementation for Operating Systems that use KQueue (Mac OSX and BSD in particular)
| 39.666667 | 117 | 0.798319 | rnichollx |
44e9b5b20bcdf28824affe2e759e29ce9c137a81 | 7,905 | cpp | C++ | native/python/pyjp_value.cpp | mattooca/jpype | e1741e28818e1d4956834aa37b21a2bf3142b7a1 | [
"Apache-2.0"
] | null | null | null | native/python/pyjp_value.cpp | mattooca/jpype | e1741e28818e1d4956834aa37b21a2bf3142b7a1 | [
"Apache-2.0"
] | null | null | null | native/python/pyjp_value.cpp | mattooca/jpype | e1741e28818e1d4956834aa37b21a2bf3142b7a1 | [
"Apache-2.0"
] | null | null | null | /*****************************************************************************
Copyright 2004-2008 Steve Ménard
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 <pyjp.h>
static PyMethodDef classMethods[] = {
{"toString", (PyCFunction) (&PyJPValue::toString), METH_NOARGS, ""},
{NULL},
};
PyTypeObject PyJPValue::Type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_jpype.PyJPValue",
/* tp_basicsize */ sizeof (PyJPValue),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor) PyJPValue::__dealloc__,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_compare */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ (reprfunc) PyJPValue::__str__,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
/* tp_doc */
"Wrapper of a java value which holds a class and instance of an object \n"
"or a primitive. This object is always stored as the attributed \n"
"__javavalue__. Anything with this type with that attribute will be\n"
"considered a java object wrapper.",
/* tp_traverse */ (traverseproc) PyJPValue::traverse,
/* tp_clear */ (inquiry) PyJPValue::clear,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ classMethods,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ (initproc) PyJPValue::__init__,
/* tp_alloc */ 0,
/* tp_new */ PyJPValue::__new__
};
// Static methods
void PyJPValue::initType(PyObject* module)
{
PyType_Ready(&PyJPValue::Type);
Py_INCREF(&PyJPValue::Type);
PyModule_AddObject(module, "PyJPValue", (PyObject*) (&PyJPValue::Type));
}
// These are from the internal methods when we alreayd have the jvalue
JPPyObject PyJPValue::alloc(const JPValue& value)
{
return alloc(value.getClass(), value.getValue());
}
JPPyObject PyJPValue::alloc(JPClass* cls, jvalue value)
{
JPJavaFrame frame;
JP_TRACE_IN("PyJPValue::alloc");
PyJPValue* self = (PyJPValue*) PyJPValue::Type.tp_alloc(&PyJPValue::Type, 0);
JP_PY_CHECK();
// If it is not a primitive we need to reference it
if (!cls->isPrimitive())
value.l = frame.NewGlobalRef(value.l);
// New value instance
self->m_Value = JPValue(cls, value);
self->m_Cache = NULL;
JP_TRACE("Value", self->m_Value.getClass()->getCanonicalName(), &(self->m_Value.getValue()));
return JPPyObject(JPPyRef::_claim, (PyObject*) self);
JP_TRACE_OUT;
}
PyObject* PyJPValue::__new__(PyTypeObject* type, PyObject* args, PyObject* kwargs)
{
PyJPValue* self = (PyJPValue*) type->tp_alloc(type, 0);
jvalue v;
self->m_Value = JPValue(NULL, v);
self->m_Cache = NULL;
return (PyObject*) self;
}
// Replacement for convertToJava.
int PyJPValue::__init__(PyJPValue* self, PyObject* args, PyObject* kwargs)
{
JP_TRACE_IN("PyJPValue::__init__");
try
{
ASSERT_JVM_RUNNING("PyJPValue::__init__");
JPJavaFrame frame;
self->m_Cache = NULL;
PyObject* claz;
PyObject* value;
if (!PyArg_ParseTuple(args, "O!O", &PyJPClass::Type, &claz, &value))
{
return -1;
}
JPClass* type = ((PyJPClass*) claz)->m_Class;
ASSERT_NOT_NULL(value);
ASSERT_NOT_NULL(type);
// If it is already a Java object, then let Java decide
// if the cast is possible
JPValue* jval = JPPythonEnv::getJavaValue(value);
if (jval != NULL && type->isInstance(*jval))
{
jvalue v = jval->getValue();
v.l = frame.NewGlobalRef(v.l);
self->m_Value = JPValue(type, v);
return 0;
}
// Otherwise, see if we can convert it
if (type->canConvertToJava(value) == JPMatch::_none)
{
stringstream ss;
ss << "Unable to convert " << Py_TYPE(value)->tp_name << " to java type " << type->toString();
PyErr_SetString(PyExc_TypeError, ss.str().c_str());
return -1;
}
jvalue v = type->convertToJava(value);
if (!type->isPrimitive())
v.l = frame.NewGlobalRef(v.l);
self->m_Value = JPValue(type, v);
return 0;
}
PY_STANDARD_CATCH;
return -1;
JP_TRACE_OUT;
}
PyObject* PyJPValue::__str__(PyJPValue* self)
{
try
{
ASSERT_JVM_RUNNING("PyJPValue::__str__");
JPJavaFrame frame;
stringstream sout;
sout << "<java value " << self->m_Value.getClass()->toString();
// FIXME Remove these extra diagnostic values
if ((self->m_Value.getClass())->isPrimitive())
sout << endl << " value = primitive";
else
{
jobject jo = self->m_Value.getJavaObject();
sout << " value = " << jo << " " << JPJni::toString(jo);
}
sout << ">";
return JPPyString::fromStringUTF8(sout.str()).keep();
}
PY_STANDARD_CATCH;
return 0;
}
void PyJPValue::__dealloc__(PyJPValue* self)
{
JP_TRACE_IN("PyJPValue::__dealloc__");
JPValue& value = self->m_Value;
JPClass* cls = value.getClass();
// This one can't check for initialized because we may need to delete a stale
// resource after shutdown.
if (cls != NULL && JPEnv::isInitialized() && !cls->isPrimitive())
{
JP_TRACE("Value", cls->getCanonicalName(), &(value.getValue()));
// If the JVM has shutdown then we don't need to free the resource
// FIXME there is a problem with initializing the sytem twice.
// Once we shut down the cls type goes away so this will fail. If
// we then reinitialize we will access this bad resource. Not sure
// of an easy solution.
JP_TRACE("Dereference object");
JPJavaFrame::ReleaseGlobalRef(value.getValue().l);
}
PyObject_GC_UnTrack(self);
clear(self);
Py_TYPE(self)->tp_free(self);
JP_TRACE_OUT;
}
int PyJPValue::traverse(PyJPValue *self, visitproc visit, void *arg)
{
Py_VISIT(self->m_Cache);
return 0;
}
int PyJPValue::clear(PyJPValue *self)
{
Py_CLEAR(self->m_Cache);
return 0;
}
void ensureCache(PyJPValue* self)
{
if (self->m_Cache != NULL)
return;
self->m_Cache = PyDict_New();
}
/** This is the way to convert an object into a python string. */
PyObject* PyJPValue::toString(PyJPValue* self)
{
JP_TRACE_IN("PyJPValue::toString");
try
{
ASSERT_JVM_RUNNING("PyJPValue::toString");
JPJavaFrame frame;
JPClass* cls = self->m_Value.getClass();
if (cls == JPTypeManager::_java_lang_String)
{
// Java strings are immutable so we will cache them.
ensureCache(self);
PyObject* out;
out = PyDict_GetItemString(self->m_Cache, "str"); // Borrowed reference
if (out == NULL)
{
jstring str = (jstring) self->m_Value.getValue().l;
if (str == NULL)
JP_RAISE_VALUE_ERROR("null string");
PyDict_SetItemString(self->m_Cache, "str", out = JPPyString::fromStringUTF8(JPJni::toStringUTF8(str)).keep());
}
Py_INCREF(out);
return out;
}
if (cls->isPrimitive())
JP_RAISE_VALUE_ERROR("toString requires a java object");
if (cls == NULL)
JP_RAISE_VALUE_ERROR("toString called with null class");
// In general toString is not immutable, so we won't cache it.
return JPPyString::fromStringUTF8(JPJni::toString(self->m_Value.getValue().l)).keep();
}
PY_STANDARD_CATCH;
return 0;
JP_TRACE_OUT;
}
| 28.956044 | 114 | 0.647312 | mattooca |
44eb91efce60308b63c90825b1b66296f3bdb22c | 5,353 | cpp | C++ | src/RaceNet/TrainingGround.cpp | janisozaur/OpenNFS | d2bce25a3ab8ddab67e8b75e920cd60b832b279a | [
"MIT"
] | null | null | null | src/RaceNet/TrainingGround.cpp | janisozaur/OpenNFS | d2bce25a3ab8ddab67e8b75e920cd60b832b279a | [
"MIT"
] | null | null | null | src/RaceNet/TrainingGround.cpp | janisozaur/OpenNFS | d2bce25a3ab8ddab67e8b75e920cd60b832b279a | [
"MIT"
] | null | null | null | //
// Created by Amrik on 28/10/2018.
//
#include "TrainingGround.h"
TrainingGround::TrainingGround(uint16_t populationSize, uint16_t nGenerations, uint32_t nTicks, shared_ptr<ONFSTrack> training_track, shared_ptr<Car> training_car, std::shared_ptr<Logger> logger, GLFWwindow *gl_window) : window(gl_window), raceNetRenderer(gl_window, logger){
LOG(INFO) << "Beginning GA evolution session. Population Size: " << populationSize << " nGenerations: "
<< nGenerations << " nTicks: " << nTicks << " Track: " << training_track->name << " (" << ToString(training_track->tag) << ")";
this->training_track = training_track;
this->training_car = training_car;
physicsEngine.registerTrack(this->training_track);
InitialiseAgents(populationSize);
std::vector<std::vector<int>> trainedAgentFitness = TrainAgents(nGenerations, nTicks);
LOG(INFO) << "Saving best agent network to " << BEST_NETWORK_PATH;
car_agents[trainedAgentFitness[0][0]]->carNet.net.saveNetworkParams(BEST_NETWORK_PATH.c_str());
LOG(INFO) << "Done";
}
void TrainingGround::Mutate(RaceNet &toMutate) {
for(uint8_t mut_Idx = 0; mut_Idx < 200; ++mut_Idx){
unsigned long layerToMutate = rand() % toMutate.net.W.size();
auto &m = toMutate.net.W[layerToMutate];
int h = m.getHeight();
int w = m.getWidth();
int xNeuronToMutate = rand() % h;
int yNeuronToMutate = rand() % w;
m.put(xNeuronToMutate, yNeuronToMutate, m.get(xNeuronToMutate, yNeuronToMutate) * Utils::RandomFloat(0.5, 1.5));
}
}
// Move this to agent class?
float TrainingGround::EvaluateFitness(shared_ptr<Car> car_agent) {
int closestBlockID = 0;
float lowestDistanceSqr = FLT_MAX;
// Get nearest track block to car
for (auto &track_block : training_track->track_blocks) {
float distanceSqr = glm::length2(glm::distance(car_agent->car_body_model.position, track_block.center));
if (distanceSqr < lowestDistanceSqr) {
closestBlockID = track_block.block_id;
lowestDistanceSqr = distanceSqr;
}
}
// Return a number corresponding to the distance driven
return (float) closestBlockID;
}
void TrainingGround::InitialiseAgents(uint16_t populationSize) {
// Create new cars from models loaded in training_car to avoid VIV extract again, each with new RaceNetworks
for (uint16_t pop_Idx = 0; pop_Idx < populationSize; ++pop_Idx) {
shared_ptr<Car> car_agent = std::make_shared<Car>(pop_Idx, this->training_car->all_models, NFS_3, "diab", RaceNet());
physicsEngine.registerVehicle(car_agent);
car_agent->resetCar(TrackUtils::pointToVec(this->training_track->track_blocks[0].center));
car_agents.emplace_back(car_agent);
}
LOG(INFO) << "Agents initialised";
}
std::vector<std::vector<int>> TrainingGround::TrainAgents(uint16_t nGenerations, uint32_t nTicks) {
std::vector<std::vector<int>> agentFitnesses;
// TODO: Remove this and
std::vector<int> dummyAgentData = {0,0};
agentFitnesses.emplace_back(dummyAgentData);
for (uint16_t gen_Idx = 0; gen_Idx < nGenerations; ++gen_Idx) {
LOG(INFO) << "Beginning Generation " << gen_Idx;
// Simulate the population
for (uint32_t tick_Idx = 0; tick_Idx < nTicks; ++tick_Idx) {
for (auto &car_agent : car_agents) {
//car_agent->applyAccelerationForce(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS, glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS);
//car_agent->applyBrakingForce(glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS);
//car_agent->applySteeringRight(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS);
//car_agent->applySteeringLeft(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS);
car_agent->simulate();
}
physicsEngine.stepSimulation(stepTime);
raceNetRenderer.Render(tick_Idx, car_agents, training_track);
if(glfwWindowShouldClose(window)) return agentFitnesses;
}
// Clear fitness data for next generation
agentFitnesses.clear();
// Evaluate the fitnesses and sort them
for (auto &car_agent : car_agents) {
LOG(INFO) << "Agent " << car_agent->populationID << " made it to trkblock " << EvaluateFitness(car_agent);
std::vector<int> agentData = {car_agent->populationID, (int) EvaluateFitness(car_agent)};
agentFitnesses.emplace_back(agentData);
}
std::sort(agentFitnesses.begin(), agentFitnesses.end(),
[](const std::vector<int> &a, const std::vector<int> &b) {
return a[1] > b[1];
});
LOG(DEBUG) << "Agent " << agentFitnesses[0][0] << " was fittest";
car_agents[agentFitnesses[0][0]]->carNet.net.saveNetworkParams("./assets/bestNetPreMut.net");
// Mutate the fittest network
Mutate(car_agents[agentFitnesses[0][0]]->carNet);
car_agents[agentFitnesses[0][0]]->carNet.net.saveNetworkParams("./assets/bestNetPostMut.net");
// Reset the cars for the next generation
for (auto &car_agent : car_agents) {
car_agent->resetCar(TrackUtils::pointToVec(this->training_track->track_blocks[0].center));
}
}
return agentFitnesses;
}
| 42.824 | 275 | 0.662806 | janisozaur |
44ed848890ba80e2eb50899e6f2fbeb961d78074 | 19,039 | cpp | C++ | framework/test/driver/ServiceFactoryTest.cpp | dingxiangfei2009/CppMicroServices | 5be6d095be8531992f794cdbf21a154695f0833c | [
"Apache-2.0"
] | 1 | 2021-06-10T00:04:32.000Z | 2021-06-10T00:04:32.000Z | framework/test/driver/ServiceFactoryTest.cpp | dingxiangfei2009/CppMicroServices | 5be6d095be8531992f794cdbf21a154695f0833c | [
"Apache-2.0"
] | null | null | null | framework/test/driver/ServiceFactoryTest.cpp | dingxiangfei2009/CppMicroServices | 5be6d095be8531992f794cdbf21a154695f0833c | [
"Apache-2.0"
] | null | null | null | /*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
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 "cppmicroservices/Bundle.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/Constants.h"
#include "cppmicroservices/Framework.h"
#include "cppmicroservices/FrameworkEvent.h"
#include "cppmicroservices/FrameworkFactory.h"
#include "cppmicroservices/GetBundleContext.h"
#include "cppmicroservices/LDAPProp.h"
#include "cppmicroservices/ListenerToken.h"
#include "cppmicroservices/ServiceObjects.h"
#include "cppmicroservices/detail/Threads.h"
#include "TestUtils.h"
#include "TestingConfig.h"
#include "TestingMacros.h"
#include <future>
#include <thread>
using namespace cppmicroservices;
namespace cppmicroservices {
struct TestBundleH
{
virtual ~TestBundleH() {}
};
struct TestBundleH2
{
virtual ~TestBundleH2() {}
};
}
void TestServiceFactoryBundleScope(BundleContext context)
{
// Install and start test bundle H, a service factory and test that the methods
// in that interface works.
auto bundle = testing::InstallLib(context, "TestBundleH");
US_TEST_CONDITION_REQUIRED(bundle, "Test for existing bundle TestBundleH")
auto bundleH = testing::GetBundle("TestBundleH", context);
US_TEST_CONDITION_REQUIRED(bundleH, "Test for existing bundle TestBundleH")
bundleH.Start();
std::vector<ServiceReferenceU> registeredRefs =
bundleH.GetRegisteredServices();
US_TEST_CONDITION_REQUIRED(
registeredRefs.size() == 7,
"Test that the # of registered services is seven.");
US_TEST_CONDITION(
registeredRefs[0].GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_BUNDLE,
"First service is bundle scope");
US_TEST_CONDITION(
registeredRefs[1].GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_BUNDLE,
"Second service is bundle scope");
US_TEST_CONDITION(
registeredRefs[2].GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_BUNDLE,
"Third service is bundle scope");
US_TEST_CONDITION(
registeredRefs[3].GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_BUNDLE,
"Fourth service is bundle scope");
US_TEST_CONDITION(
registeredRefs[4].GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_BUNDLE,
"Fifth service is bundle scope");
US_TEST_CONDITION(
registeredRefs[5].GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_BUNDLE,
"Sixth service is prototype scope");
US_TEST_CONDITION(
registeredRefs[6].GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_PROTOTYPE,
"Seventh service is prototype scope");
// Check that a service reference exists
const ServiceReferenceU sr1 =
context.GetServiceReference("cppmicroservices::TestBundleH");
US_TEST_CONDITION_REQUIRED(sr1, "A valid service reference was returned.");
US_TEST_CONDITION(sr1.GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_BUNDLE,
"service is bundle scope");
InterfaceMapConstPtr service = context.GetService(sr1);
US_TEST_CONDITION_REQUIRED(service && service->size() >= 1,
"Returned at least 1 service object");
InterfaceMap::const_iterator serviceIter =
service->find("cppmicroservices::TestBundleH");
US_TEST_CONDITION_REQUIRED(serviceIter != service->end(),
"Find a service object implementing the "
"'cppmicroservices::TestBundleH' interface");
US_TEST_CONDITION_REQUIRED(serviceIter->second != nullptr,
"The service object is valid (i.e. not nullptr)");
InterfaceMapConstPtr service2 = context.GetService(sr1);
US_TEST_CONDITION(*(service.get()) == *(service2.get()),
"Two service interface maps are equal");
std::vector<ServiceReferenceU> usedRefs =
context.GetBundle().GetServicesInUse();
US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "1 service in use");
US_TEST_CONDITION(usedRefs[0] == sr1, "service references are equal");
InterfaceMapConstPtr service3 = bundleH.GetBundleContext().GetService(sr1);
US_TEST_CONDITION(service.get() != service3.get(),
"Different service pointer");
// release any service objects before stopping the bundle
service.reset();
service2.reset();
service3.reset();
bundleH.Stop();
}
void TestServiceFactoryBundleScopeErrorConditions()
{
auto framework = FrameworkFactory().NewFramework();
framework.Start();
auto context = framework.GetBundleContext();
bool mainStarted = false;
// Start the embedded test driver bundle. It is needed by
// the recursive service factory tests.
for (auto b : context.GetBundles()) {
if (b.GetSymbolicName() == "main") {
b.Start();
mainStarted = true;
break;
}
}
US_TEST_CONDITION_REQUIRED(mainStarted, "Start main bundle")
auto bundle = testing::InstallLib(context, "TestBundleH");
US_TEST_CONDITION_REQUIRED(bundle, "Test for existing bundle TestBundleH")
auto bundleH = testing::GetBundle("TestBundleH", context);
US_TEST_CONDITION_REQUIRED(bundleH, "Test for existing bundle TestBundleH")
bundleH.Start();
struct
: detail::MultiThreaded<>
, std::vector<FrameworkEvent>
{
} fwEvents;
auto eventCountListener = [&fwEvents](const FrameworkEvent& event) {
fwEvents.Lock(), fwEvents.push_back(event);
};
auto listenerToken =
bundleH.GetBundleContext().AddFrameworkListener(eventCountListener);
// Test that a service factory which returns a nullptr returns an invalid (nullptr) shared_ptr
std::string returnsNullPtrFilter(LDAPProp("returns_nullptr") == true);
auto serviceRefs(context.GetServiceReferences("cppmicroservices::TestBundleH",
returnsNullPtrFilter));
US_TEST_CONDITION_REQUIRED(serviceRefs.size() == 1,
"Number of service references returned is 1.");
US_TEST_CONDITION_REQUIRED(
"1" ==
serviceRefs[0].GetProperty(std::string("returns_nullptr")).ToString(),
"Test that 'returns_nullptr' service property is 'true'");
US_TEST_CONDITION_REQUIRED(
nullptr == context.GetService(serviceRefs[0]),
"Test that the service object returned is a nullptr");
US_TEST_CONDITION_REQUIRED(1 == fwEvents.size(),
"Test that one FrameworkEvent was sent");
bundleH.GetBundleContext().RemoveListener(std::move(listenerToken));
fwEvents.clear();
listenerToken =
bundleH.GetBundleContext().AddFrameworkListener(eventCountListener);
// Test getting a service object using an interface which isn't implemented by the service factory
std::string returnsWrongInterfaceFilter(LDAPProp("returns_wrong_interface") ==
true);
auto svcNoInterfaceRefs(context.GetServiceReferences(
"cppmicroservices::TestBundleH", returnsWrongInterfaceFilter));
US_TEST_CONDITION_REQUIRED(svcNoInterfaceRefs.size() == 1,
"Number of service references returned is 1.");
US_TEST_CONDITION_REQUIRED(
"1" == svcNoInterfaceRefs[0]
.GetProperty(std::string("returns_wrong_interface"))
.ToString(),
"Test that 'returns_wrong_interface' service property is 'true'");
US_TEST_CONDITION_REQUIRED(
nullptr == context.GetService(svcNoInterfaceRefs[0]),
"Test that the service object returned is a nullptr");
US_TEST_CONDITION_REQUIRED(1 == fwEvents.size(),
"Test that one FrameworkEvent was sent");
bundleH.GetBundleContext().RemoveListener(std::move(listenerToken));
fwEvents.clear();
listenerToken =
bundleH.GetBundleContext().AddFrameworkListener(eventCountListener);
// Test getting a service object from a service factory which throws an exception
std::string getServiceThrowsFilter(LDAPProp("getservice_exception") == true);
auto svcGetServiceThrowsRefs(context.GetServiceReferences(
"cppmicroservices::TestBundleH", getServiceThrowsFilter));
US_TEST_CONDITION_REQUIRED(svcGetServiceThrowsRefs.size() == 1,
"Number of service references returned is 1.");
US_TEST_CONDITION_REQUIRED(
"1" == svcGetServiceThrowsRefs[0]
.GetProperty(std::string("getservice_exception"))
.ToString(),
"Test that 'getservice_exception' service property is 'true'");
US_TEST_CONDITION_REQUIRED(
nullptr == context.GetService(svcGetServiceThrowsRefs[0]),
"Test that the service object returned is a nullptr");
US_TEST_CONDITION_REQUIRED(1 == fwEvents.size(),
"Test that one FrameworkEvent was sent");
bundleH.GetBundleContext().RemoveListener(std::move(listenerToken));
fwEvents.clear();
listenerToken =
bundleH.GetBundleContext().AddFrameworkListener(eventCountListener);
std::string unGetServiceThrowsFilter(LDAPProp("ungetservice_exception") ==
true);
auto svcUngetServiceThrowsRefs(context.GetServiceReferences(
"cppmicroservices::TestBundleH", unGetServiceThrowsFilter));
US_TEST_CONDITION_REQUIRED(svcUngetServiceThrowsRefs.size() == 1,
"Number of service references returned is 1.");
US_TEST_CONDITION_REQUIRED(
"1" == svcUngetServiceThrowsRefs[0]
.GetProperty(std::string("ungetservice_exception"))
.ToString(),
"Test that 'ungetservice_exception' service property is 'true'");
{
auto sfUngetServiceThrowSvc =
context.GetService(svcUngetServiceThrowsRefs[0]);
} // When sfUngetServiceThrowSvc goes out of scope, ServiceFactory::UngetService should be called
US_TEST_CONDITION_REQUIRED(1 == fwEvents.size(),
"Test that one FrameworkEvent was sent");
fwEvents.clear();
std::string recursiveGetServiceFilter(LDAPProp("getservice_recursion") ==
true);
auto svcRecursiveGetServiceRefs(context.GetServiceReferences(
"cppmicroservices::TestBundleH", recursiveGetServiceFilter));
US_TEST_CONDITION_REQUIRED(svcRecursiveGetServiceRefs.size() == 1,
"Number of service references returned is 1.");
US_TEST_CONDITION_REQUIRED(
"1" == svcRecursiveGetServiceRefs[0]
.GetProperty(std::string("getservice_recursion"))
.ToString(),
"Test that 'getservice_recursion' service property is 'true'");
#if !defined(US_ENABLE_THREADING_SUPPORT) || defined(US_HAVE_THREAD_LOCAL)
US_TEST_CONDITION_REQUIRED(
nullptr == context.GetService(svcRecursiveGetServiceRefs[0]),
"Test that the service object returned is a nullptr");
US_TEST_CONDITION_REQUIRED(2 == fwEvents.size(),
"Test that one FrameworkEvent was sent");
US_TEST_CONDITION_REQUIRED(fwEvents[0].GetType() ==
FrameworkEvent::FRAMEWORK_ERROR,
"Test for correct framwork event type");
US_TEST_CONDITION_REQUIRED(fwEvents[0].GetBundle() == context.GetBundle(),
"Test for correct framwork event bundle");
US_TEST_NO_EXCEPTION_REQUIRED(
try {
std::rethrow_exception(fwEvents[0].GetThrowable());
US_TEST_FAILED_MSG(<< "Exception not thrown");
} catch (const ServiceException& exc) {
US_TEST_CONDITION_REQUIRED(
exc.GetType() == ServiceException::FACTORY_RECURSION,
"Test for correct service exception type (recursion)");
});
#endif
#ifdef US_ENABLE_THREADING_SUPPORT
# ifdef US_HAVE_THREAD_LOCAL
{
std::vector<std::future<void>> futures;
for (std::size_t i = 0; i < 10; ++i) {
futures.push_back(std::async(std::launch::async, [&] {
for (std::size_t j = 0; j < 100; ++j) {
// Get and automatically unget the service
auto svc = context.GetService(svcRecursiveGetServiceRefs[0]);
}
}));
}
for (auto& fut : futures) {
fut.wait();
}
}
# endif
#else
{
// Get and automatically unget the service
auto svc = context.GetService(svcRecursiveGetServiceRefs[0]);
}
#endif
// Test recursive service factory GetService calls, but with different
// calling bundles. This should work.
fwEvents.clear();
US_TEST_CONDITION_REQUIRED(
nullptr != GetBundleContext().GetService(svcRecursiveGetServiceRefs[0]),
"Test that the service object returned is not a nullptr");
US_TEST_CONDITION_REQUIRED(fwEvents.empty(),
"Test that no FrameworkEvent was sent");
framework.Stop();
framework.WaitForStop(std::chrono::milliseconds::zero());
}
void TestServiceFactoryPrototypeScope(BundleContext context)
{
// Install and start test bundle H, a service factory and test that the methods
// in that interface works.
auto bundle = testing::InstallLib(context, "TestBundleH");
US_TEST_CONDITION_REQUIRED(bundle, "Test for existing bundle TestBundleH")
auto bundleH = testing::GetBundle("TestBundleH", context);
US_TEST_CONDITION_REQUIRED(bundleH, "Test for existing bundle TestBundleH")
bundleH.Start();
// Check that a service reference exist
const ServiceReference<TestBundleH2> sr1 =
context.GetServiceReference<TestBundleH2>();
US_TEST_CONDITION_REQUIRED(sr1, "Service shall be present.")
US_TEST_CONDITION(sr1.GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_PROTOTYPE,
"service scope")
ServiceObjects<TestBundleH2> svcObjects = context.GetServiceObjects(sr1);
auto prototypeServiceH2 = svcObjects.GetService();
const ServiceReferenceU sr1void =
context.GetServiceReference(us_service_interface_iid<TestBundleH2>());
ServiceObjects<void> svcObjectsVoid = context.GetServiceObjects(sr1void);
InterfaceMapConstPtr prototypeServiceH2Void = svcObjectsVoid.GetService();
US_TEST_CONDITION_REQUIRED(
prototypeServiceH2Void->find(us_service_interface_iid<TestBundleH2>()) !=
prototypeServiceH2Void->end(),
"ServiceObjects<void>::GetService()")
#ifdef US_BUILD_SHARED_LIBS
// There should be only one service in use
US_TEST_CONDITION_REQUIRED(context.GetBundle().GetServicesInUse().size() == 1,
"services in use")
#endif
auto bundleScopeService = context.GetService(sr1);
US_TEST_CONDITION_REQUIRED(bundleScopeService &&
bundleScopeService != prototypeServiceH2,
"GetService()")
US_TEST_CONDITION_REQUIRED(
prototypeServiceH2 !=
prototypeServiceH2Void->find(us_service_interface_iid<TestBundleH2>())
->second,
"GetService()")
auto bundleScopeService2 = context.GetService(sr1);
US_TEST_CONDITION(bundleScopeService == bundleScopeService2,
"Same service pointer")
#ifdef US_BUILD_SHARED_LIBS
std::vector<ServiceReferenceU> usedRefs =
context.GetBundle().GetServicesInUse();
US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use")
US_TEST_CONDITION(usedRefs[0] == sr1, "service ref in use")
#endif
std::string filter = "(" + Constants::SERVICE_ID + "=" +
sr1.GetProperty(Constants::SERVICE_ID).ToString() + ")";
const ServiceReference<TestBundleH> sr2 =
context.GetServiceReferences<TestBundleH>(filter).front();
US_TEST_CONDITION_REQUIRED(sr2, "Service shall be present.")
US_TEST_CONDITION(sr2.GetProperty(Constants::SERVICE_SCOPE).ToString() ==
Constants::SCOPE_PROTOTYPE,
"service scope")
US_TEST_CONDITION(any_cast<long>(sr2.GetProperty(Constants::SERVICE_ID)) ==
any_cast<long>(sr1.GetProperty(Constants::SERVICE_ID)),
"same service id")
#ifdef US_BUILD_SHARED_LIBS
// There should still be only one service in use
usedRefs = context.GetBundle().GetServicesInUse();
US_TEST_CONDITION_REQUIRED(usedRefs.size() == 1, "services in use")
#endif
ServiceObjects<TestBundleH2> svcObjects2 = std::move(svcObjects);
ServiceObjects<TestBundleH2> svcObjects3 = context.GetServiceObjects(sr1);
prototypeServiceH2 = svcObjects2.GetService();
auto prototypeServiceH2_2 = svcObjects3.GetService();
US_TEST_CONDITION_REQUIRED(prototypeServiceH2_2 &&
prototypeServiceH2_2 != prototypeServiceH2,
"prototype service")
bundleH.Stop();
}
#ifdef US_ENABLE_THREADING_SUPPORT
// test that concurrent calls to ServiceFactory::GetService and ServiceFactory::UngetService
// don't cause race conditions.
void TestConcurrentServiceFactory()
{
auto framework = FrameworkFactory().NewFramework();
framework.Start();
auto bundle =
testing::InstallLib(framework.GetBundleContext(), "TestBundleH");
bundle.Start();
std::vector<std::thread> worker_threads;
for (size_t i = 0; i < 100; ++i) {
worker_threads.push_back(std::thread([framework]() {
auto frameworkCtx = framework.GetBundleContext();
if (!frameworkCtx) {
US_TEST_FAILED_MSG(<< "Failed to get Framework's bundle context. "
"Terminating the thread...");
return;
}
for (int i = 0; i < 100; ++i) {
auto ref =
frameworkCtx.GetServiceReference<cppmicroservices::TestBundleH2>();
if (ref) {
std::shared_ptr<cppmicroservices::TestBundleH2> svc =
frameworkCtx.GetService(ref);
if (!svc) {
US_TEST_FAILED_MSG(<< "Failed to retrieve a valid service object");
}
}
}
}));
}
for (auto& t : worker_threads)
t.join();
}
#endif
int ServiceFactoryTest(int /*argc*/, char* /*argv*/[])
{
US_TEST_BEGIN("ServiceFactoryTest");
FrameworkFactory factory;
auto framework = factory.NewFramework();
framework.Start();
TestServiceFactoryPrototypeScope(framework.GetBundleContext());
TestServiceFactoryBundleScope(framework.GetBundleContext());
TestServiceFactoryBundleScopeErrorConditions();
#ifdef US_ENABLE_THREADING_SUPPORT
TestConcurrentServiceFactory();
#endif
US_TEST_END()
}
| 38.307847 | 100 | 0.694942 | dingxiangfei2009 |
44ed95113a2a2fe4ef44ed6f80bd2af5579853ea | 18,519 | cc | C++ | dcmdata/libsrc/dchashdi.cc | chrisvana/dcmtk_copy | f929ab8590aca5b7a319c95af4fe2ee31be52f46 | [
"Apache-2.0"
] | 24 | 2015-07-22T05:07:51.000Z | 2019-02-28T04:52:33.000Z | dcmdata/libsrc/dchashdi.cc | chrisvana/dcmtk_copy | f929ab8590aca5b7a319c95af4fe2ee31be52f46 | [
"Apache-2.0"
] | 13 | 2015-07-23T05:43:02.000Z | 2021-07-17T17:14:45.000Z | dcmdata/libsrc/dchashdi.cc | chrisvana/dcmtk_copy | f929ab8590aca5b7a319c95af4fe2ee31be52f46 | [
"Apache-2.0"
] | 13 | 2015-07-23T01:07:30.000Z | 2021-01-05T09:49:30.000Z | /*
*
* Copyright (C) 1997-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Andrew Hewett
*
* Purpose: Hash table interface for DICOM data dictionary
*
* Last Update: $Author: uli $
* Update Date: $Date: 2010-11-10 12:02:01 $
* CVS/RCS Revision: $Revision: 1.26 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dchashdi.h"
#include "dcmtk/dcmdata/dcdicent.h"
#define INCLUDE_CSTDIO
#define INCLUDE_CASSERT
#include "dcmtk/ofstd/ofstdinc.h"
/*
** DcmDictEntryList
*/
DcmDictEntryList::~DcmDictEntryList()
{
clear();
}
void
DcmDictEntryList::clear()
{
while (!empty()) {
delete front();
pop_front();
}
}
DcmDictEntry*
DcmDictEntryList::insertAndReplace(DcmDictEntry* e)
{
if (empty()) {
push_front(e);
} else {
DcmDictEntryListIterator iter(begin());
DcmDictEntryListIterator last(end());
Uint32 eHash = e->hash();
Uint32 iterHash = 0;
// insert smallest first
for (iter = begin(); iter != last; ++iter) {
iterHash = (*iter)->hash();
if (eHash == iterHash)
{
if (e->privateCreatorMatch(**iter))
{
// entry is already there so replace it
DcmDictEntry* oldEntry = *iter;
*iter = e;
return oldEntry;
}
else
{
// insert before listEntry
insert(iter, e);
return NULL;
}
}
else if (eHash < iterHash)
{
// insert before listEntry
insert(iter, e);
return NULL;
}
}
// add to end
push_back(e);
}
return NULL;
}
DcmDictEntry *DcmDictEntryList::find(const DcmTagKey& k, const char *privCreator)
{
if (!empty()) {
DcmDictEntryListIterator iter;
DcmDictEntryListIterator last = end();
Uint32 kHash = k.hash();
Uint32 iterHash = 0;
for (iter = begin(); iter != last; ++iter) {
iterHash = (*iter)->hash();
if ((iterHash == kHash) && (*iter)->privateCreatorMatch(privCreator))
{
return *iter;
} else if (iterHash > kHash) {
return NULL; // not there
}
}
}
return NULL;
}
/*
** DcmHashDictIterator
*/
void
DcmHashDictIterator::init(const DcmHashDict* d, OFBool atEnd)
{
dict = d;
hindex = 0;
iterating = OFFalse;
if (dict != NULL) {
if (atEnd) {
hindex = dict->highestBucket;
if (dict->size() > 0) {
iter = dict->hashTab[hindex]->end();
iterating = OFTrue;
}
} else {
hindex = dict->lowestBucket;
if (dict->size() > 0) {
iter = dict->hashTab[hindex]->begin();
iterating = OFTrue;
}
}
}
}
void
DcmHashDictIterator::stepUp()
{
assert(dict != NULL);
while (hindex <= dict->highestBucket) {
DcmDictEntryList* bucket = dict->hashTab[hindex];
if (bucket == NULL) {
if (hindex == dict->highestBucket)
return; /* We reached the end of the dictionary */
hindex++; // move on to next bucket
iterating = OFFalse;
} else {
if (!iterating) {
iter = bucket->begin();
iterating = OFTrue;
if (iter != bucket->end()) {
return; /* we have found the next one */
}
}
if (iter == bucket->end()) {
if (hindex == dict->highestBucket)
return; /* We reached the end of the dictionary */
iterating = OFFalse;
hindex++;
} else {
++iter;
if (iter != bucket->end()) {
return; /* we have found the next one */
}
}
}
}
}
/*
** DcmHashDict
*/
void
DcmHashDict::_init(int hashTabLen)
{
hashTab = new DcmDictEntryList*[hashTabLen];
assert(hashTab != NULL);
hashTabLength = hashTabLen;
for (int i=0; i<hashTabLength; i++) {
hashTab[i] = NULL;
}
lowestBucket = hashTabLength-1;
highestBucket = 0;
entryCount = 0;
}
DcmHashDict::~DcmHashDict()
{
clear();
delete[] hashTab;
}
void
DcmHashDict::clear()
{
for (int i=0; i<hashTabLength; i++) {
delete hashTab[i];
hashTab[i] = NULL;
}
lowestBucket = hashTabLength-1;
highestBucket = 0;
entryCount = 0;
}
int
DcmHashDict::hash(const DcmTagKey* k) const
{
/*
** Use a hash function based upon the relative number of
** data dictionary entries in each group by splitting
** the hash table into proportional sections .
*/
int h = 0;
int lower = 0; /* default */
int upper = hashTabLength-1; /* default */
switch (k->getGroup()) {
/* the code in this switch statement was generated automatically */
case 0x0: /* %usage: 3.47 */
lower = int(0 * hashTabLength);
upper = int(0.0346608 * hashTabLength);
break;
case 0x2: /* %usage: 0.74 */
lower = int(0.0346608 * hashTabLength);
upper = int(0.0420354 * hashTabLength);
break;
case 0x4: /* %usage: 1.40 */
lower = int(0.0420354 * hashTabLength);
upper = int(0.0560472 * hashTabLength);
break;
case 0x8: /* %usage: 7.30 */
lower = int(0.0560472 * hashTabLength);
upper = int(0.129056 * hashTabLength);
break;
case 0x10: /* %usage: 2.43 */
lower = int(0.129056 * hashTabLength);
upper = int(0.153392 * hashTabLength);
break;
case 0x18: /* %usage: 18.36 */
lower = int(0.153392 * hashTabLength);
upper = int(0.337021 * hashTabLength);
break;
case 0x20: /* %usage: 3.98 */
lower = int(0.337021 * hashTabLength);
upper = int(0.376844 * hashTabLength);
break;
case 0x28: /* %usage: 8.63 */
lower = int(0.376844 * hashTabLength);
upper = int(0.463127 * hashTabLength);
break;
case 0x32: /* %usage: 1.92 */
lower = int(0.463127 * hashTabLength);
upper = int(0.482301 * hashTabLength);
break;
case 0x38: /* %usage: 1.62 */
lower = int(0.482301 * hashTabLength);
upper = int(0.498525 * hashTabLength);
break;
case 0x40: /* %usage: 6.93 */
lower = int(0.498525 * hashTabLength);
upper = int(0.567847 * hashTabLength);
break;
case 0x41: /* %usage: 2.29 */
lower = int(0.567847 * hashTabLength);
upper = int(0.590708 * hashTabLength);
break;
case 0x50: /* %usage: 0.59 */
lower = int(0.590708 * hashTabLength);
upper = int(0.596608 * hashTabLength);
break;
case 0x54: /* %usage: 5.75 */
lower = int(0.596608 * hashTabLength);
upper = int(0.65413 * hashTabLength);
break;
case 0x88: /* %usage: 0.59 */
lower = int(0.65413 * hashTabLength);
upper = int(0.660029 * hashTabLength);
break;
case 0x1000: /* %usage: 0.52 */
lower = int(0.660029 * hashTabLength);
upper = int(0.665192 * hashTabLength);
break;
case 0x1010: /* %usage: 0.15 */
lower = int(0.665192 * hashTabLength);
upper = int(0.666667 * hashTabLength);
break;
case 0x2000: /* %usage: 0.59 */
lower = int(0.666667 * hashTabLength);
upper = int(0.672566 * hashTabLength);
break;
case 0x2010: /* %usage: 1.18 */
lower = int(0.672566 * hashTabLength);
upper = int(0.684366 * hashTabLength);
break;
case 0x2020: /* %usage: 0.59 */
lower = int(0.684366 * hashTabLength);
upper = int(0.690265 * hashTabLength);
break;
case 0x2030: /* %usage: 0.22 */
lower = int(0.690265 * hashTabLength);
upper = int(0.692478 * hashTabLength);
break;
case 0x2040: /* %usage: 0.66 */
lower = int(0.692478 * hashTabLength);
upper = int(0.699115 * hashTabLength);
break;
case 0x2050: /* %usage: 0.22 */
lower = int(0.699115 * hashTabLength);
upper = int(0.701327 * hashTabLength);
break;
case 0x2100: /* %usage: 0.81 */
lower = int(0.701327 * hashTabLength);
upper = int(0.70944 * hashTabLength);
break;
case 0x2110: /* %usage: 0.37 */
lower = int(0.70944 * hashTabLength);
upper = int(0.713127 * hashTabLength);
break;
case 0x2120: /* %usage: 0.29 */
lower = int(0.713127 * hashTabLength);
upper = int(0.716077 * hashTabLength);
break;
case 0x2130: /* %usage: 0.66 */
lower = int(0.716077 * hashTabLength);
upper = int(0.722714 * hashTabLength);
break;
case 0x3002: /* %usage: 1.25 */
lower = int(0.722714 * hashTabLength);
upper = int(0.735251 * hashTabLength);
break;
case 0x3004: /* %usage: 1.62 */
lower = int(0.735251 * hashTabLength);
upper = int(0.751475 * hashTabLength);
break;
case 0x3006: /* %usage: 3.24 */
lower = int(0.751475 * hashTabLength);
upper = int(0.783923 * hashTabLength);
break;
case 0x300a: /* %usage: 16.52 */
lower = int(0.783923 * hashTabLength);
upper = int(0.949115 * hashTabLength);
break;
case 0x300c: /* %usage: 1.84 */
lower = int(0.949115 * hashTabLength);
upper = int(0.967552 * hashTabLength);
break;
case 0x300e: /* %usage: 0.29 */
lower = int(0.967552 * hashTabLength);
upper = int(0.970501 * hashTabLength);
break;
case 0x4000: /* %usage: 0.22 */
lower = int(0.970501 * hashTabLength);
upper = int(0.972714 * hashTabLength);
break;
case 0x4008: /* %usage: 2.06 */
lower = int(0.972714 * hashTabLength);
upper = int(0.993363 * hashTabLength);
break;
case 0x7fe0: /* %usage: 0.37 */
lower = int(0.993363 * hashTabLength);
upper = int(0.99705 * hashTabLength);
break;
case 0xfffc: /* %usage: 0.07 */
lower = int(0.99705 * hashTabLength);
upper = int(0.997788 * hashTabLength);
break;
case 0xfffe: /* %usage: 0.22 */
lower = int(0.997788 * hashTabLength);
upper = int(1 * hashTabLength);
break;
default:
lower = 0; /* default */
upper = hashTabLength-1; /* default */
break;
}
int span = upper - lower;
int offset = 0;
if (span > 0) {
offset = OFstatic_cast(int, (k->hash() & 0x7FFFFFFF) % span);
}
h = lower + offset;
assert((h >= 0) && (h < hashTabLength));
return h;
}
DcmDictEntry*
DcmHashDict::insertInList(DcmDictEntryList& l, DcmDictEntry* e)
{
return l.insertAndReplace(e);
}
void
DcmHashDict::put(DcmDictEntry* e)
{
int idx = hash(e);
DcmDictEntryList* bucket = hashTab[idx];
// if there is no bucket then create one
if (bucket == NULL) {
bucket = new DcmDictEntryList;
assert(bucket != NULL);
hashTab[idx] = bucket;
}
DcmDictEntry* old = insertInList(*bucket, e);
if (old != NULL) {
/* an old entry has been replaced */
#ifdef PRINT_REPLACED_DICTIONARY_ENTRIES
DCMDATA_WARN("replacing " << *old);
#endif
delete old;
} else {
entryCount++;
}
lowestBucket = (lowestBucket<idx)?(lowestBucket):(idx);
highestBucket = (highestBucket>idx)?(highestBucket):(idx);
}
DcmDictEntry *DcmHashDict::findInList(DcmDictEntryList& l, const DcmTagKey& k, const char *privCreator) const
{
return l.find(k, privCreator);
}
const DcmDictEntry*
DcmHashDict::get(const DcmTagKey& k, const char *privCreator) const
{
const DcmDictEntry* entry = NULL;
// first we look for an entry that exactly matches the given tag key
Uint32 idx = hash(&k);
DcmDictEntryList* bucket = hashTab[idx];
if (bucket) entry = findInList(*bucket, k, privCreator);
if ((entry == NULL) && privCreator)
{
// As a second guess, we look for a private tag with flexible element number.
DcmTagKey tk(k.getGroup(), OFstatic_cast(unsigned short, k.getElement() & 0xff));
idx = hash(&tk);
bucket = hashTab[idx];
if (bucket) entry = findInList(*bucket, tk, privCreator);
}
return entry;
}
DcmDictEntry*
DcmHashDict::removeInList(DcmDictEntryList& l, const DcmTagKey& k, const char *privCreator)
{
DcmDictEntry* entry = findInList(l, k, privCreator);
l.remove(entry); // does not delete entry
return entry;
}
void
DcmHashDict::del(const DcmTagKey& k, const char *privCreator)
{
Uint32 idx = hash(&k);
DcmDictEntryList* bucket = hashTab[idx];
if (bucket != NULL) {
DcmDictEntry* entry = removeInList(*bucket, k, privCreator);
delete entry;
}
}
STD_NAMESPACE ostream&
DcmHashDict::loadSummary(STD_NAMESPACE ostream& out)
{
out << "DcmHashDict: size=" << hashTabLength <<
", total entries=" << size() << OFendl;
DcmDictEntryList* bucket = NULL;
int largestBucket = 0;
for (int i=0; i<hashTabLength; i++) {
bucket = hashTab[i];
if (bucket != NULL) {
if (int(bucket->size()) > largestBucket) {
largestBucket = bucket->size();
}
}
}
for (int j=0; j<hashTabLength; j++) {
out << " hashTab[" << j << "]: ";
bucket = hashTab[j];
if (bucket == NULL) {
out << "0 entries" << OFendl;
} else {
out << bucket->size() << " entries" << OFendl;
}
}
out << "Bucket Sizes" << OFendl;
int n, x, k, l_size;
for (x=0; x<=largestBucket; x++) {
n = 0;
for (k=0; k<hashTabLength; k++) {
bucket = hashTab[k];
l_size = 0;
if (bucket != NULL) {
l_size = bucket->size();
}
if (l_size == x) {
n++;
}
}
out << " entries{" << x << "}: " << n << " buckets" << OFendl;
}
return out;
}
/*
** CVS/RCS Log:
** $Log: dchashdi.cc,v $
** Revision 1.26 2010-11-10 12:02:01 uli
** Made DcmHashDictIterator::stepUp correctly stop at the end of the dict.
**
** Revision 1.25 2010-10-14 13:14:08 joergr
** Updated copyright header. Added reference to COPYRIGHT file.
**
** Revision 1.24 2010-02-22 11:39:54 uli
** Remove some unneeded includes.
**
** Revision 1.23 2009-11-10 12:38:29 uli
** Fix compilation on windows.
**
** Revision 1.22 2009-11-04 09:58:09 uli
** Switched to logging mechanism provided by the "new" oflog module
**
** Revision 1.21 2006-08-15 15:49:54 meichel
** Updated all code in module dcmdata to correctly compile when
** all standard C++ classes remain in namespace std.
**
** Revision 1.20 2005/12/08 15:41:11 meichel
** Changed include path schema for all DCMTK header files
**
** Revision 1.19 2004/02/04 16:33:02 joergr
** Adapted type casts to new-style typecast operators defined in ofcast.h.
**
** Revision 1.18 2003/06/02 16:58:01 meichel
** Renamed local variables to avoid name clashes with STL
**
** Revision 1.17 2003/03/21 13:08:04 meichel
** Minor code purifications for warnings reported by MSVC in Level 4
**
** Revision 1.16 2002/11/27 12:06:47 meichel
** Adapted module dcmdata to use of new header file ofstdinc.h
**
** Revision 1.15 2002/07/23 14:21:33 meichel
** Added support for private tag data dictionaries to dcmdata
**
** Revision 1.14 2001/06/01 15:49:04 meichel
** Updated copyright header
**
** Revision 1.13 2000/10/12 10:26:52 meichel
** Updated data dictionary for 2000 edition of the DICOM standard
**
** Revision 1.12 2000/05/03 14:19:09 meichel
** Added new class GlobalDcmDataDictionary which implements read/write lock
** semantics for safe access to the DICOM dictionary from multiple threads
** in parallel. The global dcmDataDict now uses this class.
**
** Revision 1.11 2000/04/14 16:16:22 meichel
** Dcmdata library code now consistently uses ofConsole for error output.
**
** Revision 1.10 2000/03/08 16:26:36 meichel
** Updated copyright header.
**
** Revision 1.9 2000/03/03 14:05:33 meichel
** Implemented library support for redirecting error messages into memory
** instead of printing them to stdout/stderr for GUI applications.
**
** Revision 1.8 2000/02/02 14:32:51 joergr
** Replaced 'delete' statements by 'delete[]' for objects created with 'new[]'.
**
** Revision 1.7 1999/03/31 09:25:29 meichel
** Updated copyright header in module dcmdata
**
** Revision 1.6 1999/03/22 09:58:32 meichel
** Fixed bug in data dictionary causing a segmentation fault
** if dictionary was cleared and a smaller version reloaded.
**
** Revision 1.5 1998/07/28 15:52:37 meichel
** Introduced new compilation flag PRINT_REPLACED_DICTIONARY_ENTRIES
** which causes the dictionary to display all duplicate entries.
**
** Revision 1.4 1998/07/15 15:51:57 joergr
** Removed several compiler warnings reported by gcc 2.8.1 with
** additional options, e.g. missing copy constructors and assignment
** operators, initialization of member variables in the body of a
** constructor instead of the member initialization list, hiding of
** methods by use of identical names, uninitialized member variables,
** missing const declaration of char pointers. Replaced tabs by spaces.
**
** Revision 1.3 1998/06/29 12:17:57 meichel
** Removed some name clashes (e.g. local variable with same
** name as class member) to improve maintainability.
** Applied some code purifications proposed by the gcc 2.8.1 -Weffc++ option.
**
** Revision 1.2 1997/09/18 08:10:54 meichel
** Many minor type conflicts (e.g. long passed as int) solved.
**
** Revision 1.1 1997/08/26 13:35:02 hewett
** Initial Version - Implementation of hash table for data dictionary.
**
*/
| 29.583067 | 109 | 0.575139 | chrisvana |
6022b97744f74a453993094ed6f83d4cfbd5e583 | 776 | hpp | C++ | core/api/service/state/state_jrpc_processor.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | 110 | 2019-04-03T13:39:39.000Z | 2022-03-09T11:54:42.000Z | core/api/service/state/state_jrpc_processor.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | 890 | 2019-03-22T21:33:30.000Z | 2022-03-31T14:31:22.000Z | core/api/service/state/state_jrpc_processor.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | 27 | 2019-06-25T06:21:47.000Z | 2021-11-01T14:12:10.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_STATE_JRPC_PROCESSOR_HPP
#define KAGOME_STATE_JRPC_PROCESSOR_HPP
#include "api/jrpc/jrpc_processor.hpp"
#include "api/jrpc/jrpc_server_impl.hpp"
#include "api/service/state/state_api.hpp"
namespace kagome::api::state {
class StateJrpcProcessor : public JRpcProcessor {
public:
StateJrpcProcessor(std::shared_ptr<JRpcServer> server,
std::shared_ptr<StateApi> api);
~StateJrpcProcessor() override = default;
void registerHandlers() override;
private:
std::shared_ptr<StateApi> api_;
std::shared_ptr<JRpcServer> server_;
};
} // namespace kagome::api::state
#endif // KAGOME_STATE_JRPC_PROCESSOR_HPP
| 25.032258 | 58 | 0.728093 | FlorianFranzen |
60236342244b4f08dd3343abd7b34bae22b312d1 | 10,314 | hpp | C++ | src/layer.hpp | ktts16/mini-caffe | 58a5007d7921c69c9c3105b20b92b2136af26a4e | [
"BSD-3-Clause"
] | 413 | 2015-07-09T09:33:07.000Z | 2022-03-10T02:26:27.000Z | src/layer.hpp | ktts16/mini-caffe | 58a5007d7921c69c9c3105b20b92b2136af26a4e | [
"BSD-3-Clause"
] | 65 | 2015-07-10T01:38:10.000Z | 2020-08-06T07:27:42.000Z | src/layer.hpp | ktts16/mini-caffe | 58a5007d7921c69c9c3105b20b92b2136af26a4e | [
"BSD-3-Clause"
] | 196 | 2015-08-18T07:59:33.000Z | 2021-07-27T02:44:21.000Z | #ifndef CAFFE_LAYER_H_
#define CAFFE_LAYER_H_
#include <algorithm>
#include <string>
#include <vector>
#include "caffe/blob.hpp"
#include "./common.hpp"
#include "./layer_factory.hpp"
#include "./proto/caffe.pb.h"
namespace caffe {
/**
* @brief An interface for the units of computation which can be composed into a
* Net.
*
* Layer%s must implement a Forward function, in which they take their input
* (bottom) Blob%s (if any) and compute their output Blob%s (if any).
* They may also implement a Backward function, in which they compute the error
* gradients with respect to their input Blob%s, given the error gradients with
* their output Blob%s.
*/
class Layer {
public:
/**
* You should not implement your own constructor. Any set up code should go
* to SetUp(), where the dimensions of the bottom blobs are provided to the
* layer.
*/
explicit Layer(const LayerParameter& param)
: layer_param_(param) {
// Set phase and copy blobs (if there are any).
if (layer_param_.blobs_size() > 0) {
blobs_.resize(layer_param_.blobs_size());
for (int i = 0; i < layer_param_.blobs_size(); ++i) {
blobs_[i].reset(new Blob);
blobs_[i]->FromProto(layer_param_.blobs(i));
}
}
}
virtual ~Layer() {}
/**
* @brief Implements common layer setup functionality.
*
* @param bottom the preshaped input blobs
* @param top
* the allocated but unshaped output blobs, to be shaped by Reshape
*
* Checks that the number of bottom and top blobs is correct.
* Calls LayerSetUp to do special layer setup for individual layer types,
* followed by Reshape to set up sizes of top blobs and internal buffers.
* Sets up the loss weight multiplier blobs for any non-zero loss weights.
* This method may not be overridden.
*/
void SetUp(const vector<Blob*>& bottom, const vector<Blob*>& top) {
CheckBlobCounts(bottom, top);
LayerSetUp(bottom, top);
Reshape(bottom, top);
}
/**
* @brief Does layer-specific setup: your layer should implement this function
* as well as Reshape.
*
* @param bottom
* the preshaped input blobs, whose data fields store the input data for
* this layer
* @param top
* the allocated but unshaped output blobs
*
* This method should do one-time layer specific setup. This includes reading
* and processing relevent parameters from the <code>layer_param_</code>.
* Setting up the shapes of top blobs and internal buffers should be done in
* <code>Reshape</code>, which will be called before the forward pass to
* adjust the top blob sizes.
*/
virtual void LayerSetUp(const vector<Blob*>& bottom,
const vector<Blob*>& top) {}
/**
* @brief Adjust the shapes of top blobs and internal buffers to accommodate
* the shapes of the bottom blobs.
*
* @param bottom the input blobs, with the requested input shapes
* @param top the top blobs, which should be reshaped as needed
*
* This method should reshape top blobs as needed according to the shapes
* of the bottom (input) blobs, as well as reshaping any internal buffers
* and making any other necessary adjustments so that the layer can
* accommodate the bottom blobs.
*/
virtual void Reshape(const vector<Blob*>& bottom,
const vector<Blob*>& top) = 0;
/**
* @brief Given the bottom blobs, compute the top blobs and the loss.
*
* @param bottom
* the input blobs, whose data fields store the input data for this layer
* @param top
* the preshaped output blobs, whose data fields will store this layers'
* outputs
* \return The total loss from the layer.
*
* The Forward wrapper calls the relevant device wrapper function
* (Forward_cpu or Forward_gpu) to compute the top blob values given the
* bottom blobs. If the layer has any non-zero loss_weights, the wrapper
* then computes and returns the loss.
*
* Your layer should implement Forward_cpu and (optionally) Forward_gpu.
*/
inline void Forward(const vector<Blob*>& bottom,
const vector<Blob*>& top);
/*! \brief get internal temporary blobs to share memory */
virtual std::vector<Blob*> GetTempBlobs() { return {}; }
/**
* @brief Returns the vector of learnable parameter blobs.
*/
vector<shared_ptr<Blob> >& blobs() { return blobs_; }
/**
* @brief Returns the layer parameter.
*/
const LayerParameter& layer_param() const { return layer_param_; }
/**
* @brief Writes the layer parameter to a protocol buffer
*/
virtual void ToProto(LayerParameter* param);
/**
* @brief Returns the layer type.
*/
virtual const char* type() const = 0;
/**
* @brief Returns the exact number of bottom blobs required by the layer,
* or -1 if no exact number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some exact number of bottom blobs.
*/
virtual int ExactNumBottomBlobs() const { return -1; }
/**
* @brief Returns the minimum number of bottom blobs required by the layer,
* or -1 if no minimum number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some minimum number of bottom blobs.
*/
virtual int MinBottomBlobs() const { return -1; }
/**
* @brief Returns the maximum number of bottom blobs required by the layer,
* or -1 if no maximum number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some maximum number of bottom blobs.
*/
virtual int MaxBottomBlobs() const { return -1; }
/**
* @brief Returns the exact number of top blobs required by the layer,
* or -1 if no exact number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some exact number of top blobs.
*/
virtual int ExactNumTopBlobs() const { return -1; }
/**
* @brief Returns the minimum number of top blobs required by the layer,
* or -1 if no minimum number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some minimum number of top blobs.
*/
virtual int MinTopBlobs() const { return -1; }
/**
* @brief Returns the maximum number of top blobs required by the layer,
* or -1 if no maximum number is required.
*
* This method should be overridden to return a non-negative value if your
* layer expects some maximum number of top blobs.
*/
virtual int MaxTopBlobs() const { return -1; }
/**
* @brief Returns true if the layer requires an equal number of bottom and
* top blobs.
*
* This method should be overridden to return true if your layer expects an
* equal number of bottom and top blobs.
*/
virtual bool EqualNumBottomTopBlobs() const { return false; }
protected:
/** The protobuf that stores the layer parameters */
LayerParameter layer_param_;
/** The vector that stores the learnable parameters as a set of blobs. */
vector<shared_ptr<Blob> > blobs_;
/** @brief Using the CPU device, compute the layer output. */
virtual void Forward_cpu(const vector<Blob*>& bottom,
const vector<Blob*>& top) = 0;
/**
* @brief Using the GPU device, compute the layer output.
* Fall back to Forward_cpu() if unavailable.
*/
virtual void Forward_gpu(const vector<Blob*>& bottom,
const vector<Blob*>& top) {
// LOG(WARNING) << "Using CPU code as backup.";
return Forward_cpu(bottom, top);
}
/**
* Called by the parent Layer's SetUp to check that the number of bottom
* and top Blobs provided as input match the expected numbers specified by
* the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions.
*/
virtual void CheckBlobCounts(const vector<Blob*>& bottom,
const vector<Blob*>& top) {
if (ExactNumBottomBlobs() >= 0) {
CHECK_EQ(ExactNumBottomBlobs(), bottom.size())
<< type() << " Layer takes " << ExactNumBottomBlobs()
<< " bottom blob(s) as input.";
}
if (MinBottomBlobs() >= 0) {
CHECK_LE(MinBottomBlobs(), bottom.size())
<< type() << " Layer takes at least " << MinBottomBlobs()
<< " bottom blob(s) as input.";
}
if (MaxBottomBlobs() >= 0) {
CHECK_GE(MaxBottomBlobs(), bottom.size())
<< type() << " Layer takes at most " << MaxBottomBlobs()
<< " bottom blob(s) as input.";
}
if (ExactNumTopBlobs() >= 0) {
CHECK_EQ(ExactNumTopBlobs(), top.size())
<< type() << " Layer produces " << ExactNumTopBlobs()
<< " top blob(s) as output.";
}
if (MinTopBlobs() >= 0) {
CHECK_LE(MinTopBlobs(), top.size())
<< type() << " Layer produces at least " << MinTopBlobs()
<< " top blob(s) as output.";
}
if (MaxTopBlobs() >= 0) {
CHECK_GE(MaxTopBlobs(), top.size())
<< type() << " Layer produces at most " << MaxTopBlobs()
<< " top blob(s) as output.";
}
if (EqualNumBottomTopBlobs()) {
CHECK_EQ(bottom.size(), top.size())
<< type() << " Layer produces one top blob as output for each "
<< "bottom blob input.";
}
}
private:
DISABLE_COPY_AND_ASSIGN(Layer);
}; // class Layer
// Forward and backward wrappers. You should implement the cpu and
// gpu specific implementations instead, and should not change these
// functions.
inline void Layer::Forward(const vector<Blob*>& bottom,
const vector<Blob*>& top) {
switch (Caffe::mode()) {
case Caffe::CPU:
Forward_cpu(bottom, top);
break;
case Caffe::GPU:
Forward_gpu(bottom, top);
break;
default:
LOG(FATAL) << "Unknown caffe mode.";
}
}
// Serialize LayerParameter to protocol buffer
inline void Layer::ToProto(LayerParameter* param) {
param->Clear();
param->CopyFrom(layer_param_);
param->clear_blobs();
for (int i = 0; i < blobs_.size(); ++i) {
blobs_[i]->ToProto(param->add_blobs());
}
}
} // namespace caffe
#endif // CAFFE_LAYER_H_
| 35.081633 | 80 | 0.648051 | ktts16 |
6024aefffe637beddb37039687919122f3c2fcc1 | 6,999 | cpp | C++ | Siv3D/src/Siv3D/ImageFormat/PNG/PNGEncoder.cpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 2 | 2021-11-22T00:52:48.000Z | 2021-12-24T09:33:55.000Z | Siv3D/src/Siv3D/ImageFormat/PNG/PNGEncoder.cpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | null | null | null | Siv3D/src/Siv3D/ImageFormat/PNG/PNGEncoder.cpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 1 | 2021-12-31T05:08:00.000Z | 2021-12-31T05:08:00.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/ImageFormat/PNGEncoder.hpp>
# include <Siv3D/BinaryWriter.hpp>
# include <Siv3D/Image.hpp>
# include <Siv3D/EngineLog.hpp>
# if SIV3D_PLATFORM(WINDOWS) | SIV3D_PLATFORM(MACOS) | SIV3D_PLATFORM(WEB)
# include <ThirdParty-prebuilt/libpng/png.h>
# else
# include <png.h>
# endif
namespace s3d
{
static void PngWriteCallbackIWriter(png_structp png_ptr, png_bytep src, png_size_t length)
{
IWriter* pWriter = static_cast<IWriter*>(::png_get_io_ptr(png_ptr));
pWriter->write(src, length);
}
static void PngWriteCallbackBlob(png_structp png_ptr, png_bytep src, png_size_t length)
{
Blob* pBlob = static_cast<Blob*>(::png_get_io_ptr(png_ptr));
pBlob->append(src, length);
}
StringView PNGEncoder::name() const
{
return U"PNG"_sv;
}
ImageFormat PNGEncoder::imageFormat() const noexcept
{
return ImageFormat::PNG;
}
bool PNGEncoder::save(const Image& image, const FilePathView path) const
{
return save(image, path, PNGFilter::Default);
}
const Array<String>& PNGEncoder::possibleExtensions() const
{
static const Array<String> extensions = { U"png" };
return extensions;
}
bool PNGEncoder::save(const Image& image, const FilePathView path, const PNGFilter filter) const
{
BinaryWriter writer{ path };
if (not writer)
{
return false;
}
return encode(image, writer, filter);
}
bool PNGEncoder::save(const Grid<uint16>& image, const FilePathView path, const PNGFilter filter) const
{
BinaryWriter writer{ path };
if (not writer)
{
return false;
}
return encode(image, writer, filter);
}
bool PNGEncoder::encode(const Image& image, IWriter& writer) const
{
return encode(image, writer, PNGFilter::Default);
}
bool PNGEncoder::encode(const Image& image, IWriter& writer, const PNGFilter filter) const
{
if (not writer.isOpen())
{
return false;
}
png_structp png_ptr = ::png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (not png_ptr)
{
return false;
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if (not info_ptr)
{
::png_destroy_write_struct(&png_ptr, nullptr);
return false;
}
::png_set_write_fn(png_ptr, &writer, PngWriteCallbackIWriter, nullptr);
const png_uint_32 width = image.width();
const png_uint_32 height = image.height();
::png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
::png_set_filter(png_ptr, 0, FromEnum(filter));
::png_write_info(png_ptr, info_ptr);
const uint8* pRow = image.dataAsUint8();
for (uint32 y = 0; y < height; ++y)
{
::png_write_row(png_ptr, pRow);
pRow += image.stride();
}
::png_write_end(png_ptr, info_ptr);
::png_destroy_write_struct(&png_ptr, &info_ptr);
return true;
}
bool PNGEncoder::encode(const Grid<uint16>& image, IWriter& writer, const PNGFilter filter) const
{
if (not writer.isOpen())
{
return false;
}
png_structp png_ptr = ::png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (not png_ptr)
{
return false;
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if (not info_ptr)
{
::png_destroy_write_struct(&png_ptr, nullptr);
return false;
}
::png_set_write_fn(png_ptr, &writer, PngWriteCallbackIWriter, nullptr);
const png_uint_32 width = static_cast<png_uint_32>(image.width());
const png_uint_32 height = static_cast<png_uint_32>(image.height());
::png_set_IHDR(png_ptr, info_ptr, width, height, 16, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
::png_set_filter(png_ptr, 0, FromEnum(filter));
::png_write_info(png_ptr, info_ptr);
const uint8* pRow = static_cast<const uint8*>(static_cast<const void*>(image.data()));
const uint32 stride = (width * sizeof(uint16));
Array<const uint8*> rows(image.height());
for (uint32 y = 0; y < height; ++y)
{
rows[y] = pRow;
pRow += stride;
}
::png_set_rows(png_ptr, info_ptr, (png_bytepp)rows.data());
::png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_SWAP_ENDIAN, nullptr);
::png_destroy_write_struct(&png_ptr, &info_ptr);
return true;
}
Blob PNGEncoder::encode(const Image& image) const
{
return encode(image, PNGFilter::Default);
}
Blob PNGEncoder::encode(const Image& image, const PNGFilter filter) const
{
png_structp png_ptr = ::png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (not png_ptr)
{
return{};
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if (not info_ptr)
{
::png_destroy_write_struct(&png_ptr, nullptr);
return{};
}
Blob blob;
::png_set_write_fn(png_ptr, &blob, PngWriteCallbackBlob, nullptr);
const png_uint_32 width = image.width();
const png_uint_32 height = image.height();
::png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
::png_set_filter(png_ptr, 0, FromEnum(filter));
::png_write_info(png_ptr, info_ptr);
const uint8* pRow = image.dataAsUint8();
for (uint32 y = 0; y < height; ++y)
{
::png_write_row(png_ptr, pRow);
pRow += image.stride();
}
::png_write_end(png_ptr, info_ptr);
::png_destroy_write_struct(&png_ptr, &info_ptr);
return blob;
}
Blob PNGEncoder::encode(const Grid<uint16>& image, const PNGFilter filter) const
{
png_structp png_ptr = ::png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (not png_ptr)
{
return{};
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if (not info_ptr)
{
::png_destroy_write_struct(&png_ptr, nullptr);
return{};
}
Blob blob;
::png_set_write_fn(png_ptr, &blob, PngWriteCallbackBlob, nullptr);
const png_uint_32 width = static_cast<png_uint_32>(image.width());
const png_uint_32 height = static_cast<png_uint_32>(image.height());
::png_set_IHDR(png_ptr, info_ptr, width, height, 16, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
::png_set_filter(png_ptr, 0, FromEnum(filter));
::png_write_info(png_ptr, info_ptr);
const uint8* pRow = static_cast<const uint8*>(static_cast<const void*>(image.data()));
const uint32 stride = (width * sizeof(uint16));
Array<const uint8*> rows(image.height());
for (uint32 y = 0; y < height; ++y)
{
rows[y] = pRow;
pRow += stride;
}
::png_set_rows(png_ptr, info_ptr, (png_bytepp)rows.data());
::png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_SWAP_ENDIAN, nullptr);
::png_destroy_write_struct(&png_ptr, &info_ptr);
return blob;
}
}
| 22.947541 | 155 | 0.703529 | tas9n |
602a979b1bad0c2a510c897bb3e5594572b7512c | 1,850 | cpp | C++ | Source/hud.cpp | OneSadCookie/Astro | 4b7de6fc7bff4010a0f9aa3ed6b9029e79a785b1 | [
"Zlib"
] | null | null | null | Source/hud.cpp | OneSadCookie/Astro | 4b7de6fc7bff4010a0f9aa3ed6b9029e79a785b1 | [
"Zlib"
] | null | null | null | Source/hud.cpp | OneSadCookie/Astro | 4b7de6fc7bff4010a0f9aa3ed6b9029e79a785b1 | [
"Zlib"
] | null | null | null | #include "hud.hpp"
#include "globals.hpp"
#include "main.hpp"
#include "ufo.hpp"
void hud_draw(int lives, unsigned long score, const world& w) {
int i;
float y = 2 * ufo::properties().averageRadius;
unsigned char score_string[128];
ufo life;
float scale;
glColor4f(1, 1, 1, 0.5);
for (i = 0; i < lives; ++i) {
float x = w.width - (2.5 * i + 2) * ufo::properties().averageRadius;
life.set_position(vector(x, y, w.z_plane));
life.draw();
}
glPushMatrix();
sprintf((char*)score_string, "%lu", score);
glColor4fv(TEXT_COLOR);
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glTranslatef(ufo::properties().averageRadius, 2 * ufo::properties().averageRadius, 0);
scale = 2 * ufo::properties().averageRadius / GLUT_STROKE_FONT_HEIGHT_EXT;
glScalef(scale, -scale, scale);
glutStrokeStringEXT(GLUT_STROKE_ROMAN, score_string);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
glPopMatrix();
glColor3f(1, 1, 1);
}
void hud_erase(int lives, unsigned long score, const world& w) {
int i;
float y = 2 * ufo::properties().averageRadius;
unsigned char score_string[128];
ufo life;
float scale;
for (i = 0; i < lives; ++i) {
float x = w.width - (2.5 * i + 2) * ufo::properties().averageRadius;
life.set_position(vector(x, y, w.z_plane));
life.erase();
}
glPushMatrix();
sprintf((char*)score_string, "%lu", score);
glColor4fv(BACKGROUND_COLOR);
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glTranslatef(ufo::properties().averageRadius, 2 * ufo::properties().averageRadius, 0);
scale = 2 * ufo::properties().averageRadius / GLUT_STROKE_FONT_HEIGHT_EXT;
glScalef(scale, -scale, scale);
glutStrokeStringEXT(GLUT_STROKE_ROMAN, score_string);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
glPopMatrix();
glColor3f(1, 1, 1);
}
| 23.125 | 88 | 0.658919 | OneSadCookie |
602b5b2cf413b8efa1fab81c067e46dad156a5e6 | 274 | cpp | C++ | 200119Zad01/zad01.cpp | elenazaharieva/fifthgrade | 60d1301c118b9f0cb4089d672fdf9e1780aedf80 | [
"Apache-2.0"
] | null | null | null | 200119Zad01/zad01.cpp | elenazaharieva/fifthgrade | 60d1301c118b9f0cb4089d672fdf9e1780aedf80 | [
"Apache-2.0"
] | null | null | null | 200119Zad01/zad01.cpp | elenazaharieva/fifthgrade | 60d1301c118b9f0cb4089d672fdf9e1780aedf80 | [
"Apache-2.0"
] | null | null | null | /*
* zad01.cpp
*
* Created on: Jan 19, 2020
* Author: eli
*/
#include <iostream>
using namespace std;
int main() {
int B;
int chislo;
int suma = 0;
cin >> B;
do {
cin >> chislo;
suma += chislo;
} while (suma <= B);
cout << suma << endl;
return 0;
}
| 11.913043 | 28 | 0.543796 | elenazaharieva |
6031d02aa3db17231cfb1c391c3bd805a361e4d6 | 4,907 | cpp | C++ | src/lib/ffi/ffi_cert.cpp | Sirrix-AG/botan | d2cb5601b28969b045762b66200f816639a9a763 | [
"BSD-2-Clause"
] | 16 | 2018-03-27T13:22:23.000Z | 2019-03-04T12:21:12.000Z | src/lib/ffi/ffi_cert.cpp | Sirrix-AG/botan | d2cb5601b28969b045762b66200f816639a9a763 | [
"BSD-2-Clause"
] | 2 | 2019-10-05T15:38:45.000Z | 2021-05-20T18:30:57.000Z | src/lib/ffi/ffi_cert.cpp | Sirrix-AG/botan | d2cb5601b28969b045762b66200f816639a9a763 | [
"BSD-2-Clause"
] | 3 | 2020-04-02T12:52:49.000Z | 2021-07-01T13:29:41.000Z | /*
* (C) 2015,2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/ffi.h>
#include <botan/internal/ffi_util.h>
#include <botan/internal/ffi_pkey.h>
#include <botan/x509cert.h>
#include <botan/data_src.h>
extern "C" {
using namespace Botan_FFI;
BOTAN_FFI_DECLARE_STRUCT(botan_x509_cert_struct, Botan::X509_Certificate, 0x8F628937);
int botan_x509_cert_load_file(botan_x509_cert_t* cert_obj, const char* cert_path)
{
return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {
if(!cert_obj || !cert_path)
return BOTAN_FFI_ERROR_NULL_POINTER;
#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
std::unique_ptr<Botan::X509_Certificate> c(new Botan::X509_Certificate(cert_path));
*cert_obj = new botan_x509_cert_struct(c.release());
return BOTAN_FFI_SUCCESS;
#else
return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;
#endif
});
}
int botan_x509_cert_load(botan_x509_cert_t* cert_obj, const uint8_t cert_bits[], size_t cert_bits_len)
{
return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {
if(!cert_obj || !cert_bits)
return BOTAN_FFI_ERROR_NULL_POINTER;
Botan::DataSource_Memory bits(cert_bits, cert_bits_len);
std::unique_ptr<Botan::X509_Certificate> c(new Botan::X509_Certificate(bits));
*cert_obj = new botan_x509_cert_struct(c.release());
return BOTAN_FFI_SUCCESS;
});
}
int botan_x509_cert_get_public_key(botan_x509_cert_t cert, botan_pubkey_t* key)
{
return ffi_guard_thunk(BOTAN_CURRENT_FUNCTION, [=]() -> int {
if(key == nullptr)
return BOTAN_FFI_ERROR_NULL_POINTER;
*key = nullptr;
#if defined(BOTAN_HAS_RSA)
std::unique_ptr<Botan::Public_Key> publicKey = safe_get(cert).load_subject_public_key();
*key = new botan_pubkey_struct(publicKey.release());
return BOTAN_FFI_SUCCESS;
#else
return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;
#endif
});
}
int botan_x509_cert_get_issuer_dn(botan_x509_cert_t cert,
const char* key, size_t index,
uint8_t out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_str_output(out, out_len, c.issuer_info(key).at(index)); });
}
int botan_x509_cert_get_subject_dn(botan_x509_cert_t cert,
const char* key, size_t index,
uint8_t out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_str_output(out, out_len, c.subject_info(key).at(index)); });
}
int botan_x509_cert_to_string(botan_x509_cert_t cert, char out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_str_output(out, out_len, c.to_string()); });
}
int botan_x509_cert_allowed_usage(botan_x509_cert_t cert, unsigned int key_usage)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, {
const Botan::Key_Constraints k = static_cast<Botan::Key_Constraints>(key_usage);
if(c.allowed_usage(k))
return BOTAN_FFI_SUCCESS;
return 1;
});
}
int botan_x509_cert_destroy(botan_x509_cert_t cert)
{
return BOTAN_FFI_CHECKED_DELETE(cert);
}
int botan_x509_cert_get_time_starts(botan_x509_cert_t cert, char out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_str_output(out, out_len, c.not_before().to_string()); });
}
int botan_x509_cert_get_time_expires(botan_x509_cert_t cert, char out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_str_output(out, out_len, c.not_after().to_string()); });
}
int botan_x509_cert_get_serial_number(botan_x509_cert_t cert, uint8_t out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_vec_output(out, out_len, c.serial_number()); });
}
int botan_x509_cert_get_fingerprint(botan_x509_cert_t cert, const char* hash, uint8_t out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_str_output(out, out_len, c.fingerprint(hash)); });
}
int botan_x509_cert_get_authority_key_id(botan_x509_cert_t cert, uint8_t out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_vec_output(out, out_len, c.authority_key_id()); });
}
int botan_x509_cert_get_subject_key_id(botan_x509_cert_t cert, uint8_t out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_vec_output(out, out_len, c.subject_key_id()); });
}
int botan_x509_cert_get_public_key_bits(botan_x509_cert_t cert, uint8_t out[], size_t* out_len)
{
return BOTAN_FFI_DO(Botan::X509_Certificate, cert, c, { return write_vec_output(out, out_len, c.subject_public_key_bits()); });
}
}
| 35.817518 | 132 | 0.715305 | Sirrix-AG |
6033bf4ca2747987db836aef5eae2817bcba932a | 15,961 | cpp | C++ | src/widgets/CLabel.cpp | RoboticsDesignLab/chai3d | 66927fb9c81a173b988e1fc81cf6bfd57d69dcd7 | [
"BSD-3-Clause"
] | 75 | 2016-12-22T14:53:01.000Z | 2022-03-31T08:04:19.000Z | src/widgets/CLabel.cpp | RoboticsDesignLab/chai3d | 66927fb9c81a173b988e1fc81cf6bfd57d69dcd7 | [
"BSD-3-Clause"
] | 6 | 2017-04-03T21:27:16.000Z | 2019-08-28T17:05:23.000Z | src/widgets/CLabel.cpp | RoboticsDesignLab/chai3d | 66927fb9c81a173b988e1fc81cf6bfd57d69dcd7 | [
"BSD-3-Clause"
] | 53 | 2017-03-16T16:38:34.000Z | 2022-02-25T14:31:01.000Z | //==============================================================================
/*
Software License Agreement (BSD License)
Copyright (c) 2003-2016, CHAI3D.
(www.chai3d.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of CHAI3D nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\author <http://www.chai3d.org>
\author Francois Conti
\version 3.2.0 $Rev: 2153 $
*/
//==============================================================================
//------------------------------------------------------------------------------
#include "CLabel.h"
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace chai3d {
//------------------------------------------------------------------------------
//==============================================================================
/*!
Constructor of cLabel.
*/
//==============================================================================
cLabel::cLabel(cFontPtr a_font)
{
// set label properties
m_fontScale = 1.0;
m_letterSpacing = 1.0;
m_lineSpacing = 1.0;
m_text = "";
m_font = a_font;
// set panel properties
m_panelColorTopLeft.setGrayLevel(0.40f);
m_panelColorTopRight.setGrayLevel(0.40f);
m_panelColorBottomLeft.setGrayLevel(0.40f);
m_panelColorBottomRight.setGrayLevel(0.40f);
m_panelRadiusTopLeft = 0.0;
m_panelRadiusTopRight = 0.0;
m_panelRadiusBottomLeft = 0.0;
m_panelRadiusBottomRight = 0.0;
m_numPanelSegmentsPerCorner = 8;
m_showPanel = false;
}
//==============================================================================
/*!
Destructor of cLabel.
*/
//==============================================================================
cLabel::~cLabel()
{
}
//==============================================================================
/*!
This method renders the label using OpenGL.
\param a_options Rendering options.
*/
//==============================================================================
void cLabel::render(cRenderOptions& a_options)
{
#ifdef C_USE_OPENGL
// render background panel
if (m_showPanel)
{
cMesh::render(a_options);
}
/////////////////////////////////////////////////////////////////////////
// Render parts that are always opaque
/////////////////////////////////////////////////////////////////////////
if (SECTION_RENDER_OPAQUE_PARTS_ONLY(a_options))
{
// disable lighting properties
glDisable(GL_LIGHTING);
// render font color
m_fontColor.render();
// render string at desired location
glPushMatrix();
glTranslated(m_marginLeft, m_marginBottom, 0.0);
m_font->renderText(m_text, m_fontColor, m_fontScale, m_letterSpacing, m_lineSpacing, a_options);
glPopMatrix();
// enable lighting properties
glEnable(GL_LIGHTING);
}
#endif
}
//==============================================================================
/*!
This method assigns a text string to rendered by this label.
\param a_text Input text string.
*/
//==============================================================================
void cLabel::setText(const string a_text)
{
// copy string
m_text = a_text;
// get width and height of string
double w = getTextWidth();
double h = getTextHeight();
// add margins
w = w + m_marginLeft + m_marginRight;
h = h + m_marginTop + m_marginBottom;
// set size of panel
setSize(w, h);
// adjust size of boundary box
updateBoundaryBox();
}
//==============================================================================
/*!
This method sets the font scale factor.
\param a_scale Scale factor.
*/
//==============================================================================
void cLabel::setFontScale(const double a_scale)
{
// update scale factor
m_fontScale = fabs(a_scale);
// adjust size of boundary box
updateBoundaryBox();
}
//==============================================================================
/*!
This method returns the width of the current text string in pixels.
\return Length of current text string in pixels.
*/
//==============================================================================
double cLabel::getTextWidth() const
{
if (m_font == NULL)
{
return (0);
}
else
{
return (m_fontScale * m_font->getTextWidth(m_text, m_letterSpacing));
}
}
//==============================================================================
/*!
This method returns the height of the current text string in pixels.
\return Height of text string in pixels.
*/
//==============================================================================
double cLabel::getTextHeight() const
{
if (m_font == NULL)
{
return (0);
}
else
{
return (m_fontScale * m_font->getTextHeight(m_text, m_lineSpacing));
}
}
//==============================================================================
/*!
This method creates a copy of itself.
\param a_duplicateMaterialData If __true__, material (if available) is duplicated, otherwise it is shared.
\param a_duplicateTextureData If __true__, texture data (if available) is duplicated, otherwise it is shared.
\param a_duplicateMeshData If __true__, mesh data (if available) is duplicated, otherwise it is shared.
\param a_buildCollisionDetector If __true__, collision detector (if available) is duplicated, otherwise it is shared.
\return Pointer to new object.
*/
//==============================================================================
cLabel* cLabel::copy(const bool a_duplicateMaterialData,
const bool a_duplicateTextureData,
const bool a_duplicateMeshData,
const bool a_buildCollisionDetector)
{
cLabel* obj = new cLabel(m_font);
// copy cLabel properties
copyLabelProperties(obj,
a_duplicateMaterialData,
a_duplicateTextureData,
a_duplicateMeshData,
a_buildCollisionDetector);
// return object
return (obj);
}
//==============================================================================
/*!
This method copies all properties of this object to another.
\param a_obj Destination object where properties are copied to.
\param a_duplicateMaterialData If __true__, material (if available) is duplicated, otherwise it is shared.
\param a_duplicateTextureData If __true__, texture data (if available) is duplicated, otherwise it is shared.
\param a_duplicateMeshData If __true__, mesh data (if available) is duplicated, otherwise it is shared.
\param a_buildCollisionDetector If __true__, collision detector (if available) is duplicated, otherwise it is shared.
*/
//==============================================================================
void cLabel::copyLabelProperties(cLabel* a_obj,
const bool a_duplicateMaterialData,
const bool a_duplicateTextureData,
const bool a_duplicateMeshData,
const bool a_buildCollisionDetector)
{
// copy properties of cPanel
copyPanelProperties(a_obj,
a_duplicateMaterialData,
a_duplicateTextureData,
a_duplicateMeshData,
a_buildCollisionDetector);
// copy properties of cLabel
a_obj->m_fontScale = m_fontScale;
a_obj->m_fontColor = m_fontColor;
a_obj->setText(m_text);
}
//==============================================================================
/*!
This method determines whether a given segment intersects with this label.
The segment is described by a start \p a_segmentPointA and end
point \p a_segmentPointB.
\param a_segmentPointA Start point of segment.
\param a_segmentPointB End point of segment.
\param a_recorder Recorder which stores all collision events.
\param a_settings Contains collision settings information.
\return __true__ if a collision has occurred, __false__ otherwise.
*/
//==============================================================================
bool cLabel::computeOtherCollisionDetection(cVector3d& a_segmentPointA,
cVector3d& a_segmentPointB,
cCollisionRecorder& a_recorder,
cCollisionSettings& a_settings)
{
////////////////////////////////////////////////////////////////////////////
// COMPUTE COLLISION
////////////////////////////////////////////////////////////////////////////
// check if panel is enabled. if enabled, ignore as collision will be computed
// with the triangles composing the panel.
if (m_showPanel) { return (false); }
// no collision has occurred yet
bool hit = false;
// temp variable to store collision data
cVector3d collisionPoint;
cVector3d collisionNormal;
double c01, c02;
double collisionDistanceSq = 0.0;
// compute collision detection between segment and sphere
if (cIntersectionSegmentTriangle(a_segmentPointA,
a_segmentPointB,
cVector3d(0.0, 0.0, 0.0),
cVector3d(m_width, 0.0, 0.0),
cVector3d(m_width, m_height, 0.0),
true,
true,
collisionPoint,
collisionNormal,
c01,
c02))
{
hit = true;
collisionDistanceSq = cDistanceSq(a_segmentPointA, collisionPoint);
}
else
{
if (cIntersectionSegmentTriangle(a_segmentPointA,
a_segmentPointB,
cVector3d(0.0, 0.0, 0.0),
cVector3d(m_width, m_height, 0.0),
cVector3d(0.0, m_height, 0.0),
true,
true,
collisionPoint,
collisionNormal,
c01,
c02))
{
hit = true;
collisionDistanceSq = cDistanceSq(a_segmentPointA, collisionPoint);
}
}
////////////////////////////////////////////////////////////////////////////
// REPORT COLLISION
////////////////////////////////////////////////////////////////////////////
// here we finally report the new collision to the collision event handler.
if (hit)
{
// we verify if anew collision needs to be created or if we simply
// need to update the nearest collision.
if (a_settings.m_checkForNearestCollisionOnly)
{
// no new collision event is create. We just check if we need
// to update the nearest collision
if(collisionDistanceSq <= a_recorder.m_nearestCollision.m_squareDistance)
{
// report basic collision data
a_recorder.m_nearestCollision.m_type = C_COL_SHAPE;
a_recorder.m_nearestCollision.m_object = this;
a_recorder.m_nearestCollision.m_localPos = collisionPoint;
a_recorder.m_nearestCollision.m_localNormal = collisionNormal;
a_recorder.m_nearestCollision.m_squareDistance = collisionDistanceSq;
a_recorder.m_nearestCollision.m_adjustedSegmentAPoint = a_segmentPointA;
// report advanced collision data
if (!a_settings.m_returnMinimalCollisionData)
{
a_recorder.m_nearestCollision.m_globalPos = cAdd(getGlobalPos(),
cMul(getGlobalRot(),
a_recorder.m_nearestCollision.m_localPos));
a_recorder.m_nearestCollision.m_globalNormal = cMul(getGlobalRot(),
a_recorder.m_nearestCollision.m_localNormal);
}
}
}
else
{
cCollisionEvent newCollisionEvent;
// report basic collision data
newCollisionEvent.m_type = C_COL_SHAPE;
newCollisionEvent.m_object = this;
newCollisionEvent.m_triangles = nullptr;
newCollisionEvent.m_localPos = collisionPoint;
newCollisionEvent.m_localNormal = collisionNormal;
newCollisionEvent.m_squareDistance = collisionDistanceSq;
newCollisionEvent.m_adjustedSegmentAPoint = a_segmentPointA;
// report advanced collision data
if (!a_settings.m_returnMinimalCollisionData)
{
newCollisionEvent.m_globalPos = cAdd(getGlobalPos(),
cMul(getGlobalRot(),
newCollisionEvent.m_localPos));
newCollisionEvent.m_globalNormal = cMul(getGlobalRot(),
newCollisionEvent.m_localNormal);
}
// add new collision even to collision list
a_recorder.m_collisions.push_back(newCollisionEvent);
// check if this new collision is a candidate for "nearest one"
if(collisionDistanceSq <= a_recorder.m_nearestCollision.m_squareDistance)
{
a_recorder.m_nearestCollision = newCollisionEvent;
}
}
}
// return result
return (hit);
}
//------------------------------------------------------------------------------
} // namespace chai3d
//------------------------------------------------------------------------------
| 37.118605 | 124 | 0.499217 | RoboticsDesignLab |
6038f35cbdc388f245825407664adec4577c467c | 251 | cpp | C++ | categorias/iniciante/c++/1114.cpp | carlos3g/URI-solutions | dc7f9b896cdff88aedf67611917b178d3ad60ab3 | [
"MIT"
] | 1 | 2022-01-26T23:38:17.000Z | 2022-01-26T23:38:17.000Z | categorias/iniciante/c++/1114.cpp | carlos3g/URI-solutions | dc7f9b896cdff88aedf67611917b178d3ad60ab3 | [
"MIT"
] | 1 | 2020-07-12T00:49:35.000Z | 2021-06-26T20:53:18.000Z | categorias/iniciante/c++/1114.cpp | carlos3g/URI-solutions | dc7f9b896cdff88aedf67611917b178d3ad60ab3 | [
"MIT"
] | 1 | 2020-07-04T03:27:04.000Z | 2020-07-04T03:27:04.000Z | #include <iostream>
#define PASS 2002
using namespace std;
int main() {
int input;
cin >> input;
while (input != PASS) {
cout << "Senha Invalida\n";
cin >> input;
}
cout << "Acesso Permitido\n";
return 0;
} | 13.944444 | 35 | 0.541833 | carlos3g |
603ca6aefadb0958e9dbdf6d4faf7dbccc3bbcc3 | 2,310 | cpp | C++ | src/interactivity/win32/consoleKeyInfo.cpp | hessedoneen/terminal | aa54de1d648f45920996aeba1edecc67237c6642 | [
"MIT"
] | 34,359 | 2019-05-06T21:04:42.000Z | 2019-05-14T22:06:43.000Z | src/interactivity/win32/consoleKeyInfo.cpp | Ingridamilsina/terminal | 788d33ce94d28e2903bc49f841ce279211b7f557 | [
"MIT"
] | 356 | 2019-05-06T21:03:35.000Z | 2019-05-14T21:38:47.000Z | src/interactivity/win32/consoleKeyInfo.cpp | Ingridamilsina/terminal | 788d33ce94d28e2903bc49f841ce279211b7f557 | [
"MIT"
] | 3,164 | 2019-05-06T21:06:01.000Z | 2019-05-14T20:25:52.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "consoleKeyInfo.hpp"
// The following data structures are a hack to work around the fact that
// MapVirtualKey does not return the correct virtual key code in many cases.
// we store the correct info (from the keydown message) in the CONSOLE_KEY_INFO
// structure when a keydown message is translated. Then when we receive a
// wm_[sys][dead]char message, we retrieve it and clear out the record.
#define CONSOLE_FREE_KEY_INFO nullptr
#define CONSOLE_MAX_KEY_INFO 32
typedef struct _CONSOLE_KEY_INFO
{
HWND hWnd;
WORD wVirtualKeyCode;
WORD wVirtualScanCode;
} CONSOLE_KEY_INFO, *PCONSOLE_KEY_INFO;
CONSOLE_KEY_INFO ConsoleKeyInfo[CONSOLE_MAX_KEY_INFO];
void StoreKeyInfo(_In_ PMSG msg)
{
UINT i;
for (i = 0; i < CONSOLE_MAX_KEY_INFO; i++)
{
if (ConsoleKeyInfo[i].hWnd == CONSOLE_FREE_KEY_INFO || ConsoleKeyInfo[i].hWnd == msg->hwnd)
{
break;
}
}
if (i != CONSOLE_MAX_KEY_INFO)
{
ConsoleKeyInfo[i].hWnd = msg->hwnd;
ConsoleKeyInfo[i].wVirtualKeyCode = LOWORD(msg->wParam);
ConsoleKeyInfo[i].wVirtualScanCode = (BYTE)(HIWORD(msg->lParam));
}
else
{
RIPMSG0(RIP_WARNING, "ConsoleKeyInfo buffer is full");
}
}
void RetrieveKeyInfo(_In_ HWND hWnd, _Out_ PWORD pwVirtualKeyCode, _Inout_ PWORD pwVirtualScanCode, _In_ BOOL FreeKeyInfo)
{
UINT i;
for (i = 0; i < CONSOLE_MAX_KEY_INFO; i++)
{
if (ConsoleKeyInfo[i].hWnd == hWnd)
{
break;
}
}
if (i != CONSOLE_MAX_KEY_INFO)
{
*pwVirtualKeyCode = ConsoleKeyInfo[i].wVirtualKeyCode;
*pwVirtualScanCode = ConsoleKeyInfo[i].wVirtualScanCode;
if (FreeKeyInfo)
{
ConsoleKeyInfo[i].hWnd = CONSOLE_FREE_KEY_INFO;
}
}
else
{
*pwVirtualKeyCode = (WORD)MapVirtualKeyW(*pwVirtualScanCode, 3);
}
}
void ClearKeyInfo(const HWND hWnd)
{
for (UINT i = 0; i < CONSOLE_MAX_KEY_INFO; i++)
{
if (ConsoleKeyInfo[i].hWnd == hWnd)
{
ConsoleKeyInfo[i].hWnd = CONSOLE_FREE_KEY_INFO;
}
}
}
| 26.860465 | 123 | 0.628139 | hessedoneen |
603f7aea274d3b9d4d8c50f42e7cbfa6fc57ae30 | 190 | cpp | C++ | competitive_programming/programming_contests/uri/password.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 205 | 2018-12-01T17:49:49.000Z | 2021-12-22T07:02:27.000Z | competitive_programming/programming_contests/uri/password.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 2 | 2020-01-01T16:34:29.000Z | 2020-04-26T19:11:13.000Z | competitive_programming/programming_contests/uri/password.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 50 | 2018-11-28T20:51:36.000Z | 2021-11-29T04:08:25.000Z | // https://www.urionlinejudge.com.br/judge/en/problems/view/2146
#include <iostream>
using namespace std;
int main() {
int n;
while (cin >> n) {
cout << n-1 << endl;
}
return 0;
} | 12.666667 | 64 | 0.626316 | LeandroTk |
603fb3e33f0e2f0878495beddfab03b4d51c823a | 12,982 | cpp | C++ | src/dale/Form/Type/Type.cpp | ChengCat/dale | 4a764895611679cd1670d9a43ffdbee136661759 | [
"BSD-3-Clause"
] | null | null | null | src/dale/Form/Type/Type.cpp | ChengCat/dale | 4a764895611679cd1670d9a43ffdbee136661759 | [
"BSD-3-Clause"
] | null | null | null | src/dale/Form/Type/Type.cpp | ChengCat/dale | 4a764895611679cd1670d9a43ffdbee136661759 | [
"BSD-3-Clause"
] | null | null | null | #include "Type.h"
#include <cstdio>
#include <string>
#include <vector>
#include "../../Form/TopLevel/GlobalVariable/GlobalVariable.h"
#include "../../Units/Units.h"
#include "../Parameter/Parameter.h"
#include "../Struct/Struct.h"
#include "../Value/Value.h"
using namespace dale::ErrorInst;
static int anon_struct_count = 0;
namespace dale {
int parseLiteralIntegerToInt(Node *node, ErrorReporter *er) {
if (!node->is_token) {
Error *e = new Error(UnexpectedElement, node, "symbol",
"integer", "list");
er->addError(e);
return -1;
}
if (node->token->type != TokenType::Int) {
Error *e = new Error(UnexpectedElement, node, "integer",
"literal", node->token->tokenType());
er->addError(e);
return -1;
}
const char *num_str = node->token->str_value.c_str();
char *end_ptr;
unsigned long num =
strtoul(num_str, &end_ptr, DECIMAL_RADIX); // NOLINT
if (STRTOUL_FAILED(num, num_str, end_ptr)) {
Error *e = new Error(UnableToParseInteger, node,
node->token->str_value.c_str());
er->addError(e);
return -1;
}
return num;
}
Type *parseTypeToken(Units *units, Node *node) {
Context *ctx = units->top()->ctx;
Token *token = node->token;
if (token->type != TokenType::String) {
Error *e = new Error(IncorrectSingleParameterType, node,
"symbol", token->tokenType());
ctx->er->addError(e);
return NULL;
}
const char *type_str = token->str_value.c_str();
int base_type = stringToBaseType(type_str);
if (base_type != -1) {
Type *type = ctx->tr->getBasicType(base_type);
if (type) {
if (!units->top()->is_x86_64 &&
(type->base_type == BaseType::Int128 ||
type->base_type == BaseType::UInt128)) {
Error *e = new Error(TypeNotSupported, node, type_str);
ctx->er->addError(e);
return NULL;
}
return type;
}
}
Struct *st = NULL;
if ((st = ctx->getStruct(type_str))) {
std::string st_name;
bool res = ctx->setFullyQualifiedStructName(type_str, &st_name);
assert(res && "unable to set struct name");
_unused(res);
return ctx->tr->getStructType(st_name.c_str());
}
Error *err = new Error(TypeNotInScope, node, type_str);
ctx->er->addError(err);
return NULL;
}
Type *FormTypeParse(Units *units, Node *node, bool allow_anon_structs,
bool allow_bitfields, bool allow_refs,
bool allow_retvals) {
Context *ctx = units->top()->ctx;
node = units->top()->mp->parsePotentialMacroCall(node);
if (!node) {
return NULL;
} else if (node->is_token) {
return parseTypeToken(units, node);
}
std::vector<Node *> *lst = node->list;
Node *name_node = (*lst)[0];
if (!name_node->is_token) {
Error *e = new Error(FirstListElementMustBeAtom, name_node);
ctx->er->addError(e);
return NULL;
}
Token *token = name_node->token;
if (token->type != TokenType::String) {
Error *e = new Error(FirstListElementMustBeSymbol, name_node);
ctx->er->addError(e);
return NULL;
}
std::vector<Node *> lst_tail;
if (!strcmp(token->str_value.c_str(), "do")) {
lst_tail.assign(lst->begin() + 1, lst->end());
lst = &lst_tail;
if (lst->size() == 1) {
return FormTypeParse(units, (*lst)[0], allow_anon_structs,
allow_bitfields, allow_refs,
allow_retvals);
}
}
if (lst->size() < 2) {
Error *e = new Error(InvalidType, node);
ctx->er->addError(e);
return NULL;
}
Node *fst_node = (*lst)[0];
Node *snd_node = (*lst)[1];
/* If list is a two-element list, where the first element is
* 'ref', then this is a reference type. */
if (lst->size() == 2 && fst_node->is_token &&
!(fst_node->token->str_value.compare("ref"))) {
if (!allow_refs) {
Error *e = new Error(RefsNotPermittedHere, node);
ctx->er->addError(e);
return NULL;
}
/* Reference types are only permitted at the 'node level' of
* the type. */
Type *reference_type = FormTypeParse(
units, snd_node, allow_anon_structs, allow_bitfields);
if (reference_type == NULL) {
return NULL;
}
return ctx->tr->getReferenceType(reference_type);
}
/* If list is a two-element list, where the first element is
* 'rv-ref', then this is an rvalue reference type. */
if (lst->size() == 2 && fst_node->is_token &&
!(fst_node->token->str_value.compare("rv-ref"))) {
if (!allow_refs) {
Error *e = new Error(RefsNotPermittedHere, node);
ctx->er->addError(e);
return NULL;
}
/* Reference types are only permitted at the 'node level' of
* the type. */
Type *rvalue_reference_type = FormTypeParse(
units, snd_node, allow_anon_structs, allow_bitfields);
if (rvalue_reference_type == NULL) {
return NULL;
}
return ctx->tr->getRvalueReferenceType(rvalue_reference_type);
}
/* If list is a two-element list, where the first element is
* 'retval', then this is a retval type. */
if (lst->size() == 2 && fst_node->is_token &&
!(fst_node->token->str_value.compare("retval"))) {
if (!allow_retvals) {
Error *e = new Error(RetvalsNotPermittedHere, node);
ctx->er->addError(e);
return NULL;
}
/* Retval types are only permitted at the 'node level' of
* the type. */
Type *retval_type = FormTypeParse(
units, snd_node, allow_anon_structs, allow_bitfields);
if (retval_type == NULL) {
return NULL;
}
return ctx->tr->getRetvalType(retval_type);
}
/* If list is a two-element list, where the first element is
* 'struct', then this is an anonymous struct. If
* allow_anon_structs is enabled, then construct a list that can
* in turn be used to create that struct, call
* parseStructDefinition, and then use that new struct name as the
* value of this element. */
if (allow_anon_structs && lst->size() == 2 && fst_node->is_token &&
!(fst_node->token->str_value.compare("struct"))) {
lst->insert((lst->begin() + 1), new Node("extern"));
char buf[255];
snprintf(buf, sizeof(buf), "__as%d", anon_struct_count++);
int error_count_begin =
ctx->er->getErrorTypeCount(ErrorType::Error);
FormStructParse(units, new Node(lst), buf);
int error_count_end =
ctx->er->getErrorTypeCount(ErrorType::Error);
if (error_count_begin != error_count_end) {
return NULL;
}
Type *type = FormTypeParse(units, new Node(buf), false, false);
assert(type && "unable to retrieve anonymous struct type");
return type;
}
/* If list is a three-element list, where the first element is
* 'bf', then this is a bitfield type. Only return such a type
* if allow_bitfields is enabled. */
if (allow_bitfields && lst->size() == 3 && fst_node->is_token &&
!(fst_node->token->str_value.compare("bf"))) {
Type *type = FormTypeParse(units, snd_node, false, false);
if (!type->isIntegerType()) {
Error *e = new Error(BitfieldMustHaveIntegerType, node);
ctx->er->addError(e);
return NULL;
}
int size = parseLiteralIntegerToInt((*lst)[2], ctx->er);
if (size == -1) {
return NULL;
}
return ctx->tr->getBitfieldType(type, size);
}
if (fst_node->is_token &&
!strcmp(fst_node->token->str_value.c_str(), "const")) {
if (lst->size() != 2) {
Error *e =
new Error(IncorrectNumberOfArgs, node, "const", "1",
(static_cast<int>(lst->size()) - 1));
ctx->er->addError(e);
return NULL;
}
Type *const_type = FormTypeParse(
units, snd_node, allow_anon_structs, allow_bitfields);
if (const_type == NULL) {
return NULL;
}
return ctx->tr->getConstType(const_type);
}
if (fst_node->is_token &&
!strcmp(fst_node->token->str_value.c_str(), "array-of")) {
if (lst->size() != 3) {
Error *e =
new Error(IncorrectNumberOfArgs, node, "array-of", "2",
(static_cast<int>(lst->size()) - 1));
ctx->er->addError(e);
return NULL;
}
Type *array_type = FormTypeParse(
units, (*lst)[2], allow_anon_structs, allow_bitfields);
if (array_type == NULL) {
return NULL;
}
llvm::Constant *size_value = NULL;
int unused_size;
size_value = FormValueParse(units, ctx->tr->type_int, snd_node,
&unused_size);
if (!size_value) {
return NULL;
}
llvm::ConstantInt *size_value_int =
llvm::dyn_cast<llvm::ConstantInt>(size_value);
if (!size_value_int) {
Error *e = new Error(
ErrorInst::UnableToParseIntegerNoString, snd_node);
ctx->er->addError(e);
return NULL;
}
int size = size_value_int->getZExtValue();
return ctx->tr->getArrayType(array_type, size);
}
if (fst_node->is_token &&
!strcmp(fst_node->token->str_value.c_str(), "p")) {
if (!ctx->er->assertArgNums("p", node, 1, 1)) {
return NULL;
}
Type *points_to_type = FormTypeParse(
units, snd_node, allow_anon_structs, allow_bitfields);
if (points_to_type == NULL) {
return NULL;
}
return ctx->tr->getPointerType(points_to_type);
}
if (fst_node->is_token &&
!strcmp(fst_node->token->str_value.c_str(), "fn")) {
if (!ctx->er->assertArgNums("fn", node, 2, 2)) {
return NULL;
}
Type *ret_type =
FormTypeParse(units, snd_node, allow_anon_structs,
allow_bitfields, false, true);
if (ret_type == NULL) {
return NULL;
}
if (ret_type->is_array) {
Error *e = new Error(ReturnTypesCannotBeArrays, node);
ctx->er->addError(e);
return NULL;
}
Node *params = (*lst)[2];
if (!params->is_list) {
Error *e = new Error(UnexpectedElement, node, "list",
"fn parameters", "symbol");
ctx->er->addError(e);
return NULL;
}
std::vector<Type *> parameter_types;
for (std::vector<Node *>::iterator b = params->list->begin(),
e = params->list->end();
b != e; ++b) {
Variable *var = new Variable();
var->type = NULL;
FormParameterParse(units, var, (*b), allow_anon_structs,
allow_bitfields, true, false);
if (var->type == NULL) {
delete var;
return NULL;
}
if (var->type->base_type == BaseType::Void) {
delete var;
if (params->list->size() != 1) {
Error *e =
new Error(VoidMustBeTheOnlyParameter, params);
ctx->er->addError(e);
return NULL;
}
break;
}
if (var->type->base_type == BaseType::VarArgs) {
if ((params->list->end() - b) != 1) {
delete var;
Error *e =
new Error(VarArgsMustBeLastParameter, params);
ctx->er->addError(e);
return NULL;
}
parameter_types.push_back(var->type);
break;
}
if (var->type->is_function) {
delete var;
Error *e = new Error(NonPointerFunctionParameter, (*b));
ctx->er->addError(e);
return NULL;
}
parameter_types.push_back(var->type);
}
Type *type = new Type();
type->is_function = true;
type->return_type = ret_type;
type->parameter_types = parameter_types;
return type;
}
Error *e = new Error(InvalidType, node);
ctx->er->addError(e);
return NULL;
}
}
| 32.293532 | 72 | 0.529348 | ChengCat |
603fb99857ecfdfec3e4fcaf4858fa5f9f8bfd4b | 624 | hpp | C++ | TGEngine/public/graphics/GUIModule.hpp | Troblecodings/TGEngine | 09c845f6ad68f99e51fdd7f9139e45475010f3d9 | [
"Apache-2.0"
] | 9 | 2018-03-22T16:01:54.000Z | 2022-01-12T02:27:10.000Z | TGEngine/public/graphics/GUIModule.hpp | Troblecodings/TGEngine | 09c845f6ad68f99e51fdd7f9139e45475010f3d9 | [
"Apache-2.0"
] | 20 | 2018-03-11T12:35:55.000Z | 2020-02-19T17:36:47.000Z | TGEngine/public/graphics/GUIModule.hpp | Troblecodings/TGEngine | 09c845f6ad68f99e51fdd7f9139e45475010f3d9 | [
"Apache-2.0"
] | 6 | 2019-02-26T13:59:55.000Z | 2021-07-15T14:11:10.000Z | #pragma once
#include "../Module.hpp"
#include "GameGraphicsModule.hpp"
#include "WindowModule.hpp"
namespace tge::gui {
class GUIModule : public tge::main::Module {
public:
tge::graphics::WindowModule *winModule;
tge::graphics::APILayer *api;
void *pool;
void *buffer;
void *renderpass;
void *framebuffer;
void (*guicallback)() = [] {};
GUIModule(tge::graphics::WindowModule *winModule,
tge::graphics::APILayer *api)
: winModule(winModule), api(api) {}
main::Error init() override;
void tick(double deltatime) override;
void destroy() override;
};
} // namespace tge::gui
| 18.352941 | 51 | 0.671474 | Troblecodings |
6041c522a9094b7342126553f6f21c0fa25cd960 | 312 | cc | C++ | src/main.cc | hedzr/hicc | c2a33afec2ff1f79c42ed9f888ad091710e7ae60 | [
"MIT"
] | null | null | null | src/main.cc | hedzr/hicc | c2a33afec2ff1f79c42ed9f888ad091710e7ae60 | [
"MIT"
] | null | null | null | src/main.cc | hedzr/hicc | c2a33afec2ff1f79c42ed9f888ad091710e7ae60 | [
"MIT"
] | null | null | null | #include <iostream>
#include "../include/core11.hh"
#include "hicc/hicc.hh"
void fatal_exit(const std::string &msg) {
std::cerr << msg << '\n';
exit(-1);
}
int main() {
std::string s1("a string", 2, 3);
std::cout << "Hello, World!" << s1 << '\n';
hicc_debug("ok");
return 0;
}
| 14.857143 | 47 | 0.535256 | hedzr |
6041ed1f1b6fe3caaefea953ec8b663423bc8c7c | 1,957 | cpp | C++ | LCS.cpp | shivamkrs89/DYNAMIC-PROGRAMMING | 7284918d61107ed9ac8092349b5289c69e628e2d | [
"MIT"
] | 2 | 2021-05-27T14:56:52.000Z | 2021-05-27T15:08:02.000Z | LCS.cpp | shivamkrs89/DYNAMIC-PROGRAMMING | 7284918d61107ed9ac8092349b5289c69e628e2d | [
"MIT"
] | null | null | null | LCS.cpp | shivamkrs89/DYNAMIC-PROGRAMMING | 7284918d61107ed9ac8092349b5289c69e628e2d | [
"MIT"
] | null | null | null | /*
Longest Common Subsequence
Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.
Example 1:
Input:
A = 6, B = 6
str1 = ABCDGH
str2 = AEDFHR
Output: 3
Explanation: LCS for input Sequences
“ABCDGH” and “AEDFHR” is “ADH” of
length 3.
Example 1:
Input:
A = 3, B = 2
str1 = ABC
str2 = AC
Output: 2
Explanation: LCS of "ABC" and "AC" is
"AC" of length 2.
Your Task:
Complete the function lcs() which takes the length of two strings respectively and two strings as input parameters and returns the length of the longest subsequence present in both of them.
Expected Time Complexity : O(|str1|*|str2|)
Expected Auxiliary Space: O(|str1|*|str2|)
Constraints:
1<=size(str1),size(str2)<=100
*/
//code goes here
#include<bits/stdc++.h>
const int mod=1e9+7;
using namespace std;
int lcs(int, int, string, string);
int main()
{
int t,n,k,x,y;
cin>>t;
while(t--)
{
cin>>x>>y; // Take size of both the strings as input
string s1,s2;
cin>>s1>>s2; // Take both the string as input
cout << lcs(x, y, s1, s2) << endl;
}
return 0;
}
// } Driver Code Ends
// function to find longest common subsequence
int lcsmat[1001][1001];
int clcs(int x, int y, string s1, string s2){
// your code here
if(x==0 || y==0)
return 0;
if(s1[x-1]==s2[y-1]){
if(lcsmat[x-1][y-1]==-1)
lcsmat[x-1][y-1]=clcs(x-1,y-1,s1,s2);
return 1+lcsmat[x-1][y-1];
}
else{
if(lcsmat[x][y-1]==-1)
lcsmat[x][y-1]=clcs(x,y-1,s1,s2);
if(lcsmat[x-1][y]==-1)
lcsmat[x-1][y]=clcs(x-1,y,s1,s2);
return max(lcsmat[x][y-1],lcsmat[x-1][y]);
}
}
int lcs(int x, int y, string s1, string s2){
// your code here
int i,j;
for(i=0;i<=x;i++)
{
for(j=0;j<=y;j++)
lcsmat[i][j]=-1;
}
return clcs(x,y,s1,s2);
}
| 19.767677 | 189 | 0.58048 | shivamkrs89 |
604275d1b48b029296295a54a33ff8cc3e3291e5 | 820 | hpp | C++ | sparta/simdb/include/simdb/schema/ColumnTypedefs.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/simdb/include/simdb/schema/ColumnTypedefs.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/simdb/include/simdb/schema/ColumnTypedefs.hpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | // <ColumnTypedefs> -*- C++ -*-
#ifndef __SIMDB_COLUMN_TYPEDEFS_H__
#define __SIMDB_COLUMN_TYPEDEFS_H__
#include <cstdint>
#include <cstddef>
#include <utility>
#include <string>
namespace simdb {
//! Data types supported by SimDB schemas
enum class ColumnDataType : int8_t {
int8_t,
uint8_t,
int16_t,
uint16_t,
int32_t,
uint32_t,
int64_t,
uint64_t,
float_t,
double_t,
char_t,
string_t,
blob_t,
fkey_t
};
//! From a table's perspective, each column can be uniquely
//! described by its column name and its data type.
using ColumnDescriptor = std::pair<std::string, ColumnDataType>;
//! Blob descriptor used for writing and reading raw bytes
//! to/from the database.
struct Blob {
const void * data_ptr = nullptr;
size_t num_bytes = 0;
};
}
#endif
| 18.222222 | 64 | 0.685366 | knute-sifive |
60483704b4c384f0503c5bdcdf909ec161334ca9 | 6,252 | cpp | C++ | resource/csdk/resource-directory/samples/rd_publishingClient.cpp | webispy/iotivity | 70154e7b27bbaa9feef0e625f9e0ee761d4de179 | [
"Apache-2.0"
] | 2 | 2019-10-02T08:36:35.000Z | 2020-11-27T05:42:34.000Z | iotivity/resource/csdk/resource-directory/samples/rd_publishingClient.cpp | 2nd-Chance/Fire-evacuation-guidance-system-IoT | 33031a8255fe1ae516ddd58f1baa808801cd3abf | [
"MIT"
] | 21 | 2019-10-02T08:31:36.000Z | 2021-12-09T21:46:49.000Z | resource/csdk/resource-directory/samples/rd_publishingClient.cpp | webispy/iotivity | 70154e7b27bbaa9feef0e625f9e0ee761d4de179 | [
"Apache-2.0"
] | 3 | 2020-05-11T07:06:42.000Z | 2020-11-27T05:42:37.000Z | //******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "iotivity_config.h"
#include <iostream>
#include <sstream>
#include <limits>
#include "oic_string.h"
#include "rd_client.h"
/// This example is using experimental API, so there is no guarantee of support for future release,
/// nor any there any guarantee that breaking changes will not occur across releases.
/// logging part is not critical but convenient for developer
#include "experimental/payload_logging.h"
#define TAG ("RD_PublishClient")
#define DEFAULT_CONTEXT_VALUE 0x99
OCResourceHandle handles[2];
std::ostringstream rdAddress;
OCStackResult registerLocalResources()
{
std::string resourceURI_thermostat = "/a/thermostat";
std::string resourceTypeName_thermostat = "core.thermostat";
std::string resourceURI_light = "/a/light";
std::string resourceTypeName_light = "core.light";
std::string resourceInterface = OC_RSRVD_INTERFACE_DEFAULT;
uint8_t resourceProperty = OC_DISCOVERABLE;
OCStackResult result = OCCreateResource(&handles[0],
resourceTypeName_thermostat.c_str(),
resourceInterface.c_str(),
resourceURI_thermostat.c_str(),
NULL,
NULL,
resourceProperty);
if (OC_STACK_OK != result)
{
return result;
}
result = OCCreateResource(&handles[1],
resourceTypeName_light.c_str(),
resourceInterface.c_str(),
resourceURI_light.c_str(),
NULL,
NULL,
resourceProperty);
return result;
}
void printHelp()
{
std::cout << std::endl;
std::cout << "********************************************" << std::endl;
std::cout << "* method Type : 1 - Discover RD *" << std::endl;
std::cout << "* method Type : 2 - Publish *" << std::endl;
std::cout << "* method Type : 3 - Update *" << std::endl;
std::cout << "* method Type : 4 - Delete *" << std::endl;
std::cout << "* method Type : 5 - Status *" << std::endl;
std::cout << "********************************************" << std::endl;
std::cout << std::endl;
}
static OCStackApplicationResult handleDiscoveryCB(__attribute__((unused))void *ctx,
__attribute__((unused)) OCDoHandle handle,
__attribute__((unused))
OCClientResponse *clientResponse)
{
OIC_LOG(DEBUG, TAG, "Successfully found RD.");
rdAddress << clientResponse->devAddr.addr << ":" << clientResponse->devAddr.port;
std::cout << "RD Address is : " << rdAddress.str() << std::endl;
return OC_STACK_DELETE_TRANSACTION;
}
static OCStackApplicationResult handlePublishCB(__attribute__((unused))void *ctx,
__attribute__((unused)) OCDoHandle handle,
__attribute__((unused))
OCClientResponse *clientResponse)
{
OIC_LOG(DEBUG, TAG, "Successfully published resources.");
return OC_STACK_DELETE_TRANSACTION;
}
int main()
{
std::cout << "Initializing IoTivity Platform" << std::endl;
OCStackResult result = OCInit(NULL, 0, OC_CLIENT_SERVER);
if (OC_STACK_OK != result)
{
std::cout << "OCInit Failed" << result << std::endl;
return -1;
}
std::cout << "Created Platform..." << std::endl;
result = registerLocalResources();
if (OC_STACK_OK != result)
{
std::cout << "Could not create the resource " << result << std::endl;
return -1;
}
while (1)
{
if (handles[0] == NULL || handles[1] == NULL)
{
continue;
}
printHelp();
int in = 0;
std::cin >> in;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input type, please try again" << std::endl;
continue;
}
switch ((int)in)
{
case 1:
{
OCCallbackData cbData;
cbData.cb = &handleDiscoveryCB;;
cbData.cd = NULL;
cbData.context = (void*) DEFAULT_CONTEXT_VALUE;
OCRDDiscover(nullptr, CT_ADAPTER_IP, &cbData, OC_LOW_QOS);
break;
}
case 2:
{
OCCallbackData cbData;
cbData.cb = &handlePublishCB;
cbData.cd = NULL;
cbData.context = (void*) DEFAULT_CONTEXT_VALUE;
std::string address = rdAddress.str();
OCRDPublish(nullptr, address.c_str(), CT_ADAPTER_IP, handles,
2, OIC_RD_PUBLISH_TTL, &cbData, OC_LOW_QOS);
break;
}
case 3:
break;
default:
std::cout << "Invalid input, please try again" << std::endl;
break;
}
}
return 0;
}
| 35.931034 | 99 | 0.511836 | webispy |
604bb7869e161d0ff0de2882a6eb1f8ea02779f6 | 26,591 | cpp | C++ | lib/Frontend/DiagnosticVerifier.cpp | francisvm/swift | 15e209ea2fde679ee78438d4ba949144acb7fee4 | [
"Apache-2.0"
] | 1 | 2018-01-11T07:08:30.000Z | 2018-01-11T07:08:30.000Z | lib/Frontend/DiagnosticVerifier.cpp | francisvm/swift | 15e209ea2fde679ee78438d4ba949144acb7fee4 | [
"Apache-2.0"
] | 153 | 2018-01-21T15:24:47.000Z | 2018-09-13T12:46:16.000Z | lib/Frontend/DiagnosticVerifier.cpp | francisvm/swift | 15e209ea2fde679ee78438d4ba949144acb7fee4 | [
"Apache-2.0"
] | 11 | 2017-12-13T08:08:15.000Z | 2019-06-18T14:27:32.000Z | //===--- DiagnosticVerifier.cpp - Diagnostic Verifier (-verify) -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the DiagnosticVerifier class.
//
//===----------------------------------------------------------------------===//
#include "swift/Frontend/DiagnosticVerifier.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Parse/Lexer.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>
using namespace swift;
namespace {
struct ExpectedFixIt {
const char *StartLoc, *EndLoc; // The loc of the {{ and }}'s.
unsigned StartCol;
unsigned EndCol;
std::string Text;
};
struct ExpectedDiagnosticInfo {
// This specifies the full range of the "expected-foo {{}}" specifier.
const char *ExpectedStart, *ExpectedEnd = nullptr;
llvm::SourceMgr::DiagKind Classification;
// This is true if a '*' constraint is present to say that the diagnostic
// may appear (or not) an uncounted number of times.
bool mayAppear = false;
// This is true if a '{{none}}' is present to mark that there should be no
// extra fixits.
bool noExtraFixitsMayAppear = false;
// This is the raw input buffer for the message text, the part in the
// {{...}}
StringRef MessageRange;
// This is the message string with escapes expanded.
std::string MessageStr;
unsigned LineNo = ~0U;
std::vector<ExpectedFixIt> Fixits;
ExpectedDiagnosticInfo(const char *ExpectedStart,
llvm::SourceMgr::DiagKind Classification)
: ExpectedStart(ExpectedStart), Classification(Classification) {
}
};
} // end anonymous namespace
static std::string getDiagKindString(llvm::SourceMgr::DiagKind Kind) {
switch (Kind) {
case llvm::SourceMgr::DK_Error: return "error";
case llvm::SourceMgr::DK_Warning: return "warning";
case llvm::SourceMgr::DK_Note: return "note";
case llvm::SourceMgr::DK_Remark: return "remark";
}
llvm_unreachable("Unhandled DiagKind in switch.");
}
namespace {
/// This class implements support for -verify mode in the compiler. It
/// buffers up diagnostics produced during compilation, then checks them
/// against expected-error markers in the source file.
class DiagnosticVerifier {
SourceManager &SM;
std::vector<llvm::SMDiagnostic> CapturedDiagnostics;
public:
explicit DiagnosticVerifier(SourceManager &SM) : SM(SM) {}
void addDiagnostic(const llvm::SMDiagnostic &Diag) {
CapturedDiagnostics.push_back(Diag);
}
/// verifyFile - After the file has been processed, check to see if we
/// got all of the expected diagnostics and check to see if there were any
/// unexpected ones.
bool verifyFile(unsigned BufferID, bool autoApplyFixes);
/// diagnostics for '<unknown>:0' should be considered as unexpected.
bool verifyUnknown();
/// If there are any -verify errors (e.g. differences between expectations
/// and actual diagnostics produced), apply fixits to the original source
/// file and drop it back in place.
void autoApplyFixes(unsigned BufferID,
ArrayRef<llvm::SMDiagnostic> diagnostics);
private:
std::vector<llvm::SMDiagnostic>::iterator
findDiagnostic(const ExpectedDiagnosticInfo &Expected,
StringRef BufferName);
};
} // end anonymous namespace
/// If we find the specified diagnostic in the list, return it.
/// Otherwise return CapturedDiagnostics.end().
std::vector<llvm::SMDiagnostic>::iterator
DiagnosticVerifier::findDiagnostic(const ExpectedDiagnosticInfo &Expected,
StringRef BufferName) {
for (auto I = CapturedDiagnostics.begin(), E = CapturedDiagnostics.end();
I != E; ++I) {
// Verify the file and line of the diagnostic.
if (I->getLineNo() != (int)Expected.LineNo ||
I->getFilename() != BufferName)
continue;
// Verify the classification and string.
if (I->getKind() != Expected.Classification ||
I->getMessage().find(Expected.MessageStr) == StringRef::npos)
continue;
// Okay, we found a match, hurray!
return I;
}
return CapturedDiagnostics.end();
}
static unsigned getColumnNumber(StringRef buffer, llvm::SMLoc loc) {
assert(loc.getPointer() >= buffer.data());
assert((size_t)(loc.getPointer() - buffer.data()) <= buffer.size());
StringRef UpToLoc = buffer.slice(0, loc.getPointer() - buffer.data());
size_t ColumnNo = UpToLoc.size();
size_t NewlinePos = UpToLoc.find_last_of("\r\n");
if (NewlinePos != StringRef::npos)
ColumnNo -= NewlinePos;
return static_cast<unsigned>(ColumnNo);
}
/// Return true if the given \p ExpectedFixIt is in the fix-its emitted by
/// diagnostic \p D.
static bool checkForFixIt(const ExpectedFixIt &Expected,
const llvm::SMDiagnostic &D,
StringRef buffer) {
for (auto &ActualFixIt : D.getFixIts()) {
if (ActualFixIt.getText() != Expected.Text)
continue;
llvm::SMRange Range = ActualFixIt.getRange();
if (getColumnNumber(buffer, Range.Start) != Expected.StartCol)
continue;
if (getColumnNumber(buffer, Range.End) != Expected.EndCol)
continue;
return true;
}
return false;
}
static std::string renderFixits(ArrayRef<llvm::SMFixIt> fixits,
StringRef InputFile) {
std::string Result;
llvm::raw_string_ostream OS(Result);
interleave(fixits,
[&](const llvm::SMFixIt &ActualFixIt) {
llvm::SMRange Range = ActualFixIt.getRange();
OS << "{{" << getColumnNumber(InputFile, Range.Start) << '-'
<< getColumnNumber(InputFile, Range.End) << '=';
for (auto C : ActualFixIt.getText()) {
if (C == '\n')
OS << "\\n";
else if (C == '}' || C == '\\')
OS << '\\' << C;
else
OS << C;
}
OS << "}}";
},
[&] { OS << ' '; });
return OS.str();
}
/// \brief After the file has been processed, check to see if we got all of
/// the expected diagnostics and check to see if there were any unexpected
/// ones.
bool DiagnosticVerifier::verifyFile(unsigned BufferID,
bool shouldAutoApplyFixes) {
using llvm::SMLoc;
const SourceLoc BufferStartLoc = SM.getLocForBufferStart(BufferID);
CharSourceRange EntireRange = SM.getRangeForBuffer(BufferID);
StringRef InputFile = SM.extractText(EntireRange);
StringRef BufferName = SM.getIdentifierForBuffer(BufferID);
// Queue up all of the diagnostics, allowing us to sort them and emit them in
// file order.
std::vector<llvm::SMDiagnostic> Errors;
unsigned PrevExpectedContinuationLine = 0;
std::vector<ExpectedDiagnosticInfo> ExpectedDiagnostics;
auto addError = [&](const char *Loc, std::string message,
ArrayRef<llvm::SMFixIt> FixIts = {}) {
auto loc = SourceLoc(SMLoc::getFromPointer(Loc));
auto diag = SM.GetMessage(loc, llvm::SourceMgr::DK_Error, message,
{}, FixIts);
Errors.push_back(diag);
};
// Scan the memory buffer looking for expected-note/warning/error.
for (size_t Match = InputFile.find("expected-");
Match != StringRef::npos; Match = InputFile.find("expected-", Match+1)) {
// Process this potential match. If we fail to process it, just move on to
// the next match.
StringRef MatchStart = InputFile.substr(Match);
const char *DiagnosticLoc = MatchStart.data();
llvm::SourceMgr::DiagKind ExpectedClassification;
if (MatchStart.startswith("expected-note")) {
ExpectedClassification = llvm::SourceMgr::DK_Note;
MatchStart = MatchStart.substr(strlen("expected-note"));
} else if (MatchStart.startswith("expected-warning")) {
ExpectedClassification = llvm::SourceMgr::DK_Warning;
MatchStart = MatchStart.substr(strlen("expected-warning"));
} else if (MatchStart.startswith("expected-error")) {
ExpectedClassification = llvm::SourceMgr::DK_Error;
MatchStart = MatchStart.substr(strlen("expected-error"));
} else
continue;
// Skip any whitespace before the {{.
MatchStart = MatchStart.substr(MatchStart.find_first_not_of(" \t"));
size_t TextStartIdx = MatchStart.find("{{");
if (TextStartIdx == StringRef::npos) {
addError(MatchStart.data(),
"expected {{ in expected-warning/note/error line");
continue;
}
int LineOffset = 0;
if (TextStartIdx > 0 && MatchStart[0] == '@') {
if (MatchStart[1] != '+' && MatchStart[1] != '-') {
addError(MatchStart.data(), "expected '+'/'-' for line offset");
continue;
}
StringRef Offs;
if (MatchStart[1] == '+')
Offs = MatchStart.slice(2, TextStartIdx).rtrim();
else
Offs = MatchStart.slice(1, TextStartIdx).rtrim();
size_t SpaceIndex = Offs.find(' ');
if (SpaceIndex != StringRef::npos && SpaceIndex < TextStartIdx) {
size_t Delta = Offs.size() - SpaceIndex;
MatchStart = MatchStart.substr(TextStartIdx - Delta);
TextStartIdx = Delta;
Offs = Offs.slice(0, SpaceIndex);
} else {
MatchStart = MatchStart.substr(TextStartIdx);
TextStartIdx = 0;
}
if (Offs.getAsInteger(10, LineOffset)) {
addError(MatchStart.data(), "expected line offset before '{{'");
continue;
}
}
ExpectedDiagnosticInfo Expected(DiagnosticLoc, ExpectedClassification);
unsigned Count = 1;
if (TextStartIdx > 0) {
StringRef CountStr = MatchStart.substr(0, TextStartIdx).trim();
if (CountStr == "*") {
Expected.mayAppear = true;
} else {
if (CountStr.getAsInteger(10, Count)) {
addError(MatchStart.data(), "expected match count before '{{'");
continue;
}
if (Count == 0) {
addError(MatchStart.data(),
"expected positive match count before '{{'");
continue;
}
}
// Resync up to the '{{'.
MatchStart = MatchStart.substr(TextStartIdx);
}
size_t End = MatchStart.find("}}");
if (End == StringRef::npos) {
addError(MatchStart.data(),
"didn't find '}}' to match '{{' in expected-warning/note/error line");
continue;
}
llvm::SmallString<256> Buf;
Expected.MessageRange = MatchStart.slice(2, End);
Expected.MessageStr =
Lexer::getEncodedStringSegment(Expected.MessageRange, Buf);
if (PrevExpectedContinuationLine)
Expected.LineNo = PrevExpectedContinuationLine;
else
Expected.LineNo = SM.getLineAndColumn(
BufferStartLoc.getAdvancedLoc(MatchStart.data() - InputFile.data()),
BufferID).first;
Expected.LineNo += LineOffset;
// Check if the next expected diagnostic should be in the same line.
StringRef AfterEnd = MatchStart.substr(End + strlen("}}"));
AfterEnd = AfterEnd.substr(AfterEnd.find_first_not_of(" \t"));
if (AfterEnd.startswith("\\"))
PrevExpectedContinuationLine = Expected.LineNo;
else
PrevExpectedContinuationLine = 0;
// Scan for fix-its: {{10-14=replacement text}}
StringRef ExtraChecks = MatchStart.substr(End+2).ltrim(" \t");
while (ExtraChecks.startswith("{{")) {
// First make sure we have a closing "}}".
size_t EndLoc = ExtraChecks.find("}}");
if (EndLoc == StringRef::npos) {
addError(ExtraChecks.data(),
"didn't find '}}' to match '{{' in fix-it verification");
break;
}
// Allow for close braces to appear in the replacement text.
while (EndLoc+2 < ExtraChecks.size() && ExtraChecks[EndLoc+2] == '}')
++EndLoc;
StringRef FixItStr = ExtraChecks.slice(2, EndLoc);
// Check for matching a later "}}" on a different line.
if (FixItStr.find_first_of("\r\n") != StringRef::npos) {
addError(ExtraChecks.data(), "didn't find '}}' to match '{{' in "
"fix-it verification");
break;
}
// Prepare for the next round of checks.
ExtraChecks = ExtraChecks.substr(EndLoc+2).ltrim();
// Special case for specifying no fixits should appear.
if (FixItStr == "none") {
Expected.noExtraFixitsMayAppear = true;
continue;
}
// Parse the pieces of the fix-it.
size_t MinusLoc = FixItStr.find('-');
if (MinusLoc == StringRef::npos) {
addError(FixItStr.data(), "expected '-' in fix-it verification");
continue;
}
StringRef StartColStr = FixItStr.slice(0, MinusLoc);
StringRef AfterMinus = FixItStr.substr(MinusLoc+1);
size_t EqualLoc = AfterMinus.find('=');
if (EqualLoc == StringRef::npos) {
addError(AfterMinus.data(),
"expected '=' after '-' in fix-it verification");
continue;
}
StringRef EndColStr = AfterMinus.slice(0, EqualLoc);
StringRef AfterEqual = AfterMinus.substr(EqualLoc+1);
ExpectedFixIt FixIt;
FixIt.StartLoc = StartColStr.data()-2;
FixIt.EndLoc = FixItStr.data()+EndLoc;
if (StartColStr.getAsInteger(10, FixIt.StartCol)) {
addError(StartColStr.data(),
"invalid column number in fix-it verification");
continue;
}
if (EndColStr.getAsInteger(10, FixIt.EndCol)) {
addError(EndColStr.data(),
"invalid column number in fix-it verification");
continue;
}
// Translate literal "\\n" into '\n', inefficiently.
StringRef fixItText = AfterEqual.slice(0, EndLoc);
for (const char *current = fixItText.begin(), *end = fixItText.end();
current != end; /* in loop */) {
if (*current == '\\' && current + 1 < end) {
if (current[1] == 'n') {
FixIt.Text += '\n';
current += 2;
} else { // Handle \}, \\, etc.
FixIt.Text += current[1];
current += 2;
}
} else {
FixIt.Text += *current++;
}
}
Expected.Fixits.push_back(FixIt);
}
Expected.ExpectedEnd = ExtraChecks.data();
// Don't include trailing whitespace in the expected-foo{{}} range.
while (isspace(Expected.ExpectedEnd[-1]))
--Expected.ExpectedEnd;
// Add the diagnostic the expected number of times.
for (; Count; --Count)
ExpectedDiagnostics.push_back(Expected);
}
// Make sure all the expected diagnostics appeared.
std::reverse(ExpectedDiagnostics.begin(), ExpectedDiagnostics.end());
for (unsigned i = ExpectedDiagnostics.size(); i != 0; ) {
--i;
auto &expected = ExpectedDiagnostics[i];
// Check to see if we had this expected diagnostic.
auto FoundDiagnosticIter = findDiagnostic(expected, BufferName);
if (FoundDiagnosticIter == CapturedDiagnostics.end()) {
// Diagnostic didn't exist. If this is a 'mayAppear' diagnostic, then
// we're ok. Otherwise, leave it in the list.
if (expected.mayAppear)
ExpectedDiagnostics.erase(ExpectedDiagnostics.begin()+i);
continue;
}
auto &FoundDiagnostic = *FoundDiagnosticIter;
const char *IncorrectFixit = nullptr;
// Verify that any expected fix-its are present in the diagnostic.
for (auto fixit : expected.Fixits) {
// If we found it, we're ok.
if (!checkForFixIt(fixit, FoundDiagnostic, InputFile))
IncorrectFixit = fixit.StartLoc;
}
bool matchedAllFixIts =
expected.Fixits.size() == FoundDiagnostic.getFixIts().size();
// If we have any expected fixits that didn't get matched, then they are
// wrong. Replace the failed fixit with what actually happened.
if (IncorrectFixit) {
if (FoundDiagnostic.getFixIts().empty()) {
addError(IncorrectFixit, "expected fix-it not seen");
} else {
// If we had an incorrect expected fixit, render it and produce a fixit
// of our own.
auto actual = renderFixits(FoundDiagnostic.getFixIts(), InputFile);
auto replStartLoc = SMLoc::getFromPointer(expected.Fixits[0].StartLoc);
auto replEndLoc = SMLoc::getFromPointer(expected.Fixits.back().EndLoc);
llvm::SMFixIt fix(llvm::SMRange(replStartLoc, replEndLoc), actual);
addError(IncorrectFixit,
"expected fix-it not seen; actual fix-its: " + actual, fix);
}
} else if (expected.noExtraFixitsMayAppear &&
!matchedAllFixIts &&
!expected.mayAppear) {
// If there was no fixit specification, but some were produced, add a
// fixit to add them in.
auto actual = renderFixits(FoundDiagnostic.getFixIts(), InputFile);
auto replStartLoc = SMLoc::getFromPointer(expected.ExpectedEnd - 8); // {{none}} length
auto replEndLoc = SMLoc::getFromPointer(expected.ExpectedEnd - 1);
llvm::SMFixIt fix(llvm::SMRange(replStartLoc, replEndLoc), actual);
addError(replStartLoc.getPointer(), "expected no fix-its; actual fix-it seen: " + actual, fix);
}
// Actually remove the diagnostic from the list, so we don't match it
// again. We do have to do this after checking fix-its, though, because
// the diagnostic owns its fix-its.
CapturedDiagnostics.erase(FoundDiagnosticIter);
// We found the diagnostic, so remove it... unless we allow an arbitrary
// number of diagnostics, in which case we want to reprocess this.
if (expected.mayAppear)
++i;
else
ExpectedDiagnostics.erase(ExpectedDiagnostics.begin()+i);
}
// Check to see if we have any incorrect diagnostics. If so, diagnose them as
// such.
for (unsigned i = ExpectedDiagnostics.size(); i != 0; ) {
--i;
auto &expected = ExpectedDiagnostics[i];
// Check to see if any found diagnostics have the right line and
// classification, but the wrong text.
auto I = CapturedDiagnostics.begin();
for (auto E = CapturedDiagnostics.end(); I != E; ++I) {
// Verify the file and line of the diagnostic.
if (I->getLineNo() != (int)expected.LineNo ||
I->getFilename() != BufferName ||
I->getKind() != expected.Classification)
continue;
// Otherwise, we found it, break out.
break;
}
if (I == CapturedDiagnostics.end()) continue;
auto StartLoc = SMLoc::getFromPointer(expected.MessageRange.begin());
auto EndLoc = SMLoc::getFromPointer(expected.MessageRange.end());
llvm::SMFixIt fixIt(llvm::SMRange{ StartLoc, EndLoc }, I->getMessage());
addError(expected.MessageRange.begin(), "incorrect message found", fixIt);
CapturedDiagnostics.erase(I);
ExpectedDiagnostics.erase(ExpectedDiagnostics.begin()+i);
}
// Diagnose expected diagnostics that didn't appear.
std::reverse(ExpectedDiagnostics.begin(), ExpectedDiagnostics.end());
for (auto const &expected : ExpectedDiagnostics) {
std::string message = "expected "+getDiagKindString(expected.Classification)
+ " not produced";
// Get the range of the expected-foo{{}} diagnostic specifier.
auto StartLoc = expected.ExpectedStart;
auto EndLoc = expected.ExpectedEnd;
// A very common case if for the specifier to be the last thing on the line.
// In this case, eat any trailing whitespace.
while (isspace(*EndLoc) && *EndLoc != '\n' && *EndLoc != '\r')
++EndLoc;
// If we found the end of the line, we can do great things. Otherwise,
// avoid nuking whitespace that might be zapped through other means.
if (*EndLoc != '\n' && *EndLoc != '\r') {
EndLoc = expected.ExpectedEnd;
} else {
// If we hit the end of line, then zap whitespace leading up to it.
auto FileStart = InputFile.data();
while (StartLoc-1 != FileStart && isspace(StartLoc[-1]) &&
StartLoc[-1] != '\n' && StartLoc[-1] != '\r')
--StartLoc;
// If we got to the end of the line, and the thing before this diagnostic
// is a "//" then we can remove it too.
if (StartLoc-2 >= FileStart && StartLoc[-1] == '/' && StartLoc[-2] == '/')
StartLoc -= 2;
// Perform another round of general whitespace nuking to cleanup
// whitespace before the //.
while (StartLoc-1 != FileStart && isspace(StartLoc[-1]) &&
StartLoc[-1] != '\n' && StartLoc[-1] != '\r')
--StartLoc;
// If we found a \n, then we can nuke the entire line.
if (StartLoc-1 != FileStart &&
(StartLoc[-1] == '\n' || StartLoc[-1] == '\r'))
--StartLoc;
}
// Remove the expected-foo{{}} as a fixit.
llvm::SMFixIt fixIt(llvm::SMRange{
SMLoc::getFromPointer(StartLoc),
SMLoc::getFromPointer(EndLoc)
}, "");
addError(expected.ExpectedStart, message, fixIt);
}
// Verify that there are no diagnostics (in MemoryBuffer) left in the list.
for (unsigned i = 0, e = CapturedDiagnostics.size(); i != e; ++i) {
if (CapturedDiagnostics[i].getFilename() != BufferName)
continue;
std::string Message =
"unexpected "+getDiagKindString(CapturedDiagnostics[i].getKind())+
" produced: "+CapturedDiagnostics[i].getMessage().str();
addError(CapturedDiagnostics[i].getLoc().getPointer(),
Message);
}
// Sort the diagnostics by their address in the memory buffer as the primary
// key. This ensures that an "unexpected diagnostic" and
// "expected diagnostic" in the same place are emitted next to each other.
std::sort(Errors.begin(), Errors.end(),
[&](const llvm::SMDiagnostic &lhs,
const llvm::SMDiagnostic &rhs) -> bool {
return lhs.getLoc().getPointer() < rhs.getLoc().getPointer();
});
// Emit all of the queue'd up errors.
for (auto Err : Errors)
SM.getLLVMSourceMgr().PrintMessage(llvm::errs(), Err);
// If auto-apply fixits is on, rewrite the original source file.
if (shouldAutoApplyFixes)
autoApplyFixes(BufferID, Errors);
return !Errors.empty();
}
bool DiagnosticVerifier::verifyUnknown() {
bool HadError = false;
for (unsigned i = 0, e = CapturedDiagnostics.size(); i != e; ++i) {
if (CapturedDiagnostics[i].getFilename() != "<unknown>")
continue;
HadError = true;
std::string Message =
"unexpected "+getDiagKindString(CapturedDiagnostics[i].getKind())+
" produced: "+CapturedDiagnostics[i].getMessage().str();
auto diag = SM.GetMessage({}, llvm::SourceMgr::DK_Error, Message,
{}, {});
SM.getLLVMSourceMgr().PrintMessage(llvm::errs(), diag);
}
return HadError;
}
/// If there are any -verify errors (e.g. differences between expectations
/// and actual diagnostics produced), apply fixits to the original source
/// file and drop it back in place.
void DiagnosticVerifier::autoApplyFixes(unsigned BufferID,
ArrayRef<llvm::SMDiagnostic> diags) {
// Walk the list of diagnostics, pulling out any fixits into an array of just
// them.
SmallVector<llvm::SMFixIt, 4> FixIts;
for (auto &diag : diags)
FixIts.append(diag.getFixIts().begin(), diag.getFixIts().end());
// If we have no fixits to apply, avoid touching the file.
if (FixIts.empty())
return;
// Sort the fixits by their start location.
std::sort(FixIts.begin(), FixIts.end(),
[&](const llvm::SMFixIt &lhs, const llvm::SMFixIt &rhs) -> bool {
return lhs.getRange().Start.getPointer()
< rhs.getRange().Start.getPointer();
});
// Get the contents of the original source file.
auto memBuffer = SM.getLLVMSourceMgr().getMemoryBuffer(BufferID);
auto bufferRange = memBuffer->getBuffer();
// Apply the fixes, building up a new buffer as an std::string.
const char *LastPos = bufferRange.begin();
std::string Result;
for (auto &fix : FixIts) {
// We cannot handle overlapping fixits, so assert that they don't happen.
assert(LastPos <= fix.getRange().Start.getPointer() &&
"Cannot handle overlapping fixits");
// Keep anything from the last spot we've checked to the start of the fixit.
Result.append(LastPos, fix.getRange().Start.getPointer());
// Replace the content covered by the fixit with the replacement text.
Result.append(fix.getText().begin(), fix.getText().end());
// Next character to consider is at the end of the fixit.
LastPos = fix.getRange().End.getPointer();
}
// Retain the end of the file.
Result.append(LastPos, bufferRange.end());
std::ofstream outs(memBuffer->getBufferIdentifier());
outs << Result;
}
//===----------------------------------------------------------------------===//
// Main entrypoints
//===----------------------------------------------------------------------===//
/// Every time a diagnostic is generated in -verify mode, this function is
/// called with the diagnostic. We just buffer them up until the end of the
/// file.
static void VerifyModeDiagnosticHook(const llvm::SMDiagnostic &Diag,
void *Context) {
((DiagnosticVerifier*)Context)->addDiagnostic(Diag);
}
void swift::enableDiagnosticVerifier(SourceManager &SM) {
SM.getLLVMSourceMgr().setDiagHandler(VerifyModeDiagnosticHook,
new DiagnosticVerifier(SM));
}
bool swift::verifyDiagnostics(SourceManager &SM, ArrayRef<unsigned> BufferIDs,
bool autoApplyFixes, bool ignoreUnknown) {
auto *Verifier = (DiagnosticVerifier*)SM.getLLVMSourceMgr().getDiagContext();
SM.getLLVMSourceMgr().setDiagHandler(nullptr, nullptr);
bool HadError = false;
for (auto &BufferID : BufferIDs)
HadError |= Verifier->verifyFile(BufferID, autoApplyFixes);
if (!ignoreUnknown)
HadError |= Verifier->verifyUnknown();
delete Verifier;
return HadError;
}
| 36.376197 | 101 | 0.625249 | francisvm |
604c0eb6edeb729ec1aec746438c2d4254fb2f75 | 1,357 | cpp | C++ | Motor2D/j1Label.cpp | knela96/Dev_class5_handout | ca137c8e696069bf1bb5709c97ceae79f280942b | [
"MIT"
] | null | null | null | Motor2D/j1Label.cpp | knela96/Dev_class5_handout | ca137c8e696069bf1bb5709c97ceae79f280942b | [
"MIT"
] | null | null | null | Motor2D/j1Label.cpp | knela96/Dev_class5_handout | ca137c8e696069bf1bb5709c97ceae79f280942b | [
"MIT"
] | null | null | null | #include "j1App.h"
#include "j1Render.h"
#include "j1Label.h"
#include "j1Fonts.h"
#include "p2Log.h"
#include "j1Textures.h"
#include "j1Textures.h"
#include "Brofiler\Brofiler.h"
j1Label::j1Label(fPoint position, p2SString text, int scale, int move, SDL_Texture* graphics, j1ElementGUI* parent, ElementUIType type) :
text(text),
move(move),
scale(scale),
j1ElementGUI(position, nullptr, type,graphics,parent)
{
App->font->CalcSize(text.GetString(), width, height);
this->graphics = App->font->Print(text.GetString());
global_pos = getParentPos(this);
rect = new SDL_Rect({ (int)global_pos.x * scale, (int)global_pos.y* scale,width* scale,height* scale });
}
j1Label::~j1Label()
{}
bool j1Label::CleanUp() {
//LOG("Cleaning Label");
App->tex->UnLoad(graphics);
graphics = nullptr;
delete rect;
rect = nullptr;
parent = nullptr;
return true;
}
void j1Label::Draw()
{
global_pos = getParentPos(this);
if (move) {
rect->x = global_pos.x * scale - App->render->camera.x;
rect->y = global_pos.y * scale - App->render->camera.y;
}
else {
rect->x = global_pos.x * scale;
rect->y = global_pos.y * scale;
}
App->render->Blit(graphics, global_pos.x, global_pos.y, nullptr, SDL_FLIP_NONE, scale, (float)move);
}
void j1Label::UpdateText() {
App->tex->UnLoad(graphics);
this->graphics = App->font->Print(text.GetString());
}
| 23 | 137 | 0.691231 | knela96 |
604e5c64e3641aa56163857d835936926f9f773c | 12,626 | hpp | C++ | external/armadillo-10.1.2/tmp/include/armadillo_bits/op_logmat_meat.hpp | hb407/libnome | cf11c6e34e6d147e28bfc6f54dd3ca81d2443438 | [
"MIT"
] | 55 | 2020-10-07T20:22:22.000Z | 2021-08-28T10:58:36.000Z | external/armadillo-10.1.2/tmp/include/armadillo_bits/op_logmat_meat.hpp | hb407/libnome | cf11c6e34e6d147e28bfc6f54dd3ca81d2443438 | [
"MIT"
] | 16 | 2020-12-06T22:02:38.000Z | 2021-08-19T09:37:56.000Z | external/armadillo-10.1.2/tmp/include/armadillo_bits/op_logmat_meat.hpp | hb407/libnome | cf11c6e34e6d147e28bfc6f54dd3ca81d2443438 | [
"MIT"
] | 11 | 2019-12-16T16:06:19.000Z | 2020-04-15T15:28:31.000Z | // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// 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.
// ------------------------------------------------------------------------
//! \addtogroup op_logmat
//! @{
// Partly based on algorithm 11.9 (inverse scaling and squaring algorithm with Schur decomposition) in:
// Nicholas J. Higham.
// Functions of Matrices: Theory and Computation.
// SIAM, 2008.
// ISBN 978-0-89871-646-7
template<typename T1>
inline
void
op_logmat::apply(Mat< std::complex<typename T1::elem_type> >& out, const mtOp<std::complex<typename T1::elem_type>,T1,op_logmat>& in)
{
arma_extra_debug_sigprint();
const bool status = op_logmat::apply_direct(out, in.m, in.aux_uword_a);
if(status == false)
{
out.soft_reset();
arma_stop_runtime_error("logmat(): transformation failed");
}
}
template<typename T1>
inline
bool
op_logmat::apply_direct(Mat< std::complex<typename T1::elem_type> >& out, const Op<T1,op_diagmat>& expr, const uword)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type T;
const diagmat_proxy<T1> P(expr.m);
arma_debug_check( (P.n_rows != P.n_cols), "logmat(): given matrix must be square sized" );
const uword N = P.n_rows;
out.zeros(N,N); // aliasing can't happen as op_logmat is defined as cx_mat = op(mat)
for(uword i=0; i<N; ++i)
{
const T val = P[i];
if(val >= T(0))
{
out.at(i,i) = std::log(val);
}
else
{
out.at(i,i) = std::log( std::complex<T>(val) );
}
}
return true;
}
template<typename T1>
inline
bool
op_logmat::apply_direct(Mat< std::complex<typename T1::elem_type> >& out, const Base<typename T1::elem_type,T1>& expr, const uword n_iters)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type in_T;
typedef typename std::complex<in_T> out_T;
const quasi_unwrap<T1> expr_unwrap(expr.get_ref());
const Mat<in_T>& A = expr_unwrap.M;
arma_debug_check( (A.is_square() == false), "logmat(): given matrix must be square sized" );
if(A.n_elem == 0)
{
out.reset();
return true;
}
else
if(A.n_elem == 1)
{
out.set_size(1,1);
out[0] = std::log( std::complex<in_T>( A[0] ) );
return true;
}
if(A.is_diagmat())
{
const uword N = A.n_rows;
out.zeros(N,N); // aliasing can't happen as op_logmat is defined as cx_mat = op(mat)
for(uword i=0; i<N; ++i)
{
const in_T val = A.at(i,i);
if(val >= in_T(0))
{
out.at(i,i) = std::log(val);
}
else
{
out.at(i,i) = std::log( out_T(val) );
}
}
return true;
}
#if defined(ARMA_OPTIMISE_SYMPD)
const bool try_sympd = sympd_helper::guess_sympd_anysize(A);
#else
const bool try_sympd = false;
#endif
if(try_sympd)
{
// if matrix A is sympd, all its eigenvalues are positive
Col<in_T> eigval;
Mat<in_T> eigvec;
const bool eig_status = eig_sym_helper(eigval, eigvec, A, 'd', "logmat()");
if(eig_status)
{
// ensure each eigenvalue is > 0
const uword N = eigval.n_elem;
const in_T* eigval_mem = eigval.memptr();
bool all_pos = true;
for(uword i=0; i<N; ++i) { all_pos = (eigval_mem[i] <= in_T(0)) ? false : all_pos; }
if(all_pos)
{
eigval = log(eigval);
out = conv_to< Mat<out_T> >::from( eigvec * diagmat(eigval) * eigvec.t() );
return true;
}
}
arma_extra_debug_print("warning: sympd optimisation failed");
// fallthrough if eigen decomposition failed or an eigenvalue is zero
}
Mat<out_T> S(A.n_rows, A.n_cols);
const in_T* Amem = A.memptr();
out_T* Smem = S.memptr();
const uword n_elem = A.n_elem;
for(uword i=0; i<n_elem; ++i)
{
Smem[i] = std::complex<in_T>( Amem[i] );
}
return op_logmat_cx::apply_common(out, S, n_iters);
}
template<typename T1>
inline
void
op_logmat_cx::apply(Mat<typename T1::elem_type>& out, const Op<T1,op_logmat_cx>& in)
{
arma_extra_debug_sigprint();
const bool status = op_logmat_cx::apply_direct(out, in.m, in.aux_uword_a);
if(status == false)
{
out.soft_reset();
arma_stop_runtime_error("logmat(): transformation failed");
}
}
template<typename T1>
inline
bool
op_logmat_cx::apply_direct(Mat<typename T1::elem_type>& out, const Op<T1,op_diagmat>& expr, const uword)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type eT;
const diagmat_proxy<T1> P(expr.m);
bool status = false;
if(P.is_alias(out))
{
Mat<eT> tmp;
status = op_logmat_cx::apply_direct_noalias(tmp, P);
out.steal_mem(tmp);
}
else
{
status = op_logmat_cx::apply_direct_noalias(out, P);
}
return status;
}
template<typename T1>
inline
bool
op_logmat_cx::apply_direct_noalias(Mat<typename T1::elem_type>& out, const diagmat_proxy<T1>& P)
{
arma_extra_debug_sigprint();
arma_debug_check( (P.n_rows != P.n_cols), "logmat(): given matrix must be square sized" );
const uword N = P.n_rows;
out.zeros(N,N);
for(uword i=0; i<N; ++i)
{
out.at(i,i) = std::log(P[i]);
}
return true;
}
template<typename T1>
inline
bool
op_logmat_cx::apply_direct(Mat<typename T1::elem_type>& out, const Base<typename T1::elem_type,T1>& expr, const uword n_iters)
{
arma_extra_debug_sigprint();
typedef typename T1::pod_type T;
typedef typename T1::elem_type eT;
Mat<eT> S = expr.get_ref();
arma_debug_check( (S.n_rows != S.n_cols), "logmat(): given matrix must be square sized" );
if(S.n_elem == 0)
{
out.reset();
return true;
}
else
if(S.n_elem == 1)
{
out.set_size(1,1);
out[0] = std::log(S[0]);
return true;
}
if(S.is_diagmat())
{
const uword N = S.n_rows;
out.zeros(N,N); // aliasing can't happen as S is generated
for(uword i=0; i<N; ++i) { out.at(i,i) = std::log( S.at(i,i) ); }
return true;
}
#if defined(ARMA_OPTIMISE_SYMPD)
const bool try_sympd = sympd_helper::guess_sympd_anysize(S);
#else
const bool try_sympd = false;
#endif
if(try_sympd)
{
// if matrix S is sympd, all its eigenvalues are positive
Col< T> eigval;
Mat<eT> eigvec;
const bool eig_status = eig_sym_helper(eigval, eigvec, S, 'd', "logmat()");
if(eig_status)
{
// ensure each eigenvalue is > 0
const uword N = eigval.n_elem;
const T* eigval_mem = eigval.memptr();
bool all_pos = true;
for(uword i=0; i<N; ++i) { all_pos = (eigval_mem[i] <= T(0)) ? false : all_pos; }
if(all_pos)
{
eigval = log(eigval);
out = eigvec * diagmat(eigval) * eigvec.t();
return true;
}
}
arma_extra_debug_print("warning: sympd optimisation failed");
// fallthrough if eigen decomposition failed or an eigenvalue is zero
}
return op_logmat_cx::apply_common(out, S, n_iters);
}
template<typename T>
inline
bool
op_logmat_cx::apply_common(Mat< std::complex<T> >& out, Mat< std::complex<T> >& S, const uword n_iters)
{
arma_extra_debug_sigprint();
typedef typename std::complex<T> eT;
Mat<eT> U;
const bool schur_ok = auxlib::schur(U,S);
if(schur_ok == false) { arma_extra_debug_print("logmat(): schur decomposition failed"); return false; }
//double theta[] = { 1.10e-5, 1.82e-3, 1.62e-2, 5.39e-2, 1.14e-1, 1.87e-1, 2.64e-1 };
double theta[] = { 0.0, 0.0, 1.6206284795015624e-2, 5.3873532631381171e-2, 1.1352802267628681e-1, 1.8662860613541288e-1, 2.642960831111435e-1 };
// theta[0] and theta[1] not really used
const uword N = S.n_rows;
uword p = 0;
uword m = 6;
uword iter = 0;
while(iter < n_iters)
{
const T tau = norm( (S - eye< Mat<eT> >(N,N)), 1 );
if(tau <= theta[6])
{
p++;
uword j1 = 0;
uword j2 = 0;
for(uword i=2; i<=6; ++i) { if( tau <= theta[i]) { j1 = i; break; } }
for(uword i=2; i<=6; ++i) { if((tau/2.0) <= theta[i]) { j2 = i; break; } }
// sanity check, for development purposes only
arma_debug_check( (j2 > j1), "internal error: op_logmat::apply_direct(): j2 > j1" );
if( ((j1 - j2) <= 1) || (p == 2) ) { m = j1; break; }
}
const bool sqrtmat_ok = op_sqrtmat_cx::apply_direct(S,S);
if(sqrtmat_ok == false) { arma_extra_debug_print("logmat(): sqrtmat() failed"); return false; }
iter++;
}
if(iter >= n_iters) { arma_debug_warn("logmat(): reached max iterations without full convergence"); }
S.diag() -= eT(1);
if(m >= 1)
{
const bool helper_ok = op_logmat_cx::helper(S,m);
if(helper_ok == false) { return false; }
}
out = U * S * U.t();
out *= eT(eop_aux::pow(double(2), double(iter)));
return true;
}
template<typename eT>
inline
bool
op_logmat_cx::helper(Mat<eT>& A, const uword m)
{
arma_extra_debug_sigprint();
if(A.is_finite() == false) { return false; }
const vec indices = regspace<vec>(1,m-1);
mat tmp(m,m,fill::zeros);
tmp.diag(-1) = indices / sqrt(square(2.0*indices) - 1.0);
tmp.diag(+1) = indices / sqrt(square(2.0*indices) - 1.0);
vec eigval;
mat eigvec;
const bool eig_ok = eig_sym_helper(eigval, eigvec, tmp, 'd', "logmat()");
if(eig_ok == false) { arma_extra_debug_print("logmat(): eig_sym() failed"); return false; }
const vec nodes = (eigval + 1.0) / 2.0;
const vec weights = square(eigvec.row(0).t());
const uword N = A.n_rows;
Mat<eT> B(N,N,fill::zeros);
Mat<eT> X;
for(uword i=0; i < m; ++i)
{
// B += weights(i) * solve( (nodes(i)*A + eye< Mat<eT> >(N,N)), A );
//const bool solve_ok = solve( X, (nodes(i)*A + eye< Mat<eT> >(N,N)), A, solve_opts::fast );
const bool solve_ok = solve( X, trimatu(nodes(i)*A + eye< Mat<eT> >(N,N)), A, solve_opts::no_approx );
if(solve_ok == false) { arma_extra_debug_print("logmat(): solve() failed"); return false; }
B += weights(i) * X;
}
A = B;
return true;
}
template<typename T1>
inline
void
op_logmat_sympd::apply(Mat<typename T1::elem_type>& out, const Op<T1,op_logmat_sympd>& in)
{
arma_extra_debug_sigprint();
const bool status = op_logmat_sympd::apply_direct(out, in.m);
if(status == false)
{
out.soft_reset();
arma_stop_runtime_error("logmat_sympd(): transformation failed");
}
}
template<typename T1>
inline
bool
op_logmat_sympd::apply_direct(Mat<typename T1::elem_type>& out, const Base<typename T1::elem_type,T1>& expr)
{
arma_extra_debug_sigprint();
#if defined(ARMA_USE_LAPACK)
{
typedef typename T1::pod_type T;
typedef typename T1::elem_type eT;
const unwrap<T1> U(expr.get_ref());
const Mat<eT>& X = U.M;
arma_debug_check( (X.is_square() == false), "logmat_sympd(): given matrix must be square sized" );
Col< T> eigval;
Mat<eT> eigvec;
const bool status = eig_sym_helper(eigval, eigvec, X, 'd', "logmat_sympd()");
if(status == false) { return false; }
const uword N = eigval.n_elem;
const T* eigval_mem = eigval.memptr();
bool all_pos = true;
for(uword i=0; i<N; ++i) { all_pos = (eigval_mem[i] <= T(0)) ? false : all_pos; }
if(all_pos == false) { return false; }
eigval = log(eigval);
out = eigvec * diagmat(eigval) * eigvec.t();
return true;
}
#else
{
arma_ignore(out);
arma_ignore(expr);
arma_stop_logic_error("logmat_sympd(): use of LAPACK must be enabled");
return false;
}
#endif
}
//! @}
| 23.295203 | 154 | 0.591399 | hb407 |
604fe3d541cfc12556116a40a7cd82c09b30031a | 2,506 | cpp | C++ | B Problems/TIMUS1349 - Farm.cpp | UVE-R/CP-CPP | 67819f4115917f663c22ada899b27ace7b2e9b9e | [
"Unlicense"
] | 1 | 2021-08-24T21:05:28.000Z | 2021-08-24T21:05:28.000Z | B Problems/TIMUS1349 - Farm.cpp | UVE-R/CP-CPP | 67819f4115917f663c22ada899b27ace7b2e9b9e | [
"Unlicense"
] | null | null | null | B Problems/TIMUS1349 - Farm.cpp | UVE-R/CP-CPP | 67819f4115917f663c22ada899b27ace7b2e9b9e | [
"Unlicense"
] | null | null | null | # include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <pii, int> ppi;
typedef pair <int, pii> pip;
typedef pair <pii, pii> ppp;
typedef pair <ll, ll> pll;
typedef vector<int> vi;
# define A first
# define B second
# define endl '\n'
# define sep ' '
# define kill(x) return cout << x << endl, 0
# define lc id << 1
# define rc id << 1 | 1
# define pb push_back
# define MP make_pair
# define P(x) cout<<#x<<" = { "<<x<<" }\n"
# define all(v) ((v).begin()), ((v).end())
# define sz(v) ((int)((v).size()))
# define clr(v, d) memset(v, d, sizeof(v))
# define rep(i, v) for(int i=0;i<sz(v);++i)
# define lp(i, n) for(int i=0;i<(int)(n);++i)
# define lpi(i, j, n) for(int i=(j);i<(int)(n);++i)
# define lpd(i, j, n) for(int i=(j);i>=(int)(n);--i)
# define InTheNameOfGod ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);
# define inf 0x7fffffff
ll power(ll a, ll b, ll md) {return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2, md) % md : power(a * a % md, b / 2, md) % md));}
const int xn = 1e2 + 10;
const int xm = - 20 + 10;
const int sq = 320;
const ll INF = 9e17 + 10;
const int mod = 998244353;
const int base = 257;
const int OO=(int)1e6;
const int maxim = 1e9;
const double EPS = (1e-10);
char arr[51][51];
int main()
{
InTheNameOfGod
int n;
cin>>n;
if(n==1){
cout<<"1 2 3"<<endl;
}else if(n==2){
cout<<"3 4 5"<<endl;
}else{
cout<<"-1"<<endl;
}
return 0;
}
| 35.295775 | 132 | 0.343176 | UVE-R |
6054ed7731e661665bffa59ed2f1b41d03101ab1 | 6,759 | cpp | C++ | Siv3D/src/Siv3D-Platform/WindowsDesktop/Siv3D/Window/WindowProc.cpp | tetsurom/OpenSiv3D | 935525b9ad4f54966327ffa129227c956f08e231 | [
"MIT"
] | 709 | 2016-03-19T07:55:58.000Z | 2022-03-31T08:02:22.000Z | Siv3D/src/Siv3D-Platform/WindowsDesktop/Siv3D/Window/WindowProc.cpp | tetsurom/OpenSiv3D | 935525b9ad4f54966327ffa129227c956f08e231 | [
"MIT"
] | 415 | 2017-05-21T05:05:02.000Z | 2022-03-29T16:08:27.000Z | Siv3D/src/Siv3D-Platform/WindowsDesktop/Siv3D/Window/WindowProc.cpp | tetsurom/OpenSiv3D | 935525b9ad4f54966327ffa129227c956f08e231 | [
"MIT"
] | 123 | 2016-03-19T12:47:08.000Z | 2022-03-25T03:47:51.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Error.hpp>
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/FormatLiteral.hpp>
# include <Siv3D/UserAction.hpp>
# include <Siv3D/UserAction/IUSerAction.hpp>
# include <Siv3D/Common/Siv3DEngine.hpp>
# include <Siv3D/Cursor/CCursor.hpp>
# include <Siv3D/Mouse/CMouse.hpp>
# include <Siv3D/Gamepad/CGamepad.hpp>
# include <Siv3D/System/CSystem.hpp>
# include <Siv3D/TextInput/CTextInput.hpp>
# include <Siv3D/DragDrop/CDragDrop.hpp>
# include "WindowProc.hpp"
# include "CWindow.hpp"
# include <Dbt.h>
namespace s3d
{
LRESULT CALLBACK WindowProc(const HWND hWnd, const UINT message, const WPARAM wParam, LPARAM lParam)
{
if (auto textinput = dynamic_cast<CTextInput*>(SIV3D_ENGINE(TextInput)))
{
if (textinput->process(message, wParam, &lParam))
{
return 0;
}
}
if (auto dragDrop = dynamic_cast<CDragDrop*>(SIV3D_ENGINE(DragDrop)))
{
dragDrop->process();
}
switch (message)
{
case WM_CLOSE:
{
LOG_TRACE(U"WM_CLOSE");
SIV3D_ENGINE(UserAction)->reportUserActions(UserAction::CloseButtonClicked);
return 0; // WM_DESTROY を発生させない
}
case WM_SETFOCUS:
{
LOG_VERBOSE(U"WM_SETFOCUS");
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->onFocus(true);
break;
}
case WM_SYSKEYDOWN:
{
if ((wParam == VK_RETURN) && (lParam & (1 << 29))) // Alt + Enter
{
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->requestToggleFullscreen();
return 0;
}
break;
}
case WM_SYSKEYUP:
{
break;
}
case WM_KILLFOCUS:
{
LOG_VERBOSE(U"WM_KILLFOCUS");
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->onFocus(false);
break;
}
case WM_KEYDOWN:
{
LOG_VERBOSE(U"WM_KEYDOWN");
break;
}
case WM_SYSCOMMAND:
{
LOG_VERBOSE(U"WM_SYSCOMMAND");
switch (wParam & 0xffF0)
{
case SC_SCREENSAVE:
case SC_MONITORPOWER:
case SC_KEYMENU:
return 0;
}
break;
}
case WM_DISPLAYCHANGE:
{
LOG_TRACE(U"WM_DISPLAYCHANGE");
return true;
}
case WM_DPICHANGED:
{
LOG_TRACE(U"WM_DPICHANGED");
const uint32 newDPI = HIWORD(wParam);
const RECT rect = *reinterpret_cast<const RECT*>(lParam);
const Point pos(rect.left, rect.top);
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->onDPIChange(newDPI, pos);
return true;
}
case WM_SIZE:
{
LOG_TRACE(U"WM_SIZE");
auto pCWindow = dynamic_cast<CWindow*>(SIV3D_ENGINE(Window));
pCWindow->onBoundsUpdate();
const bool minimized = (wParam == SIZE_MINIMIZED);
const bool maximized = (wParam == SIZE_MAXIMIZED)
|| (pCWindow->getState().maximized && (wParam != SIZE_RESTORED));
pCWindow->onResize(minimized, maximized);
const Size frameBufferSize(LOWORD(lParam), HIWORD(lParam));
pCWindow->onFrameBufferResize(frameBufferSize);
return 0;
}
case WM_MOVE:
{
LOG_VERBOSE(U"WM_MOVE");
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->onBoundsUpdate();
return 0;
}
case WM_DESTROY:
{
LOG_TRACE(U"WM_DESTROY");
::PostQuitMessage(0);
return 0;
}
case WM_CHAR:
{
LOG_VERBOSE(U"WM_CHAR");
if (auto p = SIV3D_ENGINE(TextInput))
{
p->pushChar(static_cast<uint32>(wParam));
}
return 0;
}
case WM_UNICHAR:
{
LOG_VERBOSE(U"WM_UNICHAR");
if (wParam == UNICODE_NOCHAR)
{
return true;
}
if (auto p = SIV3D_ENGINE(TextInput))
{
p->pushChar(static_cast<uint32>(wParam));
}
return 0;
}
case WM_DEVICECHANGE:
{
LOG_VERBOSE(U"WM_DEVICECHANGE {:#X}"_fmt(wParam));
if (wParam == DBT_DEVICEARRIVAL)
{
LOG_TRACE(U"WM_DEVICECHANGE (DBT_DEVICEARRIVAL)");
if (CSystem* system = dynamic_cast<CSystem*>(SIV3D_ENGINE(System)))
{
system->onDeviceChange();
}
const DEV_BROADCAST_HDR* dbh = reinterpret_cast<DEV_BROADCAST_HDR*>(lParam);
if (dbh && (dbh->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
{
dynamic_cast<CGamepad*>(SIV3D_ENGINE(Gamepad))->detectJoystickConnection();
}
}
else if (wParam == DBT_DEVICEREMOVECOMPLETE)
{
LOG_TRACE(U"WM_DEVICECHANGE (DBT_DEVICEREMOVECOMPLETE)");
if (CSystem* system = dynamic_cast<CSystem*>(SIV3D_ENGINE(System)))
{
system->onDeviceChange();
}
const DEV_BROADCAST_HDR* dbh = reinterpret_cast<DEV_BROADCAST_HDR*>(lParam);
if (dbh && (dbh->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE))
{
dynamic_cast<CGamepad*>(SIV3D_ENGINE(Gamepad))->detectJoystickDisconnection();
}
}
break;
}
case WM_ERASEBKGND:
{
return true;
}
case WM_GETMINMAXINFO:
{
//LOG_VERBOSE(U"WM_GETMINMAXINFO");
LPMINMAXINFO pMinMaxInfo = reinterpret_cast<LPMINMAXINFO>(lParam);
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->onMinMaxInfo(pMinMaxInfo);
break;
}
case WM_ENTERSIZEMOVE:
{
LOG_TRACE(U"WM_ENTERSIZEMOVE");
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->onEnterSizeMove();
break;
}
case WM_EXITSIZEMOVE:
{
LOG_TRACE(U"WM_EXITSIZEMOVE");
dynamic_cast<CWindow*>(SIV3D_ENGINE(Window))->onExitSizeMove();
break;
}
case WM_MOUSEMOVE:
{
if (auto p = dynamic_cast<CCursor*>(SIV3D_ENGINE(Cursor)))
{
p->handleMessage(message, wParam, lParam);
}
break;
}
case WM_SETCURSOR:
{
if (const uint32 hitTest = (lParam & 0xFFFF);
(hitTest == HTCLIENT))
{
if (auto p = dynamic_cast<CCursor*>(SIV3D_ENGINE(Cursor)))
{
p->onSetCursor();
}
return 1;
}
break;
}
case WM_MOUSEWHEEL:
{
SIV3D_ENGINE(Mouse)->onScroll(0, static_cast<short>(HIWORD(wParam)) / -double(WHEEL_DELTA));
return 0;
}
case WM_MOUSEHWHEEL:
{
SIV3D_ENGINE(Mouse)->onScroll(static_cast<short>(HIWORD(wParam)) / double(WHEEL_DELTA), 0);
return 0;
}
case WM_TOUCH:
{
if (const size_t num_inputs = LOWORD(wParam))
{
Array<TOUCHINPUT> touchInputs(num_inputs);
if (::GetTouchInputInfo(reinterpret_cast<HTOUCHINPUT>(lParam),
static_cast<uint32>(touchInputs.size()), touchInputs.data(),
sizeof(TOUCHINPUT)))
{
if (auto pMouse = dynamic_cast<CMouse*>(SIV3D_ENGINE(Mouse)))
{
pMouse->onTouchInput(touchInputs);
}
::CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(lParam));
return 0;
}
}
break;
}
}
return ::DefWindowProcW(hWnd, message, wParam, lParam);
}
}
| 21.663462 | 101 | 0.637224 | tetsurom |
605694f0cccea5188a2420b41942d03e8c882fef | 1,389 | cpp | C++ | lib/app/EnergyManager.cpp | dniklaus/batt-powered-device | a59a78a19453622007cf4b717fcfc8073cab0bc5 | [
"MIT"
] | null | null | null | lib/app/EnergyManager.cpp | dniklaus/batt-powered-device | a59a78a19453622007cf4b717fcfc8073cab0bc5 | [
"MIT"
] | null | null | null | lib/app/EnergyManager.cpp | dniklaus/batt-powered-device | a59a78a19453622007cf4b717fcfc8073cab0bc5 | [
"MIT"
] | null | null | null | /*
* EnergyManager.cpp
*
* Created on: 13.06.2019
* Author: dniklaus
*/
#include "main.h"
// #include "Timer.h"
#include "EnergyManager.h"
EnergyManager::EnergyManager()
{ }
EnergyManager::~EnergyManager()
{ }
void EnergyManager::enterMcuStopMode(uint32_t stopTimeMillis)
{
//if debugging:
#ifdef DEBUG
// delayAndSchedule(stopTimeMillis);
HAL_Delay(stopTimeMillis);
return;
#endif
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);
//__HAL_RCC_WAKEUPSTOP_CLK_CONFIG(RCC_STOP_WAKEUPCLOCK_HSI); //was hsi
// __HAL_RCC_WAKEUPSTOP_CLK_CONFIG(RCC_STOP_WAKEUPCLOCK_MSI);
// HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, stopTimeMillis * 2, RTC_WAKEUPCLOCK_RTCCLK_DIV16);
HAL_SuspendTick();
/* Enter Stop Mode */
// HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFE);
////////////////
// STOP MODE
////////////////
/* Disable Wakeup Counter */
HAL_ResumeTick();
// adjust stopped tick counter to get continuous time base
uint32_t adjustTickCounterAfterStop = stopTimeMillis;
while (adjustTickCounterAfterStop > 0)
{
HAL_IncTick();
--adjustTickCounterAfterStop;
}
// HAL_RTCEx_DeactivateWakeUpTimer (&hrtc);
/* Configures system clock after wake-up from STOP: enable HSE, PLL and select
PLL as system clock source (HSE and PLL are disabled in STOP mode) */
// SystemClock_Config();
//MX_GPIO_Init();
//MX_SPI1_Init();
}
| 23.15 | 89 | 0.716343 | dniklaus |
605a9572ae1515ffb2c70eb9cec8529b1d2b5017 | 276 | cpp | C++ | Leetcode Solution/Arrays/Easy/1299. Replace Elements with Greatest Element on Right Side.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 169 | 2021-05-30T10:02:19.000Z | 2022-03-27T18:09:32.000Z | Leetcode Solution/Arrays/Easy/1299. Replace Elements with Greatest Element on Right Side.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 1 | 2021-10-02T14:46:26.000Z | 2021-10-02T14:46:26.000Z | Leetcode Solution/Arrays/Easy/1299. Replace Elements with Greatest Element on Right Side.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 44 | 2021-05-30T19:56:29.000Z | 2022-03-17T14:49:00.000Z |
class Solution {
public:
vector<int> replaceElements(vector<int>& arr) {
int maxv = -1,temp;
for(int i=arr.size()-1;i>=0;i--)
{
temp = arr[i];
arr[i]=maxv;
maxv = max(maxv,temp);
}
return arr;
}
};
| 18.4 | 51 | 0.452899 | bilwa496 |
605d87e7bcaaa4500f0365dd3c57d864ff56688e | 846 | cpp | C++ | Source/VoxelWorld/Application/Game/Crosshair.cpp | AirGuanZ/VoxelWorld | 8defdee9e2b8fb20607d33ba0f3a316b95273693 | [
"MIT"
] | 11 | 2018-01-15T16:05:44.000Z | 2021-06-27T09:00:08.000Z | Source/VoxelWorld/Application/Game/Crosshair.cpp | AirGuanZ/VoxelWorld | 8defdee9e2b8fb20607d33ba0f3a316b95273693 | [
"MIT"
] | null | null | null | Source/VoxelWorld/Application/Game/Crosshair.cpp | AirGuanZ/VoxelWorld | 8defdee9e2b8fb20607d33ba0f3a316b95273693 | [
"MIT"
] | 3 | 2018-03-01T06:33:37.000Z | 2021-07-03T10:35:02.000Z | /*================================================================
Filename: Crosshair.cpp
Date: 2018.1.23
Created by AirGuanZ
================================================================*/
#include <Resource\ResourceNameManager.h>
#include <Window\Window.h>
#include "Crosshair.h"
bool Crosshair::Initialize(void)
{
if(!tex_.IsAvailable())
return tex_.LoadFromFile(RscNameMgr::GetInstance()("Crosshair", "Texture"));
return true;
}
void Crosshair::Draw(ImmediateScreen2D *imScr2D)
{
assert(imScr2D != nullptr);
Window &win = Window::GetInstance();
constexpr float CROSSHAIR_PIXEL_SIZE = 35.0f;
float XSize = 0.5f * CROSSHAIR_PIXEL_SIZE / win.GetClientWidth();
float YSize = 0.5f * CROSSHAIR_PIXEL_SIZE / win.GetClientHeight();
imScr2D->DrawRectangle({ -XSize, -YSize }, { XSize, YSize }, tex_);
}
| 30.214286 | 84 | 0.594563 | AirGuanZ |
60616bf10025a38d46ee1ec5377ee2947500d468 | 2,852 | cpp | C++ | tests/IoTeX/AddressTests.cpp | vladyslav-iosdev/wallet-core | 6f8f175a380bdf9756f38bfd82fedd9b73b67580 | [
"MIT"
] | 1,306 | 2019-08-08T13:25:24.000Z | 2022-03-31T23:32:28.000Z | tests/IoTeX/AddressTests.cpp | vladyslav-iosdev/wallet-core | 6f8f175a380bdf9756f38bfd82fedd9b73b67580 | [
"MIT"
] | 1,179 | 2019-08-08T07:06:10.000Z | 2022-03-31T12:33:47.000Z | tests/IoTeX/AddressTests.cpp | vladyslav-iosdev/wallet-core | 6f8f175a380bdf9756f38bfd82fedd9b73b67580 | [
"MIT"
] | 811 | 2019-08-08T13:27:44.000Z | 2022-03-31T21:22:53.000Z | // Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include <gtest/gtest.h>
#include "HexCoding.h"
#include "PrivateKey.h"
#include "PublicKey.h"
#include "IoTeX/Address.h"
namespace TW::IoTeX {
TEST(IoTeXAddress, Invalid) {
ASSERT_FALSE(Address::isValid("io187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8"));
ASSERT_FALSE(Address::isValid("io187wzp08vnhjpkydnr97qlh8kh0dpkkytfam8j"));
ASSERT_FALSE(Address::isValid("it187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8j"));
ASSERT_FALSE(Address::isValid("ko187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8j"));
ASSERT_FALSE(Address::isValid("io187wzp18vnhjjpkydnr97qlh8kh0dpkkytfam8j"));
ASSERT_FALSE(Address::isValid("io187wzp08vnhjbpkydnr97qlh8kh0dpkkytfam8j"));
ASSERT_FALSE(Address::isValid("io187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8k"));
}
TEST(IoTeXAddress, Valid) {
ASSERT_TRUE(Address::isValid("io187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8j"));
}
TEST(IoTeXAddress, FromString) {
Address address;
ASSERT_TRUE(Address::decode("io187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8j", address));
ASSERT_EQ("io187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8j", address.string());
ASSERT_FALSE(Address::decode("io187wzp08vnhjbpkydnr97qlh8kh0dpkkytfam8j", address));
}
TEST(IoTeXAddress, FromPrivateKey) {
const auto privateKey = PrivateKey(parse_hex("0806c458b262edd333a191e92f561aff338211ee3e18ab315a074a2d82aa343f"));
const auto publicKey = PublicKey(privateKey.getPublicKey(TWPublicKeyTypeSECP256k1Extended));
const auto address = Address(publicKey);
ASSERT_EQ(address.string(), "io187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8j");
EXPECT_THROW({
try
{
const auto publicKey = PublicKey(privateKey.getPublicKey(TWPublicKeyTypeSECP256k1));
const auto address = Address(publicKey);
}
catch( const std::invalid_argument& e )
{
EXPECT_STREQ("address may only be an extended SECP256k1 public key", e.what());
throw;
}
}, std::invalid_argument);
}
TEST(IoTeXAddress, FromKeyHash) {
const auto keyHash = parse_hex("3f9c20bcec9de520d88d98cbe07ee7b5ded0dac4");
const auto address = Address(keyHash);
ASSERT_EQ(address.string(), "io187wzp08vnhjjpkydnr97qlh8kh0dpkkytfam8j");
EXPECT_THROW({
try
{
const auto keyHash = parse_hex("3f9c20bcec9de520d88d98cbe07ee7b5ded0da");
const auto address = Address(keyHash);
}
catch( const std::invalid_argument& e )
{
EXPECT_STREQ("invalid address data", e.what());
throw;
}
}, std::invalid_argument);
}
} // namespace TW::IoTeX
| 36.101266 | 118 | 0.725806 | vladyslav-iosdev |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.