text
stringlengths 5
1.04M
|
|---|
// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2010 David Capello
//
// This file is distributed under the terms of the MIT license,
// please read LICENSE.txt for more information.
#include "Wg/ProgressBar.hpp"
#include "Wg/Debug.hpp"
#include "Wg/WidgetClass.hpp"
#include "Wg/PreferredSizeEvent.hpp"
#include "Wg/Win32.hpp"
#ifndef PBM_SETMARQUEE
#define PBM_SETMARQUEE 1034
#endif
using namespace Wg;
ProgressBar::ProgressBar(Widget* parent, const Style& style)
: Widget(WidgetClassName(PROGRESS_CLASS), parent, style)
{
// default values
setRange(0, 100);
setValue(0);
}
ProgressBar::ProgressBar(int minValue, int maxValue,
Widget* parent, const Style& style)
: Widget(WidgetClassName(PROGRESS_CLASS), parent, style)
{
assert(minValue <= maxValue);
setRange(minValue, maxValue);
setValue(minValue); // default value
}
ProgressBar::~ProgressBar()
= default;
/**
PBM_SETBKCOLOR
*/
void ProgressBar::setBgColor(const Color& color)
{
assert(::IsWindow(getHandle()));
Widget::setBgColor(color);
sendMessage(PBM_SETBKCOLOR, 0, convert_to<COLORREF>(color));
}
// void ProgressBar::setBarColor(const Color& color)
// {
// }
int ProgressBar::getMinimum()
{
return static_cast<int>(sendMessage(PBM_GETRANGE, TRUE, 0));
}
int ProgressBar::getMaximum()
{
return static_cast<int>(sendMessage(PBM_GETRANGE, FALSE, 0));
}
/**
PBM_GETRANGE
*/
void ProgressBar::getRange(int& minValue, int& maxValue)
{
PBRANGE pbr;
sendMessage(PBM_GETRANGE, 0, reinterpret_cast<LPARAM>(&pbr));
minValue = pbr.iLow;
maxValue = pbr.iHigh;
}
/**
PBM_SETRANGE32
*/
void ProgressBar::setRange(int minValue, int maxValue)
{
sendMessage(PBM_SETRANGE32, static_cast<WPARAM>(minValue), maxValue);
}
/**
PBM_GETPOS
*/
int ProgressBar::getValue()
{
return static_cast<int>(sendMessage(PBM_GETPOS, 0, 0));
}
/**
PBM_SETPOS
*/
void ProgressBar::setValue(int value)
{
sendMessage(PBM_SETPOS, static_cast<WPARAM>(value), 0);
}
/**
Increments the current progress bar value (position), in @a delta
units (PBM_DELTAPOS).
*/
void ProgressBar::addValue(int delta)
{
sendMessage(PBM_DELTAPOS, static_cast<WPARAM>(delta), 0);
}
void ProgressBar::setMarquee(int msecsInterval)
{
sendMessage(PBM_SETMARQUEE, msecsInterval == 0 ? FALSE: TRUE, msecsInterval);
}
void ProgressBar::onPreferredSize(PreferredSizeEvent& ev)
{
// WinXP with themes needs at least 10 pixels of height
ev.setPreferredSize(16, 16);
}
|
#pragma once
#ifndef MATHLIB_VEC4
#define MATHLIB_VEC4
#include "Includes.hpp"
/**
* \file Vector4.hpp
*
* \brief Vec4 type implementation.
*/
namespace Mathlib
{
struct Vec2;
struct Vec3;
struct MATHLIBRARY_API Vec4
{
/// Vector's X component
float X = 0.f;
/// Vector's Y component
float Y = 0.f;
/// Vector's Z component
float Z = 0.f;
/// Vector's W component
float W = 0.f;
//Constants
/// Zero vector constant {0, 0, 0, 0}.
static const Vec4 Zero;
/// One vector constant {1, 1, 1, 0}.
static const Vec4 One;
/// Right vector constant {1, 0, 0, 0}.
static const Vec4 Right;
/// Left vector constant {-1, 0, 0, 0}.
static const Vec4 Left;
/// Up vector constant {0, 1, 0, 0}.
static const Vec4 Up;
/// Down vector constant {0, -1, 0, 0}.
static const Vec4 Down;
/// Down vector constant {0, 0, 1, 0}.
static const Vec4 Forward;
/// Down vector constant {0, 0, -1, 0}.
static const Vec4 Backward;
//Constructors
/**
* \brief Default constructor
*/
Vec4() = default;
/**
* \brief Value constructor
*
* \param[in] _xyz Value applied on all vector axis.
*/
Vec4(float _xyzw) noexcept;
/**
* \brief Value constructor
*
* \param[in] _x X axis value.
* \param[in] _y Y axis value.
* \param[in] _z Z axis value.
* \param[in] _w W axis value.
*/
Vec4(float _x, float _y, float _z, float _w) noexcept;
/**
* \brief Constructor from a Vec2
*
* \param[in] _vec2 Vec2 to copy axis values from.
* \param[in] _z Z axis value.
* \param[in] _w W axis value.
*/
Vec4(Vec2 _vec2, float _z = 0.f, float _w = 0.f) noexcept;
/**
* \brief Constructor from a Vec3
*
* \param[in] _vec3 Vec3 to copy axis values from.
* \param[in] _w W axis value.
*/
Vec4(Vec3 _vec3, float _w = 0.f) noexcept;
/**
* \brief Default copy constructor
*/
Vec4(const Vec4& _vec4) = default;
/**
* \brief Default move constructor
*/
Vec4(Vec4&& _vec4) = default;
//Static Methods
/**
* \brief Compute distance between two Vec4
*
* \param[in] _start left hand side operand to compute distance with.
* \param[in] _end right hand side operand to compute distance with.
*
* \return distance between _start and _end
*/
static float Distance(const Vec4& _start, const Vec4& _end) noexcept;
/**
* \brief Compute squared distance between two Vec4
*
* \param[in] _start left hand side operand to compute squared distance with.
* \param[in] _end right hand side operand to compute squared distance with.
*
* \return squared distance between _start and _end
*/
static float SqrDistance(const Vec4& _start, const Vec4& _end) noexcept;
/**
* \brief Compute lerped vector between two Vec3
*
* \param[in] _start left hand side operand to compute lerped vector with.
* \param[in] _end right hand side operand to compute lerped vector with.
* \param[in] _alpha Alpha of the lerp.
*
* \return lerped vector between _start and _end
*/
static Vec4 Lerp(const Vec4& _start, const Vec4& _end, float _alpha) noexcept;
//Equality
/**
* \brief Check if Vec4 is equal to default Zero vector
**/
bool IsZero() const noexcept;
/**
* \brief Compare this vector with with _other
*
* \param[in] _other other vector to do the comparison with.
* \param[in] _epsilon threshold to accept equality.
*
* \return if this and _other are equal.
*/
bool Equals(const Vec4& _other, float _epsilon = 0.f) const noexcept;
/**
* \brief Operator to compare this vector with with _rhs
*
* \param[in] _rhs right hand side operand to do the comparison with.
*
* \return if this and _rhs are equal.
*/
bool operator==(const Vec4& _rhs) const noexcept;
/**
* \brief Operator to compare this vector with with _rhs.
*
* \param[in] _rhs right hand side operand to do the comparison with.
*
* \return if this and _rhs are different.
*/
bool operator!=(const Vec4& _rhs) const noexcept;
//Accessors
/**
* \brief return this vector as a float*.
*/
const float* Data() const noexcept;
//Methods
/**
* \brief return the length of this vector.
*/
float Length() const noexcept;
/**
* \brief Return the squared length of this vector.
*/
float SquaredLength() const noexcept;
/**
* \brief Normalize this vector and return it.
*/
Vec4& Normalize() noexcept;
/**
* \brief Return this vector normalized vector.
*/
Vec4 GetNormalized() const noexcept;
/**
* \brief Check if the vector is normalized.
*/
bool IsNormalized() const noexcept;
//Operator
/**
* \brief \e Default move assignement.
*
* \return self vector assigned.
*/
Vec4& operator=(Vec4&&) = default;
/**
* \brief \e Default copy assignement.
*
* \return self vector assigned.
*/
Vec4& operator=(const Vec4&) = default;
/**
* \brief \e Getter of the opposite signed vector.
*
* \return new opposite signed vector.
*/
Vec4 operator-() const noexcept;
/**
* \brief Add term by term vector values.
*
* \param[in] _rhs vector to add.
*
* \return new vector sum of both vectors.
*/
Vec4 operator+(const Vec4& _rhs) const noexcept;
/**
* \brief Substract term by term vector values.
*
* \param[in] _rhs vector to substract.
*
* \return new vector result of the substraction of both vectors.
*/
Vec4 operator-(const Vec4& _rhs) const noexcept;
/**
* \brief Multiply term by term vector values.
*
* \param[in] _rhs vector to multiply.
*
* \return new vector result of the multiplication of both vectors.
*/
Vec4 operator*(const Vec4& _rhs) const noexcept;
/**
* \brief Divide term by term vector values.
*
* \param[in] _rhs vector to divide this vector with.
*
* \return new vector result of the operation.
*/
Vec4 operator/(const Vec4& _rhs) const;
/**
* \brief Add term by term vector values.
*
* \param[in] _rhs vector to add.
*
* \return self vector result.
*/
Vec4& operator+=(const Vec4& _rhs) noexcept;
/**
* \brief Substract term by term vector values.
*
* \param[in] _rhs vector to substract.
*
* \return self vector result.
*/
Vec4& operator-=(const Vec4& _rhs) noexcept;
/**
* \brief Multiply term by term vector values.
*
* \param[in] _rhs vector to multiply.
*
* \return self vector result.
*/
Vec4& operator*=(const Vec4& _rhs) noexcept;
/**
* \brief Divide term by term vector values.
*
* \param[in] _rhs vector to divide.
*
* \return self vector result.
*/
Vec4& operator/=(const Vec4& _rhs);
/**
* \brief Scale each vector's axis by _scale.
*
* \param[in] _scale Scale value to apply to all axis.
*
* \return new vector scaled.
*/
Vec4 operator*(float _scale) const noexcept;
/**
* \brief Divide each vector's axis by _scale.
*
* \param[in] _scale Scale value to apply to all axis.
*
* \return new divided vector.
*/
Vec4 operator/(float _scale) const;
/**
* \brief Scale each vector's axis by _scale.
*
* \param[in] _scale Scale value to apply to all axis.
*
* \return self vector result.
*/
Vec4& operator*=(float _scale) noexcept;
/**
* \brief Scale each vector's axis by _scale.
*
* \param[in] _scale Scale value to apply to all axis.
*
* \return self vector result.
*/
Vec4& operator/=(float _scale);
//Debug
/**
* \brief return vector values as string.
*/
std::string ToString()const noexcept;
};
}
#endif
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "gdirenderer.hpp"
#include "../../types/inc/Viewport.hpp"
#pragma hdrstop
using namespace Microsoft::Console::Types;
using namespace Microsoft::Console::Render;
// Routine Description:
// - Notifies us that the system has requested a particular pixel area of the client rectangle should be redrawn. (On WM_PAINT)
// Arguments:
// - prcDirtyClient - Pointer to pixel area (RECT) of client region the system believes is dirty
// Return Value:
// - HRESULT S_OK, GDI-based error code, or safemath error
HRESULT GdiEngine::InvalidateSystem(const RECT* const prcDirtyClient) noexcept
{
RETURN_HR(_InvalidCombine(prcDirtyClient));
}
// Routine Description:
// - Notifies us that the console is attempting to scroll the existing screen area
// Arguments:
// - pcoordDelta - Pointer to character dimension (COORD) of the distance the console would like us to move while scrolling.
// Return Value:
// - HRESULT S_OK, GDI-based error code, or safemath error
HRESULT GdiEngine::InvalidateScroll(const COORD* const pcoordDelta) noexcept
{
if (pcoordDelta->X != 0 || pcoordDelta->Y != 0)
{
POINT ptDelta = { 0 };
RETURN_IF_FAILED(_ScaleByFont(pcoordDelta, &ptDelta));
RETURN_IF_FAILED(_InvalidOffset(&ptDelta));
SIZE szInvalidScrollNew;
RETURN_IF_FAILED(LongAdd(_szInvalidScroll.cx, ptDelta.x, &szInvalidScrollNew.cx));
RETURN_IF_FAILED(LongAdd(_szInvalidScroll.cy, ptDelta.y, &szInvalidScrollNew.cy));
// Store if safemath succeeded
_szInvalidScroll = szInvalidScrollNew;
}
return S_OK;
}
// Routine Description:
// - Notifies us that the console has changed the selection region and would like it updated
// Arguments:
// - rectangles - Vector of rectangles to draw, line by line
// Return Value:
// - HRESULT S_OK or GDI-based error code
HRESULT GdiEngine::InvalidateSelection(const std::vector<SMALL_RECT>& rectangles) noexcept
{
for (const auto& rect : rectangles)
{
RETURN_IF_FAILED(Invalidate(&rect));
}
return S_OK;
}
// Routine Description:
// - Notifies us that the console has changed the character region specified.
// - NOTE: This typically triggers on cursor or text buffer changes
// Arguments:
// - psrRegion - Character region (SMALL_RECT) that has been changed
// Return Value:
// - S_OK, GDI related failure, or safemath failure.
HRESULT GdiEngine::Invalidate(const SMALL_RECT* const psrRegion) noexcept
{
RECT rcRegion = { 0 };
RETURN_IF_FAILED(_ScaleByFont(psrRegion, &rcRegion));
RETURN_HR(_InvalidateRect(&rcRegion));
}
// Routine Description:
// - Notifies us that the console has changed the position of the cursor.
// Arguments:
// - pcoordCursor - the new position of the cursor
// Return Value:
// - S_OK, else an appropriate HRESULT for failing to allocate or write.
HRESULT GdiEngine::InvalidateCursor(const COORD* const pcoordCursor) noexcept
{
SMALL_RECT sr = Viewport::FromCoord(*pcoordCursor).ToExclusive();
return this->Invalidate(&sr);
}
// Routine Description:
// - Notifies to repaint everything.
// - NOTE: Use sparingly. Only use when something that could affect the entire frame simultaneously occurs.
// Arguments:
// - <none>
// Return Value:
// - S_OK, S_FALSE (if no window yet), GDI related failure, or safemath failure.
HRESULT GdiEngine::InvalidateAll() noexcept
{
// If we don't have a window, don't bother.
if (!_IsWindowValid())
{
return S_FALSE;
}
RECT rc;
RETURN_HR_IF(E_FAIL, !(GetClientRect(_hwndTargetWindow, &rc)));
RETURN_HR(InvalidateSystem(&rc));
}
// Method Description:
// - Notifies us that we're about to circle the buffer, giving us a chance to
// force a repaint before the buffer contents are lost. The GDI renderer
// doesn't care if we lose text - we're only painting visible text anyways,
// so we return false.
// Arguments:
// - Receives a bool indicating if we should force the repaint.
// Return Value:
// - S_FALSE - we succeeded, but the result was false.
HRESULT GdiEngine::InvalidateCircling(_Out_ bool* const pForcePaint) noexcept
{
*pForcePaint = false;
return S_FALSE;
}
// Method Description:
// - Notifies us that we're about to be torn down. This gives us a last chance
// to force a repaint before the buffer contents are lost. The GDI renderer
// doesn't care if we lose text - we're only painting visible text anyways,
// so we return false.
// Arguments:
// - Receives a bool indicating if we should force the repaint.
// Return Value:
// - S_FALSE - we succeeded, but the result was false.
HRESULT GdiEngine::PrepareForTeardown(_Out_ bool* const pForcePaint) noexcept
{
*pForcePaint = false;
return S_FALSE;
}
// Routine Description:
// - Helper to combine the given rectangle into the invalid region to be updated on the next paint
// Arguments:
// - prc - Pixel region (RECT) that should be repainted on the next frame
// Return Value:
// - S_OK, GDI related failure, or safemath failure.
HRESULT GdiEngine::_InvalidCombine(const RECT* const prc) noexcept
{
if (!_fInvalidRectUsed)
{
_rcInvalid = *prc;
_fInvalidRectUsed = true;
}
else
{
_OrRect(&_rcInvalid, prc);
}
// Ensure invalid areas remain within bounds of window.
RETURN_IF_FAILED(_InvalidRestrict());
return S_OK;
}
// Routine Description:
// - Helper to adjust the invalid region by the given offset such as when a scroll operation occurs.
// Arguments:
// - ppt - Distances by which we should move the invalid region in response to a scroll
// Return Value:
// - S_OK, GDI related failure, or safemath failure.
HRESULT GdiEngine::_InvalidOffset(const POINT* const ppt) noexcept
{
if (_fInvalidRectUsed)
{
RECT rcInvalidNew;
RETURN_IF_FAILED(LongAdd(_rcInvalid.left, ppt->x, &rcInvalidNew.left));
RETURN_IF_FAILED(LongAdd(_rcInvalid.right, ppt->x, &rcInvalidNew.right));
RETURN_IF_FAILED(LongAdd(_rcInvalid.top, ppt->y, &rcInvalidNew.top));
RETURN_IF_FAILED(LongAdd(_rcInvalid.bottom, ppt->y, &rcInvalidNew.bottom));
// Add the scrolled invalid rectangle to what was left behind to get the new invalid area.
// This is the equivalent of adding in the "update rectangle" that we would get out of ScrollWindowEx/ScrollDC.
UnionRect(&_rcInvalid, &_rcInvalid, &rcInvalidNew);
// Ensure invalid areas remain within bounds of window.
RETURN_IF_FAILED(_InvalidRestrict());
}
return S_OK;
}
// Routine Description:
// - Helper to ensure the invalid region remains within the bounds of the window.
// Arguments:
// - <none>
// Return Value:
// - S_OK, GDI related failure, or safemath failure.
HRESULT GdiEngine::_InvalidRestrict() noexcept
{
// Ensure that the invalid area remains within the bounds of the client area
RECT rcClient;
// Do restriction only if retrieving the client rect was successful.
RETURN_HR_IF(E_FAIL, !(GetClientRect(_hwndTargetWindow, &rcClient)));
_rcInvalid.left = std::clamp(_rcInvalid.left, rcClient.left, rcClient.right);
_rcInvalid.right = std::clamp(_rcInvalid.right, rcClient.left, rcClient.right);
_rcInvalid.top = std::clamp(_rcInvalid.top, rcClient.top, rcClient.bottom);
_rcInvalid.bottom = std::clamp(_rcInvalid.bottom, rcClient.top, rcClient.bottom);
return S_OK;
}
// Routine Description:
// - Helper to add a pixel rectangle to the invalid area
// Arguments:
// - prc - Pointer to pixel rectangle representing invalid area to add to next paint frame
// Return Value:
// - S_OK, GDI related failure, or safemath failure.
HRESULT GdiEngine::_InvalidateRect(const RECT* const prc) noexcept
{
RETURN_HR(_InvalidCombine(prc));
}
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/partners/v20180321/model/DescribeRebateInfosResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Partners::V20180321::Model;
using namespace std;
DescribeRebateInfosResponse::DescribeRebateInfosResponse() :
m_rebateInfoSetHasBeenSet(false),
m_totalCountHasBeenSet(false)
{
}
CoreInternalOutcome DescribeRebateInfosResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("RebateInfoSet") && !rsp["RebateInfoSet"].IsNull())
{
if (!rsp["RebateInfoSet"].IsArray())
return CoreInternalOutcome(Error("response `RebateInfoSet` is not array type"));
const rapidjson::Value &tmpValue = rsp["RebateInfoSet"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
RebateInfoElem item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_rebateInfoSet.push_back(item);
}
m_rebateInfoSetHasBeenSet = true;
}
if (rsp.HasMember("TotalCount") && !rsp["TotalCount"].IsNull())
{
if (!rsp["TotalCount"].IsUint64())
{
return CoreInternalOutcome(Error("response `TotalCount` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_totalCount = rsp["TotalCount"].GetUint64();
m_totalCountHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
vector<RebateInfoElem> DescribeRebateInfosResponse::GetRebateInfoSet() const
{
return m_rebateInfoSet;
}
bool DescribeRebateInfosResponse::RebateInfoSetHasBeenSet() const
{
return m_rebateInfoSetHasBeenSet;
}
uint64_t DescribeRebateInfosResponse::GetTotalCount() const
{
return m_totalCount;
}
bool DescribeRebateInfosResponse::TotalCountHasBeenSet() const
{
return m_totalCountHasBeenSet;
}
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//#define BOOST_GEOMETRY_DEBUG_WITH_MAPPER
//#define BOOST_GEOMETRY_DEBUG_ASSEMBLE
//#define BOOST_GEOMETRY_DEBUG_IDENTIFIER
#include <geometry_test_common.hpp>
#include <boost/geometry/algorithms/buffer.hpp>
#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <test_buffer.hpp>
static std::string const simplex = "POINT(5 5)";
template <typename P>
void test_all()
{
typedef bg::model::polygon<P> polygon;
bg::strategy::buffer::join_miter join_miter;
bg::strategy::buffer::end_flat end_flat;
double const pi = boost::geometry::math::pi<double>();
test_one<P, polygon>("simplex1", simplex, join_miter, end_flat, pi, 1.0, 1.0);
test_one<P, polygon>("simplex2", simplex, join_miter, end_flat, pi * 4.0, 2.0, 2.0, true, 0.1);
test_one<P, polygon>("simplex3", simplex, join_miter, end_flat, pi * 9.0, 3.0, 3.0, true, 0.1);
}
int test_main(int, char* [])
{
//std::cout << std::setprecision(6);
//test_all<bg::model::point<float, 2, bg::cs::cartesian> >();
test_all<bg::model::point<double, 2, bg::cs::cartesian> >();
return 0;
}
|
/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_serving/core/log_collector.h"
#include <gtest/gtest.h>
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow_serving/config/log_collector_config.pb.h"
namespace tensorflow {
namespace serving {
namespace {
class FakeLogCollector : public LogCollector {
public:
Status CollectMessage(const google::protobuf::Message& message) { return Status::OK(); }
Status Flush() override { return Status::OK(); }
};
LogCollectorConfig CreateConfig(const string& type,
const string& filename_prefix) {
LogCollectorConfig config;
config.set_type(type);
config.set_filename_prefix(filename_prefix);
return config;
}
TEST(LogCollectorTest, NotRegistered) {
std::unique_ptr<LogCollector> log_collector;
const auto status = LogCollector::Create(
CreateConfig("notregistered", "filename_prefix"), 0, &log_collector);
EXPECT_EQ(status.code(), error::NOT_FOUND);
}
TEST(LogCollectorTest, Registration) {
TF_ASSERT_OK(LogCollector::RegisterFactory(
"registered", [](const LogCollectorConfig& config, const uint32 id,
std::unique_ptr<LogCollector>* log_collector) {
*log_collector = std::unique_ptr<LogCollector>(new FakeLogCollector());
return Status::OK();
}));
std::unique_ptr<LogCollector> log_collector;
TF_ASSERT_OK(LogCollector::Create(
CreateConfig("registered", "filename_prefix"), 0, &log_collector));
}
auto duplicate_factory = [](const LogCollectorConfig& config, const uint32 id,
std::unique_ptr<LogCollector>* log_collector) {
*log_collector = std::unique_ptr<LogCollector>(new FakeLogCollector());
return Status::OK();
};
REGISTER_LOG_COLLECTOR("duplicate", duplicate_factory);
TEST(LogCollectorTest, DuplicateRegistration) {
const auto status = LogCollector::RegisterFactory(
"duplicate", [](const LogCollectorConfig& config, const uint32 id,
std::unique_ptr<LogCollector>* log_collector) {
*log_collector = std::unique_ptr<LogCollector>(new FakeLogCollector());
return Status::OK();
});
EXPECT_EQ(status.code(), error::ALREADY_EXISTS);
}
auto creation_factory = [](const LogCollectorConfig& config, const uint32 id,
std::unique_ptr<LogCollector>* log_collector) {
*log_collector = std::unique_ptr<LogCollector>(new FakeLogCollector());
return Status::OK();
};
REGISTER_LOG_COLLECTOR("creation", creation_factory);
TEST(LogCollectorTest, Creation) {
std::unique_ptr<LogCollector> log_collector0;
TF_ASSERT_OK(LogCollector::Create(CreateConfig("creation", "filename_prefix"),
0, &log_collector0));
std::unique_ptr<LogCollector> log_collector1;
TF_ASSERT_OK(LogCollector::Create(CreateConfig("creation", "filename_prefix"),
0, &log_collector1));
EXPECT_NE(log_collector0.get(), log_collector1.get());
}
} // namespace
} // namespace serving
} // namespace tensorflow
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/policy/device_network_configuration_updater.h"
#include <map>
#include "ash/constants/ash_switches.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "chrome/browser/ash/settings/cros_settings.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chromeos/network/managed_network_configuration_handler.h"
#include "chromeos/network/network_device_handler.h"
#include "chromeos/network/onc/onc_parsed_certificates.h"
#include "chromeos/network/onc/onc_utils.h"
#include "chromeos/network/onc/variable_expander.h"
#include "chromeos/settings/cros_settings_names.h"
#include "chromeos/settings/cros_settings_provider.h"
#include "chromeos/system/statistics_provider.h"
#include "components/policy/policy_constants.h"
#include "content/public/browser/browser_thread.h"
#include "net/cert/x509_certificate.h"
namespace policy {
namespace {
std::string GetDeviceAssetID() {
return g_browser_process->platform_part()
->browser_policy_connector_chromeos()
->GetDeviceAssetID();
}
} // namespace
DeviceNetworkConfigurationUpdater::~DeviceNetworkConfigurationUpdater() {}
// static
std::unique_ptr<DeviceNetworkConfigurationUpdater>
DeviceNetworkConfigurationUpdater::CreateForDevicePolicy(
PolicyService* policy_service,
chromeos::ManagedNetworkConfigurationHandler* network_config_handler,
chromeos::NetworkDeviceHandler* network_device_handler,
chromeos::CrosSettings* cros_settings,
const DeviceNetworkConfigurationUpdater::DeviceAssetIDFetcher&
device_asset_id_fetcher) {
std::unique_ptr<DeviceNetworkConfigurationUpdater> updater(
new DeviceNetworkConfigurationUpdater(
policy_service, network_config_handler, network_device_handler,
cros_settings, device_asset_id_fetcher));
updater->Init();
return updater;
}
DeviceNetworkConfigurationUpdater::DeviceNetworkConfigurationUpdater(
PolicyService* policy_service,
chromeos::ManagedNetworkConfigurationHandler* network_config_handler,
chromeos::NetworkDeviceHandler* network_device_handler,
chromeos::CrosSettings* cros_settings,
const DeviceNetworkConfigurationUpdater::DeviceAssetIDFetcher&
device_asset_id_fetcher)
: NetworkConfigurationUpdater(onc::ONC_SOURCE_DEVICE_POLICY,
key::kDeviceOpenNetworkConfiguration,
policy_service,
network_config_handler),
network_device_handler_(network_device_handler),
cros_settings_(cros_settings),
device_asset_id_fetcher_(device_asset_id_fetcher) {
DCHECK(network_device_handler_);
data_roaming_setting_subscription_ = cros_settings->AddSettingsObserver(
chromeos::kSignedDataRoamingEnabled,
base::BindRepeating(
&DeviceNetworkConfigurationUpdater::OnDataRoamingSettingChanged,
base::Unretained(this)));
if (device_asset_id_fetcher_.is_null())
device_asset_id_fetcher_ = base::BindRepeating(&GetDeviceAssetID);
}
void DeviceNetworkConfigurationUpdater::Init() {
NetworkConfigurationUpdater::Init();
const policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
// The highest authority regarding whether cellular data roaming should be
// allowed is the Device Policy. If there is no Device Policy, then
// data roaming should be allowed if this is a Cellular First device.
if (!connector->IsEnterpriseManaged() &&
chromeos::switches::IsCellularFirstDevice()) {
network_device_handler_->SetCellularAllowRoaming(true);
} else {
// Apply the roaming setting initially.
OnDataRoamingSettingChanged();
}
// Set up MAC address randomization if we are not enterprise managed.
network_device_handler_->SetMACAddressRandomizationEnabled(
!connector->IsEnterpriseManaged());
}
void DeviceNetworkConfigurationUpdater::ImportClientCertificates() {
// Importing client certificates from device policy is not implemented.
}
void DeviceNetworkConfigurationUpdater::ApplyNetworkPolicy(
base::ListValue* network_configs_onc,
base::DictionaryValue* global_network_config) {
// Ensure this is runnng on the UI thead because we're accessing global data
// to populate the substitutions.
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Expand device-specific placeholders. Note: It is OK that if the serial
// number or Asset ID are empty, the placeholders will be expanded to an empty
// string. This is to be consistent with user policy identity string
// expansions.
std::map<std::string, std::string> substitutions;
substitutions[::onc::substitutes::kDeviceSerialNumber] =
chromeos::system::StatisticsProvider::GetInstance()
->GetEnterpriseMachineID();
substitutions[::onc::substitutes::kDeviceAssetId] =
device_asset_id_fetcher_.Run();
chromeos::VariableExpander variable_expander(std::move(substitutions));
chromeos::onc::ExpandStringsInNetworks(variable_expander,
network_configs_onc);
network_config_handler_->SetPolicy(onc_source_,
std::string() /* no username hash */,
*network_configs_onc,
*global_network_config);
}
void DeviceNetworkConfigurationUpdater::OnDataRoamingSettingChanged() {
chromeos::CrosSettingsProvider::TrustedStatus trusted_status =
cros_settings_->PrepareTrustedValues(base::BindOnce(
&DeviceNetworkConfigurationUpdater::OnDataRoamingSettingChanged,
weak_factory_.GetWeakPtr()));
if (trusted_status == chromeos::CrosSettingsProvider::TEMPORARILY_UNTRUSTED) {
// Return, this function will be called again later by
// PrepareTrustedValues.
return;
}
bool data_roaming_setting = false;
if (trusted_status == chromeos::CrosSettingsProvider::TRUSTED) {
if (!cros_settings_->GetBoolean(chromeos::kSignedDataRoamingEnabled,
&data_roaming_setting)) {
LOG(ERROR) << "Couldn't get device setting "
<< chromeos::kSignedDataRoamingEnabled;
data_roaming_setting = false;
}
} else {
DCHECK_EQ(trusted_status,
chromeos::CrosSettingsProvider::PERMANENTLY_UNTRUSTED);
// Roaming is disabled as we can't determine the correct setting.
}
network_device_handler_->SetCellularAllowRoaming(data_roaming_setting);
}
} // namespace policy
|
๏ปฟ#include "menu.h"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "draw_manager.h"
#include "render.h"
#include "values.h"
#include <mutex>
namespace FGInternal {
namespace GENERAL {
bool hide_corner_text = false;
bool disable_safe_values = false;
};
namespace ESP {
bool correct_doors_enabled = false;
bool correct_path_enabled = false;
bool non_jinxed_players_enabled = false;
bool show_all_platforms_enabled = false;
bool show_player_with_tail = false;
};
namespace MOVEMENT {
bool fly_enabled = false;
float fly_speed = 15.f;
bool speed_enabled = false;
float ms_normal_boost = 12.f;
float ms_carry_boost = 10.f;
float ms_grabbing_boost = 8.f;
bool dive_enabled = false;
float normalDive_speed = 25.f;
float airDive_speed = 15.f;
bool gravity_enabled = false;
float gravity_scale = 2.f;
};
namespace COLLISIONS {
bool stun_collision = false;
bool object_collision = false;
bool player_collision = false;
bool falling_down = false;
};
namespace CARRY {
bool carryDropForce = false;
float carryNormalDropBoost = 0.f;
float carryDiveDropBoost = 0.f;
bool carryTussleChances = false;
};
namespace GRAB {
bool supergrabfeature_enabled = false;
bool grabDetectRadius = false;
float grabDetectRadiusBoost = 10.f;
bool grabCheckDistance = false;
float grabCheckDistanceBoost = 5.f;
bool grabMaxForce = false;
float grabMaxForceBoost = 2.f;
bool grabBreakTime = false;
float grabBreakTimeBoost = 5.f;
float grabBreakTimeJumpBoost = 0.01f;
bool armLength = false;
float armLengthBoost = 3.f;
bool grabCheckPredictionBase = false;
float grabCheckPredictionBaseBoost = 0.5f;
bool grabImmediateVelocityReduction = false;
float grabImmediateVelocityReductionBoost = 1.25f;
bool grabDragDirectionContribution = false;
float grabDragDirectionContributionBoost = 1.25f;
bool grabCooldown = false;
float grabCooldownBoost = 0.01f;
bool grabRegrabDelay = false;
float grabRegrabDelayBoost = 0.01f;
bool grabReleaseRegrabCooldown = false;
float grabReleaseRegrabCooldownBoost = 0.01f;
bool grabBreakAngle = false;
float grabBreakAngleBoost = 100;
bool grabberVelocity = false;
float grabberVelocityBoost = 1.f;
bool grabSeparationForce = false;
float grabSeparationForceBoost = 5.f;
};
};
namespace FGInternalHelper {
bool disable_correct_doors = false;
bool disable_correct_path = false;
bool disable_non_jinxed_players = false;
bool disable_show_all_platforms = false;
bool disable_show_player_with_tail = false;
bool disable_fly = false;
bool disable_speed = false;
bool disable_dive = false;
bool disable_gravity = false;
bool disable_carryDropForce = false;
bool disable_carryDiveDropForce = false;
bool disable_carryTussleChances = false;
bool disable_supergrabfeature = false;
};
namespace menu {
bool general_tab_active = true;
bool esp_tab_active = true;
bool boost_tab_active = true;
bool collisions_tab_active = true;
bool carrying_tab_active = true;
bool grab_tab_active = true;
void push_color_for_button(bool active) {
if (active) {
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{ 222.f / 255.f, 164.f / 255.f, 40.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{ 237.f / 255.f, 177.f / 255.f, 47.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{ 255.f, 194.f / 255.f, 64.f / 255.f, 1.f });
} else {
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{ 54.f / 255.f, 54.f / 255.f, 54.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{ 237.f / 255.f, 177.f / 255.f, 47.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{ 255.f, 194.f / 255.f, 64.f / 255.f, 1.f });
}
}
void draw_button(const char* name, bool& config_key, bool* change_opositive = nullptr) {
push_color_for_button(config_key);
if (ImGui::Button(name, {244, 25}))
{
config_key = !config_key;
if (change_opositive)
*change_opositive = !config_key;
}
ImGui::PopStyleColor(3);
}
void draw_buttonDisabled(const char* name, bool config_key = false, bool* change_opositive = nullptr) {
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{ 54.f / 255.f, 54.f / 255.f, 54.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{ 54.f / 255.f, 54.f / 255.f, 54.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{ 54.f / 255.f, 54.f / 255.f, 54.f / 255.f, 1.f });
if (!ImGui::Button(name, { 244, 25 }))
return;
ImGui::PopStyleColor(3);
}
void draw_slider(const char* name, float* val, float min, float max, const char* display_format = "%.2f") {
if (!display_format)
display_format = "%.2f";
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{ 222.f / 255.f, 164.f / 255.f, 40.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{ 237.f / 255.f, 177.f / 255.f, 47.f / 255.f, 1.f });
ImGui::SetNextItemWidth(244.0f);
ImGui::SliderFloat(name, val, min, max, display_format);
ImGui::PopStyleColor(2);
}
void draw_tab(const char* name, bool& active) {
ImGui::Text(name);
ImGui::SameLine(237);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{ 222.f / 255.f, 164.f / 255.f, 40.f / 255.f, 1.f });
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{ 237.f / 255.f, 177.f / 255.f, 47.f / 255.f, 1.f });
if (ImGui::Button("", { 10, 10 }))
active = !active;
ImGui::PopStyleColor(2);
}
std::once_flag init_style;
void draw() {
std::call_once(init_style, [&]() {
auto& style = ImGui::GetStyle();
style.WindowRounding = 0.f;
style.FrameRounding = 0.f;
style.ItemSpacing = ImVec2(8, 2);
style.WindowPadding = ImVec2(3.f, 3.f);
style.Colors[ImGuiCol_FrameBg] = ImVec4{ 35.f / 255.f, 35.f / 255.f, 35.f / 255.f, 1.f };
style.Colors[ImGuiCol_FrameBgActive] = ImVec4{ 46.f / 255.f, 46.f / 255.f, 46.f / 255.f, 1.f };
style.Colors[ImGuiCol_FrameBgHovered] = ImVec4{ 46.f / 255.f, 46.f / 255.f, 46.f / 255.f, 1.f };
style.Colors[ImGuiCol_SliderGrabActive] = ImVec4{ 222.f / 255.f, 164.f / 255.f, 40.f / 255.f, 1.f };
style.Colors[ImGuiCol_SliderGrab] = ImVec4{ 237.f / 255.f, 177.f / 255.f, 47.f / 255.f, 1.f };
});
ImGui::Begin("general_tab", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar);
ImGui::SetWindowSize({ 250, 0 }, ImGuiCond_Always);
draw_tab(u8"ยป GENERAL TAB ยซ", general_tab_active);
if (general_tab_active) {
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"HOME ยป Hide Corner Menu");
draw_button("Left Sided Menu", FGInternal::GENERAL::hide_corner_text);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"END ยป Unhook Cheat");
draw_buttonDisabled("Kill Cheat Process");
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"DEL ยป Panic Key");
draw_buttonDisabled("Kill Game Process");
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"Unsafe Values ยป 0 - 2137");
draw_button("Disable Safe Values", FGInternal::GENERAL::disable_safe_values);
}
ImGui::End();
ImGui::Begin("visuals_tab", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar);
ImGui::SetWindowSize({ 250, 0 }, ImGuiCond_Always);
draw_tab(u8"ยป VISUALS TAB ยซ", esp_tab_active);
if (esp_tab_active) {
ImGui::Text(u8"F5 ยป Doors Rush");
draw_button("Correct Doors", FGInternal::ESP::correct_doors_enabled, &FGInternalHelper::disable_correct_doors);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F6 ยป Tip Toe");
draw_button("Correct Path", FGInternal::ESP::correct_path_enabled, &FGInternalHelper::disable_correct_path);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F7 ยป Jinxed");
draw_button("Non-Jinxed Players", FGInternal::ESP::non_jinxed_players_enabled, &FGInternalHelper::disable_non_jinxed_players);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F8 ยป Fall Match (Fruits)");
draw_button("All Platforms Visible", FGInternal::ESP::show_all_platforms_enabled, &FGInternalHelper::disable_show_all_platforms);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F9 ยป Grab a Tail (Final)");
draw_button("Player with Tail", FGInternal::ESP::show_player_with_tail, &FGInternalHelper::disable_show_player_with_tail);
}
ImGui::End();
ImGui::Begin("collisions_tab", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar);
ImGui::SetWindowSize({ 250, 0 }, ImGuiCond_Always);
draw_tab(u8"ยป COLLISIONS TAB ยซ", collisions_tab_active);
if (collisions_tab_active) {
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"Stuns/Knockdowns");
draw_button("Disable Stuns/Knockdowns", FGInternal::COLLISIONS::stun_collision);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"Objects Collisions");
draw_button("Disable Objects Collisions", FGInternal::COLLISIONS::object_collision);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"Player to Player Collisions");
draw_button("Disable P2P Collisions", FGInternal::COLLISIONS::player_collision);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"Never Fall Down");
draw_button("Disable Falling Down", FGInternal::COLLISIONS::falling_down);
}
ImGui::End();
ImGui::Begin("movement_tab", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar);
ImGui::SetWindowSize({ 250, 0 }, ImGuiCond_Always);
draw_tab(u8"ยป MOVEMENT TAB ยซ", boost_tab_active);
if (boost_tab_active && !FGInternal::GENERAL::disable_safe_values) {
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F1 ยป [SPACE/SHIFT] ยป Flying Mode");
draw_button("Enable Flying", FGInternal::MOVEMENT::fly_enabled, &FGInternalHelper::disable_fly);
draw_slider("Flying Speed", &FGInternal::MOVEMENT::fly_speed, VALUES::SAFE_VALUES::MOVEMENT::fly_speed_min, VALUES::SAFE_VALUES::MOVEMENT::fly_speed_max);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"F2 ยป [W] ยป Speed Hack");
draw_button("Movement Speed Boost", FGInternal::MOVEMENT::speed_enabled, &FGInternalHelper::disable_speed);
draw_slider("Normal Speed", &FGInternal::MOVEMENT::ms_normal_boost, VALUES::SAFE_VALUES::MOVEMENT::ms_normal_min, VALUES::SAFE_VALUES::MOVEMENT::ms_normal_max);
draw_slider("Carrying Speed", &FGInternal::MOVEMENT::ms_carry_boost, VALUES::SAFE_VALUES::MOVEMENT::ms_carry_min, VALUES::SAFE_VALUES::MOVEMENT::ms_carry_max);
draw_slider("Grabbing Speed", &FGInternal::MOVEMENT::ms_grabbing_boost, VALUES::SAFE_VALUES::MOVEMENT::ms_grabbing_min, VALUES::SAFE_VALUES::MOVEMENT::ms_grabbing_max);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"F3 ยป [CTRL/RMB] ยป Dive");
draw_button("Dive Boost", FGInternal::MOVEMENT::dive_enabled, &FGInternalHelper::disable_dive);
draw_slider("Normal Dive", &FGInternal::MOVEMENT::normalDive_speed, VALUES::SAFE_VALUES::MOVEMENT::normalDive_speed_min, VALUES::SAFE_VALUES::MOVEMENT::normalDive_speed_max);
draw_slider("Air Dive", &FGInternal::MOVEMENT::airDive_speed, VALUES::SAFE_VALUES::MOVEMENT::airDive_speed_min, VALUES::SAFE_VALUES::MOVEMENT::airDive_speed_max);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"F4 ยป [SPACE] ยป Gravitation");
ImGui::Text(u8"Lower Value - Lower Gravitation");
draw_button("Gravity Scale", FGInternal::MOVEMENT::gravity_enabled, &FGInternalHelper::disable_gravity);
draw_slider("Gravity Boost", &FGInternal::MOVEMENT::gravity_scale, VALUES::SAFE_VALUES::MOVEMENT::gravity_scale_min, VALUES::SAFE_VALUES::MOVEMENT::gravity_scale_max);
} else if (boost_tab_active && FGInternal::GENERAL::disable_safe_values) {
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F1 ยป [SPACE/SHIFT] ยป Flying Mode");
draw_button("Enable Flying", FGInternal::MOVEMENT::fly_enabled, &FGInternalHelper::disable_fly);
draw_slider("Flying Speed", &FGInternal::MOVEMENT::fly_speed, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"F2 ยป [W] ยป Speed Hack");
draw_button("Movement Speed Boost", FGInternal::MOVEMENT::speed_enabled, &FGInternalHelper::disable_speed);
draw_slider("Normal Speed", &FGInternal::MOVEMENT::ms_normal_boost, 0, 2137);
draw_slider("Carrying Speed", &FGInternal::MOVEMENT::ms_carry_boost, 0, 2137);
draw_slider("Grabbing Speed", &FGInternal::MOVEMENT::ms_grabbing_boost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"F3 ยป [CTRL/RMB] ยป Dive");
draw_button("Dive Boost", FGInternal::MOVEMENT::dive_enabled, &FGInternalHelper::disable_dive);
draw_slider("Normal Dive", &FGInternal::MOVEMENT::normalDive_speed, 0, 2137);
draw_slider("Air Dive", &FGInternal::MOVEMENT::airDive_speed, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 5.0f));
ImGui::Text(u8"F4 ยป [SPACE] ยป Gravitation");
draw_button(" Gravity Scale", FGInternal::MOVEMENT::gravity_enabled, &FGInternalHelper::disable_gravity);
draw_slider("Gravitation", &FGInternal::MOVEMENT::gravity_scale, 0, 10);
}
ImGui::End();
ImGui::Begin("carrying_tab", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar);
ImGui::SetWindowSize({ 250, 0 }, ImGuiCond_Always);
draw_tab(u8"ยป CARRYING ITEMS TAB ยซ", carrying_tab_active);
if (carrying_tab_active && !FGInternal::GENERAL::disable_safe_values) {
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F10 ยป [SHIFT] ยป Drop Boost");
draw_button("Item Drop", FGInternal::CARRY::carryDropForce, &FGInternalHelper::disable_carryDropForce);
draw_slider("Normal Drop", &FGInternal::CARRY::carryNormalDropBoost, VALUES::SAFE_VALUES::CARRY::carryNormalDropForce_min, VALUES::SAFE_VALUES::CARRY::carryNormalDropForce_max);
draw_slider("Dive Drop", &FGInternal::CARRY::carryDiveDropBoost, VALUES::SAFE_VALUES::CARRY::carryDiveDropForce_min, VALUES::SAFE_VALUES::CARRY::carryDiveDropForce_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F11 ยป Tussle When Grabbed");
draw_button("Enable Equal Chances", FGInternal::CARRY::carryTussleChances, &FGInternalHelper::disable_carryTussleChances);
}
else if (carrying_tab_active && FGInternal::GENERAL::disable_safe_values) {
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F10 ยป [SHIFT] ยป Drop Boost");
draw_button("Item Drop", FGInternal::CARRY::carryDropForce, &FGInternalHelper::disable_carryDropForce);
draw_slider("Normal Drop", &FGInternal::CARRY::carryNormalDropBoost, 0, 2137);
draw_slider("Dive Drop", &FGInternal::CARRY::carryDiveDropBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
ImGui::Text(u8"F11 ยป Tussle When Grabbed");
draw_button("Enable Equal Chances", FGInternal::CARRY::carryTussleChances, &FGInternalHelper::disable_carryTussleChances);
}
ImGui::End();
ImGui::Begin("grab_tab", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar);
ImGui::SetWindowSize({ 250, 0 }, ImGuiCond_Always);
draw_tab(u8"ยป GRAB FEATURES TAB ยซ", grab_tab_active);
if (grab_tab_active && !FGInternal::GENERAL::disable_safe_values) {
if (!FGInternal::GRAB::grabDetectRadius && !FGInternal::GRAB::grabCheckDistance && !FGInternal::GRAB::grabMaxForce
&& !FGInternal::GRAB::grabBreakTime && !FGInternal::GRAB::armLength && !FGInternal::GRAB::grabCheckPredictionBase
&& !FGInternal::GRAB::grabImmediateVelocityReduction && !FGInternal::GRAB::grabDragDirectionContribution
&& !FGInternal::GRAB::grabCooldown && !FGInternal::GRAB::grabRegrabDelay
&& !FGInternal::GRAB::grabReleaseRegrabCooldown && !FGInternal::GRAB::grabBreakAngle) {
ImGui::Dummy(ImVec2(0.0f, 7.75f));
draw_button(u8"F12 ยป Super Grab Feature", FGInternal::GRAB::supergrabfeature_enabled, &FGInternalHelper::disable_supergrabfeature);
ImGui::Dummy(ImVec2(0.0f, 7.75f));
}
else {
ImGui::Text(u8"Disable all minor functions to");
ImGui::Text(u8"use Super Grab, which will remain");
ImGui::Text(u8"hidden to prevent bugs.");
}
if (!FGInternal::GRAB::supergrabfeature_enabled) {
draw_button("Grab Detect Radius", FGInternal::GRAB::grabDetectRadius);
draw_slider("Radius", &FGInternal::GRAB::grabDetectRadiusBoost, VALUES::SAFE_VALUES::GRAB::grabDetectRadius_min, VALUES::SAFE_VALUES::GRAB::grabDetectRadius_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Check Distance", FGInternal::GRAB::grabCheckDistance);
draw_slider("Distance", &FGInternal::GRAB::grabCheckDistanceBoost, VALUES::SAFE_VALUES::GRAB::grabCheckDistance_min, VALUES::SAFE_VALUES::GRAB::grabCheckDistance_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Max Force", FGInternal::GRAB::grabMaxForce);
draw_slider("Force", &FGInternal::GRAB::grabMaxForceBoost, VALUES::SAFE_VALUES::GRAB::grabMaxForce_min, VALUES::SAFE_VALUES::GRAB::grabMaxForce_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Break Time", FGInternal::GRAB::grabBreakTime);
draw_slider("Normal Break", &FGInternal::GRAB::grabBreakTimeBoost, VALUES::SAFE_VALUES::GRAB::grabBreakTime_min, VALUES::SAFE_VALUES::GRAB::grabBreakTime_max);
draw_slider("Jump Break", &FGInternal::GRAB::grabBreakTimeJumpBoost, VALUES::SAFE_VALUES::GRAB::grabBreakTimeJump_min, VALUES::SAFE_VALUES::GRAB::grabBreakTimeJump_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Arm Length", FGInternal::GRAB::armLength);
draw_slider("Boost", &FGInternal::GRAB::armLengthBoost, VALUES::SAFE_VALUES::GRAB::armLength_min, VALUES::SAFE_VALUES::GRAB::armLength_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Check Prediction", FGInternal::GRAB::grabCheckPredictionBase);
draw_slider("Prediction Boost", &FGInternal::GRAB::grabCheckPredictionBaseBoost, VALUES::SAFE_VALUES::GRAB::grabCheckPredictionBase_min, VALUES::SAFE_VALUES::GRAB::grabCheckPredictionBase_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Velocity Reduction", FGInternal::GRAB::grabImmediateVelocityReduction);
draw_slider("Reduction", &FGInternal::GRAB::grabImmediateVelocityReductionBoost, VALUES::SAFE_VALUES::GRAB::grabImmediateVelocityReduction_min, VALUES::SAFE_VALUES::GRAB::grabImmediateVelocityReduction_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Direction Contribution", FGInternal::GRAB::grabDragDirectionContribution);
draw_slider("Drag Boost", &FGInternal::GRAB::grabDragDirectionContributionBoost, VALUES::SAFE_VALUES::GRAB::grabDragDirectionContribution_min, VALUES::SAFE_VALUES::GRAB::grabDragDirectionContribution_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Cooldown", FGInternal::GRAB::grabCooldown);
draw_slider("Cooldown", &FGInternal::GRAB::grabCooldownBoost, VALUES::SAFE_VALUES::GRAB::grabCooldown_min, VALUES::SAFE_VALUES::GRAB::grabCooldown_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Regrab Delay", FGInternal::GRAB::grabRegrabDelay);
draw_slider("Delay", &FGInternal::GRAB::grabRegrabDelayBoost, VALUES::SAFE_VALUES::GRAB::grabRegrabDelay_min, VALUES::SAFE_VALUES::GRAB::grabRegrabDelay_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Release Regrab Cooldown", FGInternal::GRAB::grabReleaseRegrabCooldown);
draw_slider("Regrab Cooldown", &FGInternal::GRAB::grabReleaseRegrabCooldownBoost, VALUES::SAFE_VALUES::GRAB::grabReleaseRegrabCooldown_min, VALUES::SAFE_VALUES::GRAB::grabReleaseRegrabCooldown_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Break Grab Angle", FGInternal::GRAB::grabBreakAngle);
draw_slider("Angle", &FGInternal::GRAB::grabBreakAngleBoost, VALUES::SAFE_VALUES::GRAB::grabBreakAngle_min, VALUES::SAFE_VALUES::GRAB::grabBreakAngle_max);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Separation Force", FGInternal::GRAB::grabSeparationForce);
draw_slider("Separation Force", &FGInternal::GRAB::grabSeparationForceBoost, VALUES::SAFE_VALUES::GRAB::grabSeparationForce_min, VALUES::SAFE_VALUES::GRAB::grabSeparationForce_max);
} else {
ImGui::Text(u8"Super Grab uses all of the");
ImGui::Text(u8"following features that will");
ImGui::Text(u8"be hidden until you disable");
ImGui::Text(u8"this feature to avoid bugs.");
}
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Increase Grabber Velocity", FGInternal::GRAB::grabberVelocity);
draw_slider("Grabber Velocity", &FGInternal::GRAB::grabberVelocityBoost, VALUES::SAFE_VALUES::GRAB::grabberVelocity_min, VALUES::SAFE_VALUES::GRAB::grabberVelocity_max);
} else if (grab_tab_active && FGInternal::GENERAL::disable_safe_values) {
if (!FGInternal::GRAB::grabDetectRadius && !FGInternal::GRAB::grabCheckDistance && !FGInternal::GRAB::grabMaxForce
&& !FGInternal::GRAB::grabBreakTime && !FGInternal::GRAB::armLength && !FGInternal::GRAB::grabCheckPredictionBase
&& !FGInternal::GRAB::grabImmediateVelocityReduction && !FGInternal::GRAB::grabDragDirectionContribution
&& !FGInternal::GRAB::grabCooldown && !FGInternal::GRAB::grabRegrabDelay
&& !FGInternal::GRAB::grabReleaseRegrabCooldown && !FGInternal::GRAB::grabBreakAngle) {
ImGui::Dummy(ImVec2(0.0f, 7.75f));
draw_button(u8"F12 ยป Super Grab Feature", FGInternal::GRAB::supergrabfeature_enabled, &FGInternalHelper::disable_supergrabfeature);
ImGui::Dummy(ImVec2(0.0f, 7.75f));
} else {
ImGui::Text(u8"Disable all minor functions to");
ImGui::Text(u8"use Super Grab, which will remain");
ImGui::Text(u8"hidden to prevent bugs.");
}
if (!FGInternal::GRAB::supergrabfeature_enabled) {
draw_button("Grab Detect Radius", FGInternal::GRAB::grabDetectRadius);
draw_slider("Radius", &FGInternal::GRAB::grabDetectRadiusBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Check Distance", FGInternal::GRAB::grabCheckDistance);
draw_slider("Distance", &FGInternal::GRAB::grabCheckDistanceBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Max Force", FGInternal::GRAB::grabMaxForce);
draw_slider("Force", &FGInternal::GRAB::grabMaxForceBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Break Time", FGInternal::GRAB::grabBreakTime);
draw_slider("Normal Break", &FGInternal::GRAB::grabBreakTimeBoost, 0, 2137);
draw_slider("Jump Break", &FGInternal::GRAB::grabBreakTimeJumpBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Arm Length", FGInternal::GRAB::armLength);
draw_slider("Boost", &FGInternal::GRAB::armLengthBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Check Prediction", FGInternal::GRAB::grabCheckPredictionBase);
draw_slider("Prediction Boost", &FGInternal::GRAB::grabCheckPredictionBaseBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Velocity Reduction", FGInternal::GRAB::grabImmediateVelocityReduction);
draw_slider("Reduction", &FGInternal::GRAB::grabImmediateVelocityReductionBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Direction Contribution", FGInternal::GRAB::grabDragDirectionContribution);
draw_slider("Drag Boost", &FGInternal::GRAB::grabDragDirectionContributionBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Cooldown", FGInternal::GRAB::grabCooldown);
draw_slider("Cooldown", &FGInternal::GRAB::grabCooldownBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Regrab Delay", FGInternal::GRAB::grabRegrabDelay);
draw_slider("Delay", &FGInternal::GRAB::grabRegrabDelayBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Release Regrab Cooldown", FGInternal::GRAB::grabReleaseRegrabCooldown);
draw_slider("Regrab Cooldown", &FGInternal::GRAB::grabReleaseRegrabCooldownBoost, 0, 2137);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Break Grab Angle", FGInternal::GRAB::grabBreakAngle);
draw_slider("Angle", &FGInternal::GRAB::grabBreakAngleBoost, 0, 360);
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Grab Separation Force", FGInternal::GRAB::grabSeparationForce);
draw_slider("Separation Force", &FGInternal::GRAB::grabSeparationForceBoost, 0, 2137);
} else {
ImGui::Text(u8"Super Grab uses all of the");
ImGui::Text(u8"following features that will");
ImGui::Text(u8"be hidden until you disable");
ImGui::Text(u8"this feature to avoid bugs.");
}
ImGui::Dummy(ImVec2(0.0f, 2.5f));
draw_button("Increase Grabber Velocity", FGInternal::GRAB::grabberVelocity);
draw_slider("Grabber Velocity", &FGInternal::GRAB::grabberVelocityBoost, 0, 2137);
}
ImGui::End();
}
bool OldKeysDown[512];
float OldNavInputs[ImGuiNavInput_COUNT];
void update_keys() {
auto io = ImGui::GetIO();
if ((io.KeysDown[VK_INSERT] && !OldKeysDown[VK_INSERT]) ||
(io.NavInputs[ImGuiNavInput_RightThumb] > 0.f && OldNavInputs[ImGuiNavInput_RightThumb] == 0.f)) {
render::menu_is_open = !render::menu_is_open;
}
if (render::menu_is_open) {
auto context = ImGui::GetCurrentContext();
if (context->NavWindow) {
if (context->Windows.Size > 1) {
int32_t move_window_direction = -1;
if (io.NavInputs[ImGuiNavInput_FocusPrev] > 0.f && OldNavInputs[ImGuiNavInput_FocusPrev] == 0.f)
move_window_direction = 0;
else if (io.NavInputs[ImGuiNavInput_FocusNext] > 0.f && OldNavInputs[ImGuiNavInput_FocusNext] == 0.f)
move_window_direction = 1;
if (move_window_direction != -1) {
ImGuiWindow* new_window = nullptr;
for (auto window : context->Windows) {
if (window == context->NavWindow || window->Hidden || window->IsFallbackWindow)
continue;
if (!strcmp(window->Name, "BackBuffer"))
continue;
if (move_window_direction == 0) {
if (window->Pos.x <= context->NavWindow->Pos.x)
if (!new_window || window->Pos.x > new_window->Pos.x)
new_window = window;
}
else {
if (window->Pos.x >= context->NavWindow->Pos.x)
if (!new_window || window->Pos.x < new_window->Pos.x)
new_window = window;
}
}
if (new_window) {
ImGui::FocusWindow(new_window);
}
}
}
}
}
if ((io.KeysDown[VK_F1] && !OldKeysDown[VK_F1]) || (io.NavInputs[ImGuiNavInput_Input] && !OldNavInputs[ImGuiNavInput_Input])) {
FGInternal::MOVEMENT::fly_enabled = !FGInternal::MOVEMENT::fly_enabled;
FGInternalHelper::disable_fly = !FGInternal::MOVEMENT::fly_enabled;
}
if (io.KeysDown[VK_F2] && !OldKeysDown[VK_F2]) {
FGInternal::MOVEMENT::speed_enabled = !FGInternal::MOVEMENT::speed_enabled;
FGInternalHelper::disable_speed = !FGInternal::MOVEMENT::speed_enabled;
}
if (io.KeysDown[VK_F3] && !OldKeysDown[VK_F3]) {
FGInternal::MOVEMENT::dive_enabled = !FGInternal::MOVEMENT::dive_enabled;
FGInternalHelper::disable_dive = !FGInternal::MOVEMENT::dive_enabled;
}
if (io.KeysDown[VK_F4] && !OldKeysDown[VK_F4]) {
FGInternal::MOVEMENT::gravity_enabled = !FGInternal::MOVEMENT::gravity_enabled;
FGInternalHelper::disable_gravity = !FGInternal::MOVEMENT::gravity_enabled;
}
if (io.KeysDown[VK_F5] && !OldKeysDown[VK_F5]) {
FGInternal::ESP::correct_doors_enabled = !FGInternal::ESP::correct_doors_enabled;
FGInternalHelper::disable_correct_doors = !FGInternal::ESP::correct_doors_enabled;
}
if (io.KeysDown[VK_F6] && !OldKeysDown[VK_F6]) {
FGInternal::ESP::correct_path_enabled = !FGInternal::ESP::correct_path_enabled;
FGInternalHelper::disable_correct_path = !FGInternal::ESP::correct_path_enabled;
}
if (io.KeysDown[VK_F7] && !OldKeysDown[VK_F7]) {
FGInternal::ESP::non_jinxed_players_enabled = !FGInternal::ESP::non_jinxed_players_enabled;
FGInternalHelper::disable_non_jinxed_players = !FGInternal::ESP::non_jinxed_players_enabled;
}
if (io.KeysDown[VK_F8] && !OldKeysDown[VK_F8]) {
FGInternal::ESP::show_all_platforms_enabled = !FGInternal::ESP::show_all_platforms_enabled;
FGInternalHelper::disable_show_all_platforms = !FGInternal::ESP::show_all_platforms_enabled;
}
if (io.KeysDown[VK_F9] && !OldKeysDown[VK_F9]) {
FGInternal::ESP::show_player_with_tail = !FGInternal::ESP::show_player_with_tail;
FGInternalHelper::disable_show_player_with_tail = !FGInternal::ESP::show_player_with_tail;
}
if (io.KeysDown[VK_F10] && !OldKeysDown[VK_F10]) {
FGInternal::CARRY::carryDropForce = !FGInternal::CARRY::carryDropForce;
FGInternalHelper::disable_carryDropForce = !FGInternal::CARRY::carryDropForce;
}
if (io.KeysDown[VK_F11] && !OldKeysDown[VK_F11]) {
FGInternal::CARRY::carryTussleChances = !FGInternal::CARRY::carryTussleChances;
FGInternalHelper::disable_carryTussleChances = !FGInternal::CARRY::carryTussleChances;
}
if (io.KeysDown[VK_F12] && !OldKeysDown[VK_F12])
FGInternal::GRAB::supergrabfeature_enabled = !FGInternal::GRAB::supergrabfeature_enabled;
FGInternalHelper::disable_supergrabfeature = !FGInternal::GRAB::supergrabfeature_enabled;
if (io.KeysDown[VK_HOME] && !OldKeysDown[VK_HOME]) {
FGInternal::GENERAL::hide_corner_text = !FGInternal::GENERAL::hide_corner_text;
}
if (io.NavInputs[ImGuiNavInput_FocusPrev] > 0.f) {
FGInternal::MOVEMENT::speed_enabled = true;
FGInternalHelper::disable_speed = false;
} else if (io.NavInputs[ImGuiNavInput_FocusPrev] == 0.f && OldNavInputs[ImGuiNavInput_FocusPrev] > 0.f) {
FGInternal::MOVEMENT::speed_enabled = false;
FGInternalHelper::disable_speed = true;
}
memcpy(OldKeysDown, io.KeysDown, 512 * sizeof(bool));
memcpy(OldNavInputs, io.NavInputs, ImGuiNavInput_COUNT * sizeof(float));
}
void update_indicators() {
auto text_size = draw_manager::calc_text_size(12, "TAKE");
auto y = float(15);
if (!FGInternal::GENERAL::hide_corner_text) {
draw_manager::add_text_on_screen({ 5, y }, 0xFF232323, 14, "FG Internal");
y += text_size.y + 4.f;
draw_manager::add_text_on_screen({ 5, y }, 0xFF363636, 12, u8"ยป github.com/xTeJk ยซ");
y += text_size.y + 3.f;
draw_manager::add_text_on_screen({ 5, y }, 0xFF363636, 12, u8"ยป INSERT ยป Open Cheat Menu");
y += text_size.y + 3.f;
draw_manager::add_text_on_screen({ 5, y }, 0xFF363636, 12, u8"ยป HOME ยป Hide Corner Text");
y += text_size.y + 3.f;
}
}
};
|
/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements the CHIP Device Interface that is used by
* applications to interact with the CHIP stack
*
*/
#include <stdlib.h>
#include "CHIPDeviceManager.h"
#include <setup_payload/SetupPayload.h>
#include <support/CHIPMem.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
namespace chip {
namespace DeviceManager {
using namespace ::chip::DeviceLayer;
void CHIPDeviceManager::CommonDeviceEventHandler(const ChipDeviceEvent * event, intptr_t arg)
{
CHIPDeviceManagerCallbacks * cb = reinterpret_cast<CHIPDeviceManagerCallbacks *>(arg);
if (cb != nullptr)
{
cb->DeviceEventCallback(event, reinterpret_cast<intptr_t>(cb));
}
}
/**
*
*/
CHIP_ERROR CHIPDeviceManager::Init(CHIPDeviceManagerCallbacks * cb)
{
CHIP_ERROR err;
mCB = cb;
// Initialize the CHIP stack.
err = PlatformMgr().InitChipStack();
SuccessOrExit(err);
switch (static_cast<RendezvousInformationFlags>(CONFIG_RENDEZVOUS_MODE))
{
case RendezvousInformationFlags::kBLE:
ConnectivityMgr().SetBLEAdvertisingEnabled(ConnectivityManager::kCHIPoBLEServiceMode_Enabled);
break;
case RendezvousInformationFlags::kWiFi:
ConnectivityMgr().SetBLEAdvertisingEnabled(ConnectivityManager::kCHIPoBLEServiceMode_Disabled);
ConnectivityMgr().SetWiFiAPMode(ConnectivityManager::kWiFiAPMode_Enabled);
break;
case RendezvousInformationFlags::kNone:
// If rendezvous is bypassed, enable SoftAP so that the device can still
// be communicated with via its SoftAP as needed.
ConnectivityMgr().SetWiFiAPMode(ConnectivityManager::kWiFiAPMode_Enabled);
break;
default:
break;
}
err = Platform::MemoryInit();
SuccessOrExit(err);
// Register a function to receive events from the CHIP device layer. Note that calls to
// this function will happen on the CHIP event loop thread, not the app_main thread.
PlatformMgr().AddEventHandler(CHIPDeviceManager::CommonDeviceEventHandler, reinterpret_cast<intptr_t>(cb));
// Start a task to run the CHIP Device event loop.
err = PlatformMgr().StartEventLoopTask();
SuccessOrExit(err);
exit:
return err;
}
void emberAfPostAttributeChangeCallback(uint8_t endpoint, EmberAfClusterId clusterId, EmberAfAttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t type, uint8_t size, uint8_t * value)
{
CHIPDeviceManagerCallbacks * cb = CHIPDeviceManager::GetInstance().GetCHIPDeviceManagerCallbacks();
if (cb != nullptr)
{
cb->PostAttributeChangeCallback(endpoint, clusterId, attributeId, mask, manufacturerCode, type, size, value);
}
}
} // namespace DeviceManager
} // namespace chip
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
#include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Type namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Forward declaring type: HAPI_Viewport
struct HAPI_Viewport;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(HoudiniEngineUnity::HAPI_Viewport, "HoudiniEngineUnity", "HAPI_Viewport");
// Type namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Size: 0x14
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: HoudiniEngineUnity.HAPI_Viewport
// [TokenAttribute] Offset: FFFFFFFF
struct HAPI_Viewport/*, public System::ValueType*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// public System.Single[] position
// Size: 0x8
// Offset: 0x0
::ArrayW<float> position;
// Field size check
static_assert(sizeof(::ArrayW<float>) == 0x8);
// public System.Single[] rotationQuaternion
// Size: 0x8
// Offset: 0x8
::ArrayW<float> rotationQuaternion;
// Field size check
static_assert(sizeof(::ArrayW<float>) == 0x8);
// public System.Single offset
// Size: 0x4
// Offset: 0x10
float offset;
// Field size check
static_assert(sizeof(float) == 0x4);
public:
// Creating value type constructor for type: HAPI_Viewport
constexpr HAPI_Viewport(::ArrayW<float> position_ = ::ArrayW<float>(nullptr), ::ArrayW<float> rotationQuaternion_ = ::ArrayW<float>(nullptr), float offset_ = {}) noexcept : position{position_}, rotationQuaternion{rotationQuaternion_}, offset{offset_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Get instance field reference: public System.Single[] position
::ArrayW<float>& dyn_position();
// Get instance field reference: public System.Single[] rotationQuaternion
::ArrayW<float>& dyn_rotationQuaternion();
// Get instance field reference: public System.Single offset
float& dyn_offset();
// public System.Void .ctor(System.Boolean initializeFields)
// Offset: 0x141E878
HAPI_Viewport(bool initializeFields);
// public System.Void Init()
// Offset: 0x141E908
void Init();
}; // HoudiniEngineUnity.HAPI_Viewport
#pragma pack(pop)
static check_size<sizeof(HAPI_Viewport), 16 + sizeof(float)> __HoudiniEngineUnity_HAPI_ViewportSizeCheck;
static_assert(sizeof(HAPI_Viewport) == 0x14);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: HoudiniEngineUnity::HAPI_Viewport::HAPI_Viewport
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: HoudiniEngineUnity::HAPI_Viewport::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HoudiniEngineUnity::HAPI_Viewport::*)()>(&HoudiniEngineUnity::HAPI_Viewport::Init)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HAPI_Viewport), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
|
#include <cstring>
#include <stdio.h>
char msg[2][200] = {
"Escaped again! More 2D grid problems!",
"Party time! Let's find a restaurant!"
};
bool rs[10001], cs[10001];
int main() {
int n, m, k, x, y, cse=1;
while (scanf("%d%d%d", &n, &m, &k)==3 && (n||m||k)) {
memset(rs, 0, n);
memset(cs, 0, m);
for (int i=0; i<k; ++i) {
scanf("%d%d", &x, &y);
rs[x] = 1;
cs[y] = 1;
}
scanf("%d%d", &x, &y);
printf("Case %d: %s\n", cse++, msg[
(rs[x] || cs[y]) &&
(rs[x] || (!y || cs[y-1]) && (y==m-1 || cs[y+1])) &&
(cs[y] || (!x || rs[x-1]) && (x==n-1 || rs[x+1]))
]);
}
}
|
/**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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.
*/
// Trough CSP - empirical model
#include "core.h"
#include "tckernel.h"
// for adjustment factors
#include "common.h"
static var_info _cm_vtab_tcstrough_empirical[] = {
/* VARTYPE DATATYPE NAME LABEL UNITS META GROUP REQUIRED_IF CONSTRAINTS UI_HINTS */
{ SSC_INPUT, SSC_STRING, "file_name", "local weather file path", "", "", "Weather", "*", "LOCAL_FILE", "" },
{ SSC_INPUT, SSC_NUMBER, "track_mode", "Tracking mode", "", "", "Weather", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "tilt", "Tilt angle of surface/axis", "", "", "Weather", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "azimuth", "Azimuth angle of surface/axis", "", "", "Weather", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "system_capacity", "Nameplate capacity", "kW", "", "trough", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "SolarAz", "Solar azimuth angle reported by the Type15 weather file", "deg", "", "solarfield", "*", "", "" },
// TOU
{ SSC_INPUT, SSC_MATRIX, "weekday_schedule", "12x24 Time of Use Values for week days", "", "", "tou_translator", "*", "", "" },
{ SSC_INPUT, SSC_MATRIX, "weekend_schedule", "12x24 Time of Use Values for week end days", "", "", "tou_translator", "*", "", "" },
// solar field
// { SSC_INPUT, SSC_NUMBER, "Site_Lat", "Latitude of Solar Plant Site", "deg", "", "solarfield", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "Site_LongD", "Longitude of Solar Plant Site", "deg", "", "solarfield", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "SHIFT", "Longitude of Standard Meridian", "deg", "", "solarfield", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "LU_Fl", "Fluid property file logical unit", "", "", "solarfield", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "LuFlEr", "Fluid property error file logical unit", "", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "i_SfTi", "Solar Field HTF inlet Temperature (if -999, calculated)", "C", "", "solarfield", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "ColType", "Collector Type", "", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfPipeHl300", "Solar field piping heat loss at design", "W/m2", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfPipeHl1", "Solar field piping heat loss at reduced temp. - linear term", "C^(-1)", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfPipeHl2", "Solar field piping heat loss at reduced temp. - quadratic term", "C^(-2)", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfPipeHl3", "Solar field piping heat loss at reduced temp. - cubic term", "C^(-3)", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "Stow_Angle", "Night-Time Trough Stow Angle", "deg", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "DepAngle", "Deployment Angle", "deg", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "Distance_SCA", "Distance between SCAs in Row", "m", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "Row_Distance", "Distance between Rows of SCAs", "m", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "NumScas", "Number of SCAs per Row", "", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "Solar_Field_Area", "Solar Field Area", "m2", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "Solar_Field_Mult", "Solar Field Multiple", "", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfInTempD", "Solar Field Design Inlet Temperature", "C", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfOutTempD", "Solar Field Design Outlet Temperature", "C", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "MinHtfTemp", "Minimum Heat Transfer Fluid Temperature", "C", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HtfGalArea", "HTF Fluids in Gallons per Field Area", "gal/m2", "", "solarfield", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "ColTilt", "Collector Axis Tilt", "deg", "", "solarfield", "*", "", "" },
// { SSC_INPUT, SSC_NUMBER, "ColAz", "Azimuthal Angle of Collector Axis", "deg", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SFTempInit", "Solar Field Initial Temperature", "C", "", "solarfield", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HTFFluid", "Type of Heat Transfer Fluid used", "", "", "solarfield", "*", "INTEGER", "" },
// SCA
{ SSC_INPUT, SSC_NUMBER, "IamF0", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "IamF1", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "IamF2", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "Ave_Focal_Length", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "ScaLen", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SCA_aper", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfAvail", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TrkTwstErr", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "GeoAcc", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "MirRef", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "MirCln", "Label", "", "", "sca", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "ConcFac", "Label", "", "", "sca", "*", "", "" },
// HCE
{ SSC_INPUT, SSC_NUMBER, "NumHCETypes", "Number of HCE types", "", "", "hce", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_ARRAY, "HCEtype", "Number indicating the receiver type", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCEFrac", "Fraction of field that is this type of HCE", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCEdust", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCEBelShad", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCEEnvTrans", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCEabs", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCEmisc", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "PerfFac", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "RefMirrAper", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCE_A0", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCE_A1", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCE_A2", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCE_A3", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCE_A4", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCE_A5", "label", "", "", "hce", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "HCE_A6", "label", "", "", "hce", "*", "", "" },
// powerblock
{ SSC_INPUT, SSC_NUMBER, "TurbOutG", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TurbEffG", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "PTTMAX", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "PTTMIN", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "MaxGrOut", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "MinGrOut", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TurSUE", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "T2EPLF0", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "T2EPLF1", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "T2EPLF2", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "T2EPLF3", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "T2EPLF4", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "E2TPLF0", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "E2TPLF1", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "E2TPLF2", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "E2TPLF3", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "E2TPLF4", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TempCorrF", "Temp Correction Mode (0=wetbulb 1=drybulb basis)", "", "", "pwrb", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "TempCorr0", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TempCorr1", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TempCorr2", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TempCorr3", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TempCorr4", "Label", "", "", "pwrb", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "LHVBoilEff", "Label", "", "", "pwrb", "*", "", "" },
// thermal energy storage
{ SSC_INPUT, SSC_NUMBER, "TurTesEffAdj", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TurTesOutAdj", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TnkHL", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "PTSmax", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "PFSmax", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "TSHOURS", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "NUMTOU", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_MATRIX, "TSLogic", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_ARRAY, "FossilFill", "Label", "", "", "tes", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "E_tes_ini", "Initial TES energy - fraction of max", "", "", "tes", "*", "", "" },
//{ SSC_INPUT, SSC_NUMBER, "TimeOfDay", "Label", "", "", "tes", "*", "", "" },
// parasitics
{ SSC_INPUT, SSC_NUMBER, "SfPar", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "SfParPF", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "ChtfPar", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "ChtfParPF", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CHTFParF0", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CHTFParF1", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CHTFParF2", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "AntiFrPar", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "BOPPar", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "BOPParPF", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "BOPParF0", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "BOPParF1", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "BOPParF2", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CtOpF", "Label", "", "", "parasitic", "*", "INTEGER", "" },
{ SSC_INPUT, SSC_NUMBER, "CtPar", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CtParPF", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CtParF0", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CtParF1", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "CtParF2", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HtrPar", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HtrParPF", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HtrParF0", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HtrParF1", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HtrParF2", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HhtfPar", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HhtfParPF", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HhtfParF0", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HhtfParF1", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "HhtfParF2", "Label", "", "", "parasitic", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "PbFixPar", "Label", "", "", "parasitic", "*", "", "" },
// OUTPUTS
// The names of the output variables should match the parameter names for the TCS units in order to signal to the TCS kernel to store the values by timestep
// VARTYPE DATATYPE NAME LABEL UNITS META GROUP REQUIRED_IF CONSTRAINTS UI_HINTS
// weather file reader
{ SSC_OUTPUT, SSC_ARRAY, "month", "Resource Month", "", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "hour", "Resource Hour of Day", "", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "solazi", "Resource Solar Azimuth", "deg", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "solzen", "Resource Solar Zenith", "deg", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "beam", "Resource Beam normal irradiance", "W/m2", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "tdry", "Resource Dry bulb temperature", "C", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "twet", "Resource Wet bulb temperature", "C", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "wspd", "Resource Wind Speed", "m/s", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "pres", "Resource Pressure", "mbar", "", "weather", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "tou_value", "Resource time-of-use value", "", "", "tou", "*", "LENGTH=8760", "" },
// type 805 - solar field
{ SSC_OUTPUT, SSC_ARRAY, "TrackAngle", "Field collector tracking angle", "deg", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Theta", "Field collector solar incidence angle", "deg", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "CosTheta", "Field collector cosine efficiency", "", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "IAM", "Field collector incidence angle modifier", "", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "RowShadow", "Field collector row shadowing loss", "", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EndLoss", "Field collector optical end loss", "", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QnipCosTh", "Field collector DNI-cosine product", "W/m2", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Ftrack", "Field collector fraction of time period tracking", "", "", "other", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "ColEff", "Field collector thermal and optical efficiency", "", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Qdni", "Field thermal power total incident", "MWt", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Qsfnipcosth", "Field thermal power incident after cosine", "MWt", "", "type_805", "*", "LENGTH=8760", "" },
//{ SSC_OUTPUT, SSC_ARRAY, "Qabs", "Energy absorbed by solar field before th. loss, per unit area", "W/m2", "", "type_805", "*", "LENGTH=8760", "" },
//{ SSC_OUTPUT, SSC_ARRAY, "Qcol", "Energy delivered by the solar field, per unit area", "W/m2", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QsfAbs", "Field thermal power absorbed", "MWt", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "RecHl", "Field thermal power receiver heat loss", "kJ/hr-m2", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QsfHceHL", "Field thermal power receiver total loss", "MWt", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QsfPipeHL", "Field thermal power pipe losses", "MWt", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Qsf", "Field thermal power total produced", "MWt", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QsfWarmup", "Field HTF energy inertial (consumed)", "MWht", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "SfMassFlow", "Field HTF mass flow rate total", "kg/s", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "o_SfTi", "Field HTF temperature cold header inlet", "C", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "SfTo", "Field HTF temperature hot header outlet", "C", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "AveSfTemp", "Field HTF temperature average", "C", "", "type_805", "*", "LENGTH=8760", "" },
// type 806 - thermal energy storage
{ SSC_OUTPUT, SSC_ARRAY, "Qtts", "TES thermal energy into storage", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Qfts", "TES thermal energy from storage", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Ets", "TES thermal energy available", "MWht", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QTsHl", "TES thermal losses from tank(s)", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
// type 807 - power plant
{ SSC_OUTPUT, SSC_ARRAY, "Enet", "Cycle electrical power output (net)", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Egr", "Cycle electrical power output (gross)", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EgrSol", "Cycle electrical power output (gross, solar share)", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EgrFos", "Cycle electrical power output (gross, fossil share)", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Qtpb", "Cycle thermal power input", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QTurSu", "Cycle thermal startup energy", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QTsFull", "Cycle thermal energy dumped - TES is full", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Qmin", "Cycle thermal energy dumped - min. load requirement", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Qdump", "Cycle thermal energy dumped - solar field", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
//Fossil backup
{ SSC_OUTPUT, SSC_ARRAY, "Qgas", "Fossil thermal power produced", "MWt", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QhtfFpHtr", "Fossil freeze protection provided", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
// parasitics
{ SSC_OUTPUT, SSC_ARRAY, "EparCHTF", "Parasitic power solar field HTF pump", "MWe", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparHhtf", "Parasitic power TES and Cycle HTF pump", "MWe", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparSf", "Parasitic power field collector drives", "MWe", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparBOP", "Parasitic power generation-dependent load", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparPB", "Parasitic power fixed load", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparHtr", "Parasitic power auxiliary heater operation", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparCT", "Parasitic power condenser operation", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparAnti", "Parasitic power freeze protection pump", "MWe", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QhtfFreezeProt", "Parasitic thermal field freeze protection", "MWt", "", "type_805", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "QhtfFpTES", "Parasitic thermal TES freeze protection", "MWt", "", "type_806", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparOffLine", "Parasitic power - offline total", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "EparOnLine", "Parasitic power - online total", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "Epar", "Parasitic power total consumption", "MWe", "", "type_807", "*", "LENGTH=8760", "" },
// other outputs
//{ SSC_OUTPUT, SSC_ARRAY, "TSLogic", "Dispatch logic w/o solar(1),with solar(2),turbine load(3)", "", "", "other", "*", "LENGTH=8760", "" },
// for connection to other ssc modules
{ SSC_OUTPUT, SSC_NUMBER, "system_use_lifetime_output", "Use lifetime output", "0/1", "", "tcs_trough_empirical", "*", "INTEGER", "" },
// { SSC_OUTPUT, SSC_ARRAY, "hourly_energy", "Hourly energy", "kWh", "", "tcs_trough_empirical", "*", "LENGTH=8760", "" },
{ SSC_OUTPUT, SSC_ARRAY, "monthly_energy", "Monthly energy", "kWh", "", "tcs_trough_empirical", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "annual_energy", "Annual energy", "kWh", "", "tcs_trough_empirical", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "annual_W_cycle_gross", "Electrical source - Power cycle gross output", "kWh", "", "tcs_trough_empirical", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "conversion_factor", "Gross to Net Conversion Factor", "%", "", "Calculated", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "capacity_factor", "Capacity factor", "%", "", "", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "kwh_per_kw", "First year kWh/kW", "kWh/kW", "", "", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "system_heat_rate", "System heat rate", "MMBtu/MWh", "", "", "*", "", "" },
{ SSC_OUTPUT, SSC_NUMBER, "annual_fuel_usage", "Annual fuel usage", "kWh", "", "", "*", "", "" },
var_info_invalid };
class cm_tcstrough_empirical : public tcKernel
{
public:
cm_tcstrough_empirical(tcstypeprovider *prov)
:tcKernel(prov)
{
add_var_info( _cm_vtab_tcstrough_empirical );
// performance adjustment factors
add_var_info(vtab_adjustment_factors);
add_var_info(vtab_technology_outputs);
//set_store_all_parameters(true); // default is 'false' = only store TCS parameters that match the SSC_OUTPUT variables above
}
void exec( )
{
bool debug_mode = (__DEBUG__ == 1); // When compiled in VS debug mode, this will use the trnsys weather file; otherwise, it will attempt to open the file with name that was passed in
//Add weather file reader unit
int weather = 0;
debug_mode = false;
if(debug_mode) weather = add_unit("trnsys_weatherreader", "TRNSYS weather reader");
else weather = add_unit("weatherreader", "TCS weather reader");
// Add tou translator
int tou = add_unit( "tou_translator", "Time of Use Translator" );
//Add Empirical Solar Field Model
int type805_solarfield = add_unit( "sam_trough_model_type805", "Test Trough" );
//Add Empirical Storage Model
int type806_storage = add_unit( "sam_trough_storage_type806", "Test Storage" );
//Add Empirical Power Block Model
int type807_powerblock = add_unit( "sam_trough_plant_type807", "Test Plant" );
if(debug_mode)
{
set_unit_value( weather, "file_name", "C:/svn_NREL/main/ssc/tcsdata/typelib/TRNSYS_weather_outputs/tucson_trnsys_weather.out" );
set_unit_value( weather, "i_hour", "TIME" );
set_unit_value( weather, "i_month", "month" );
set_unit_value( weather, "i_day", "day" );
set_unit_value( weather, "i_global", "GlobalHorizontal" );
set_unit_value( weather, "i_beam", "DNI" );
set_unit_value( weather, "i_diff", "DiffuseHorizontal" );
set_unit_value( weather, "i_tdry", "T_dry" );
set_unit_value( weather, "i_twet", "T_wet" );
set_unit_value( weather, "i_tdew", "T_dew" );
set_unit_value( weather, "i_wspd", "WindSpeed" );
set_unit_value( weather, "i_wdir", "WindDir" );
set_unit_value( weather, "i_rhum", "RelHum" );
set_unit_value( weather, "i_pres", "AtmPres" );
set_unit_value( weather, "i_snow", "SnowCover" );
set_unit_value( weather, "i_albedo", "GroundAlbedo" );
set_unit_value( weather, "i_poa", "POA" );
set_unit_value( weather, "i_solazi", "Azimuth" );
set_unit_value( weather, "i_solzen", "Zenith" );
set_unit_value( weather, "i_lat", "Latitude" );
set_unit_value( weather, "i_lon", "Longitude" );
set_unit_value( weather, "i_shift", "Shift" );
}
else
{
//Set weatherreader parameters
set_unit_value_ssc_string( weather, "file_name" );
set_unit_value_ssc_double( weather, "track_mode" ); //, 0 ); SET TO 3 IN TRNSYS FILE, no user input !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
set_unit_value_ssc_double( weather, "tilt" ); //, 0 );
set_unit_value_ssc_double( weather, "azimuth" ); //, 0 );
}
set_unit_value_ssc_matrix(tou, "weekday_schedule" ); // tou values from control will be between 1 and 9
set_unit_value_ssc_matrix(tou, "weekend_schedule" );
//Set Solar Field Parameters
// set_unit_value_ssc_double( type805_solarfield, "Site_Lat" ); //, 32.116667 );
// set_unit_value_ssc_double( type805_solarfield, "Site_LongD" ); //, -110.933333 );
// set_unit_value_ssc_double( type805_solarfield, "SHIFT" ); //, -7 );
set_unit_value_ssc_double( type805_solarfield, "Solar_Field_Area" ); //, 877580 ); csp.tr.solf.dp.fieldarea
set_unit_value_ssc_double( type805_solarfield, "Solar_Field_Mult" ); //, 2 ); csp.tr.solf.dp.solarmultiple
set_unit_value_ssc_double( type805_solarfield, "HTFFluid" ); //, 21 ); TranslateHTFType( IVal("csp.tr.solf.fieldhtftype")
set_unit_value_ssc_double( type805_solarfield, "NumHCETypes" ); //, 4 );
set_unit_value_ssc_array( type805_solarfield, "HCEtype" ); // {1,1,1,1},
set_unit_value_ssc_array( type805_solarfield, "HCEFrac" ); // {0.985,0.01,0.005,0},
set_unit_value_ssc_array( type805_solarfield, "HCEdust" ); //, t[2], 4 ); // {0.98,0.98,0.98,0.98},
set_unit_value_ssc_array( type805_solarfield, "HCEBelShad" ); //, t[3], 4 ); // {0.963,0.963,0.963,0.963},
set_unit_value_ssc_array( type805_solarfield, "HCEEnvTrans" ); //, t[4], 4 ); // {0.963,0.963,1,0.963},
set_unit_value_ssc_array( type805_solarfield, "HCEabs" ); //, t[5], 4 ); // {0.96,0.96,0.8,0.96},
set_unit_value_ssc_array( type805_solarfield, "HCEmisc" ); //, t[6], 4 ); // {1,1,1,1},
set_unit_value_ssc_array( type805_solarfield, "PerfFac" ); //, t[7], 4 ); // {1,1,1,1},
set_unit_value_ssc_array( type805_solarfield, "RefMirrAper" ); //, t[8], 4 ); // {5,5,5,5},
set_unit_value_ssc_array( type805_solarfield, "HCE_A0" ); //, t[9], 4 ); // {4.05, 50.8, -9.95, 11.8},
set_unit_value_ssc_array( type805_solarfield, "HCE_A1" ); //, t[10], 4 ); // {0.247, 0.904, 0.465, 1.35},
set_unit_value_ssc_array( type805_solarfield, "HCE_A2" ); //, t[11], 4 ); // {-0.00146, 0.000579, -0.000854, 0.0075} ,
set_unit_value_ssc_array( type805_solarfield, "HCE_A3" ); //, t[12], 4 ); // {5.65e-6, 1.13e-5, 1.85e-5, 4.07e-6},
set_unit_value_ssc_array( type805_solarfield, "HCE_A4" ); //, t[13], 4 ); // {7.62e-8, 1.73e-7, 6.89e-7, 5.85e-8} ,
set_unit_value_ssc_array( type805_solarfield, "HCE_A5" ); //, t[14], 4 ); // {-1.7, -43.2, 24.7, 4.48},
set_unit_value_ssc_array( type805_solarfield, "HCE_A6" ); //, t[15], 4 ); // {0.0125, 0.524, 3.37, 0.285}
// set_unit_value_ssc_double( type805_solarfield, "LU_Fl" ); //, 21.0 ); // necessary?
// set_unit_value_ssc_double( type805_solarfield, "LuFlEr" ); //, 0.0 ); // necessary?
set_unit_value_ssc_double( type805_solarfield, "i_SfTi" ); //, -999 );
set_unit_value_ssc_double( type805_solarfield, "Stow_Angle" ); //, 170); // csp.tr.solf.stowangle
set_unit_value_ssc_double( type805_solarfield, "DepAngle" ); //, 10); // csp.tr.solf.deployangle
set_unit_value_ssc_double( type805_solarfield, "IamF0" ); //, 1); // csp.tr.sca.iamc1
set_unit_value_ssc_double( type805_solarfield, "IamF1" ); //, 0.0506); // csp.tr.sca.iamc2
set_unit_value_ssc_double( type805_solarfield, "IamF2" ); //, -0.1763); // csp.tr.sca.iamc3
set_unit_value_ssc_double( type805_solarfield, "Ave_Focal_Length" ); //, 1.8); // csp.tr.sca.avg_focal_length
set_unit_value_ssc_double( type805_solarfield, "Distance_SCA" ); //, 1); // csp.tr.solf.distscas
set_unit_value_ssc_double( type805_solarfield, "Row_Distance" ); //, 15); // csp.tr.solf.distrows
set_unit_value_ssc_double( type805_solarfield, "SCA_aper" ); //, 5); // csp.tr.sca.aperture
set_unit_value_ssc_double( type805_solarfield, "SfAvail" ); //, 0.99); // csp.tr.sca.availability
set_unit_value_ssc_double(type805_solarfield, "ColTilt", as_double("tilt"));
//, set_unit_value_ssc_double( type805_solarfield, "ColTilt" ); //, 0.0); // csp.tr.solf.tilt
set_unit_value_ssc_double(type805_solarfield, "ColAz", as_double("azimuth"));
//, set_unit_value_ssc_double( type805_solarfield, "ColAz" ); //, 0.0); // csp.tr.solf.azimuth
set_unit_value_ssc_double( type805_solarfield, "NumScas" ); //, 4); // csp.tr.solf.nscasperloop
set_unit_value_ssc_double( type805_solarfield, "ScaLen" ); //, 100); // csp.tr.sca.length
set_unit_value_ssc_double( type805_solarfield, "MinHtfTemp" ); //, 50); // csp.tr.solf.htfmintemp
set_unit_value_ssc_double( type805_solarfield, "HtfGalArea" ); //, 0.614); // csp.tr.solf.htfgallonsperarea
set_unit_value_ssc_double( type805_solarfield, "SfPar" ); //, 0.233436);// csp.tr.par.sf.total
set_unit_value_ssc_double( type805_solarfield, "SfParPF" ); //, 1); // csp.tr.par.sf.partload
set_unit_value_ssc_double( type805_solarfield, "ChtfPar" ); //, 9.23214); // csp.tr.par.htfpump.total
set_unit_value_ssc_double( type805_solarfield, "ChtfParPF" ); //, 1); // csp.tr.par.htfpump.partload
set_unit_value_ssc_double( type805_solarfield, "CHTFParF0" ); //, -0.036); // csp.tr.par.htfpump.f0
set_unit_value_ssc_double( type805_solarfield, "CHTFParF1" ); //, 0.242); // csp.tr.par.htfpump.f1
set_unit_value_ssc_double( type805_solarfield, "CHTFParF2" ); //, 0.794); // csp.tr.par.htfpump.f2
set_unit_value_ssc_double( type805_solarfield, "AntiFrPar" ); //, 0.923214);// csp.tr.par.antifreeze.total
set_unit_value_ssc_double( type805_solarfield, "TurbOutG" ); //, 111); // csp.tr.pwrb.design_gross_output
set_unit_value_ssc_double( type805_solarfield, "TurbEffG" ); //, 0.3774); // csp.tr.pwrb.effdesign
set_unit_value_ssc_double( type805_solarfield, "SfInTempD" ); //, 293); // csp.tr.solf.htfinlettemp
set_unit_value_ssc_double( type805_solarfield, "SfOutTempD" ); //, 391); // csp.tr.solf.htfoutlettemp
// set_unit_value_ssc_double( type805_solarfield, "ColType" ); //, 1);
set_unit_value_ssc_double( type805_solarfield, "TrkTwstErr" ); //, 0.994); // csp.tr.sca.track_twist_error
set_unit_value_ssc_double( type805_solarfield, "GeoAcc" ); //, 0.98); // csp.tr.sca.geometric_accuracy
set_unit_value_ssc_double( type805_solarfield, "MirRef" ); //, 0.935); // csp.tr.sca.reflectivity
set_unit_value_ssc_double( type805_solarfield, "MirCln" ); //, 0.95); // csp.tr.sca.cleanliness
set_unit_value_ssc_double( type805_solarfield, "ConcFac" ); //, 1); // csp.tr.sca.concentrator_factor
set_unit_value_ssc_double( type805_solarfield, "SfPipeHl300" ); //, 10); // csp.tr.solf.pipingheatlossatdesign
set_unit_value_ssc_double( type805_solarfield, "SfPipeHl1" ); //, 0.001693); // csp.tr.solf.pipingheatlosscoeff1
set_unit_value_ssc_double( type805_solarfield, "SfPipeHl2" ); //, -1.683e-5); // csp.tr.solf.pipingheatlosscoeff2
set_unit_value_ssc_double( type805_solarfield, "SfPipeHl3" ); //, 6.78e-8); // csp.tr.solf.pipingheatlosscoeff3
set_unit_value_ssc_double( type805_solarfield, "SFTempInit" ); //, 100); // csp.tr.solf.htfinittemp
//Connect Solar Field Inputs
bool bConnected = connect( weather, "solazi", type805_solarfield, "SolarAz", 0.1, -1 );
bConnected &= connect( weather, "beam", type805_solarfield, "Insol_Beam_Normal", 0.1, -1 );
bConnected &= connect( weather, "tdry", type805_solarfield, "AmbientTemperature", 0.1, -1 );
bConnected &= connect(weather, "wspd", type805_solarfield, "WndSpd", 0.1, -1);
bConnected &= connect(weather, "shift", type805_solarfield, "SHIFT", 0.1, -1);
bConnected &= connect(weather, "lat", type805_solarfield, "Site_Lat", 0.1, -1);
bConnected &= connect(weather, "lon", type805_solarfield, "Site_LongD", 0.1, -1);
//Set Storage Parameters
set_unit_value_ssc_double(type806_storage, "TSHOURS" ); //,6); // csp.tr.tes.full_load_hours
set_unit_value_ssc_double(type806_storage, "NUMTOU" ); //, 9);
set_unit_value_ssc_double(type806_storage, "E2TPLF0" ); //, 0.03737); // csp.tr.pwrb.tpl_tff0
set_unit_value_ssc_double(type806_storage, "E2TPLF1" ); //, 0.98823); // csp.tr.pwrb.tpl_tff1
set_unit_value_ssc_double(type806_storage, "E2TPLF2" ); //, -0.064991); // csp.tr.pwrb.tpl_tff2
set_unit_value_ssc_double(type806_storage, "E2TPLF3" ); //, 0.039388); // csp.tr.pwrb.tpl_tff3
set_unit_value_ssc_double(type806_storage, "E2TPLF4" ); //, 0.0); // csp.tr.pwrb.tpl_tff4
//double t2[9][3] = {{0.1,0.1,1.05},{0.1,0.1,1},{0.1,0.1,1},{0.1,0.1,1},{0.1,0.1,1},{0.1,0.1,1},{0.1,0.1,1},{0.1,0.1,1},{0.1,0.1,1}};
//set_unit_value(type806_storage, "TSLogic", &t2[0][0], 9, 3);
set_unit_value_ssc_matrix(type806_storage, "TSLogic" ); // csp.tr.tes.dispX.solar, csp.tr.tes.dispX.nosolar, csp.tr.tes.dispX.turbout, where X = 1 to 9
// 4.17.14, twn
set_unit_value_ssc_double(type806_storage, "E_tes_ini");
//set_unit_value_ssc_double(type806_storage, "TOUPeriod", 1 ); //, 1 );
set_unit_value_ssc_double(type806_storage, "TnkHL" ); //, 0.97); // csp.tr.tes.tank_heatloss
set_unit_value_ssc_double(type806_storage, "PTSmax" ); //, 294.118); // csp.tr.tes.max_to_power
set_unit_value_ssc_double(type806_storage, "PFSmax" ); //, 297.999); // csp.tr.tes.max_from_power
set_unit_value_ssc_double(type806_storage, "PTTMAX" ); //, 1.05); // csp.tr.pwrb.maxoutput
set_unit_value_ssc_double(type806_storage, "PTTMIN" ); //, 0.25); // csp.tr.pwrb.minoutput
set_unit_value_ssc_double(type806_storage, "TurSUE" ); //, 0.2); // csp.tr.pwrb.startup_energy
set_unit_value_ssc_double(type806_storage, "HhtfPar" ); //, 2.22); // csp.tr.par.tes.total
set_unit_value_ssc_double(type806_storage, "HhtfParPF" ); //, 1); // csp.tr.par.tes.partload
set_unit_value_ssc_double(type806_storage, "HhtfParF0" ); //, -0.036); // csp.tr.par.tes.f0
set_unit_value_ssc_double(type806_storage, "HhtfParF1" ); //, 0.242); // csp.tr.par.tes.f1
set_unit_value_ssc_double(type806_storage, "HhtfParF2" ); //, 0.794); // csp.tr.par.tes.f2
//Connect Storage Inputs
bConnected &= connect( type805_solarfield, "Qsf", type806_storage, "Qsf", 0.1, -1);
bConnected &= connect( type805_solarfield, "Qdesign", type806_storage, "Qdesign", 0.1, -1);
bConnected &= connect( type805_solarfield, "QhtfFreezeProt", type806_storage, "QhtfFreezeProt", 0.1, -1);
bConnected &= connect( tou, "tou_value", type806_storage, "TOUPeriod");
//Set Powerblock Parameters
set_unit_value_ssc_double(type807_powerblock,"T2EPLF0" ); //, -0.037726); // csp.tr.pwrb.tpl_tef0
set_unit_value_ssc_double(type807_powerblock,"T2EPLF1" ); //, 1.0062); // csp.tr.pwrb.tpl_tef1
set_unit_value_ssc_double(type807_powerblock,"T2EPLF2" ); //, 0.076316); // csp.tr.pwrb.tpl_tef2
set_unit_value_ssc_double(type807_powerblock,"T2EPLF3" ); //, -0.044775); // csp.tr.pwrb.tpl_tef3
set_unit_value_ssc_double(type807_powerblock,"T2EPLF4" ); //, 0.0); // csp.tr.pwrb.tpl_tef4
set_unit_value_ssc_double(type807_powerblock,"E2TPLF0" ); //, 0.03737); // csp.tr.pwrb.tpl_tff0
set_unit_value_ssc_double(type807_powerblock,"E2TPLF1" ); //, 0.98823); // csp.tr.pwrb.tpl_tff1
set_unit_value_ssc_double(type807_powerblock,"E2TPLF2" ); //, -0.064991); // csp.tr.pwrb.tpl_tff2
set_unit_value_ssc_double(type807_powerblock,"E2TPLF3" ); //, 0.039388); // csp.tr.pwrb.tpl_tff3
set_unit_value_ssc_double(type807_powerblock,"E2TPLF4" ); //, 0.0); // csp.tr.pwrb.tpl_tff4
set_unit_value_ssc_double(type807_powerblock,"TempCorrF" ); //, 1); // csp.tr.pwrb.temp_corr_mode + 1
set_unit_value_ssc_double(type807_powerblock,"TempCorr0" ); //, 1); // csp.tr.pwrb.ctcf0
set_unit_value_ssc_double(type807_powerblock,"TempCorr1" ); //, 0.0); // csp.tr.pwrb.ctcf1
set_unit_value_ssc_double(type807_powerblock,"TempCorr2" ); //, 0.0); // csp.tr.pwrb.ctcf2
set_unit_value_ssc_double(type807_powerblock,"TempCorr3" ); //, 0.0); // csp.tr.pwrb.ctcf3
set_unit_value_ssc_double(type807_powerblock,"TempCorr4" ); //, 0.0); // csp.tr.pwrb.ctcf4
set_unit_value_ssc_double(type807_powerblock,"TurTesEffAdj" ); //, 0.985); // csp.tr.tes.adj_eff
set_unit_value_ssc_double(type807_powerblock,"TurTesOutAdj" ); //, 0.998); // csp.tr.tes.adj_output
set_unit_value_ssc_double(type807_powerblock,"MinGrOut" ); //, 0.25); // csp.tr.pwrb.minoutput
set_unit_value_ssc_double(type807_powerblock,"MaxGrOut" ); //, 1.05); // csp.tr.pwrb.maxoutput
set_unit_value_ssc_double(type807_powerblock,"NUMTOU" ); //, 9); // csp.tr.tes.dispX.fossil, where X = 1 to 9
//double t4[9] = {0,0,0,0,0,0,0,0,0};
set_unit_value_ssc_array(type807_powerblock, "FossilFill" ); //, t4, 9 );
set_unit_value_ssc_double(type807_powerblock,"PbFixPar" ); //, 0.6105); // csp.tr.par.fixedblock.total
set_unit_value_ssc_double(type807_powerblock,"BOPPar" ); //, 2.73837); // csp.tr.par.bop.total
set_unit_value_ssc_double(type807_powerblock,"BOPParPF" ); //, 1); // csp.tr.par.bop.partload
set_unit_value_ssc_double(type807_powerblock,"BOPParF0" ); //, 0.483); // csp.tr.par.bop.f0
set_unit_value_ssc_double(type807_powerblock,"BOPParF1" ); //, 0.517); // csp.tr.par.bop.f1
set_unit_value_ssc_double(type807_powerblock,"BOPParF2" ); //, 0.0); // csp.tr.par.bop.f2
set_unit_value_ssc_double(type807_powerblock,"CtPar" ); //, 1.892); // csp.tr.par.ct0.total
set_unit_value_ssc_double(type807_powerblock,"CtParPF" ); //, 1); // csp.tr.par.ct0.partload
set_unit_value_ssc_double(type807_powerblock,"CtParF0" ); //, -0.036); // csp.tr.par.ct0.f0
set_unit_value_ssc_double(type807_powerblock,"CtParF1" ); //, 0.242); // csp.tr.par.ct0.f1
set_unit_value_ssc_double(type807_powerblock,"CtParF2" ); //, 0.794); // csp.tr.par.ct0.f2
set_unit_value_ssc_double(type807_powerblock,"HtrPar" ); //, 2.52303); // csp.tr.par.hb.total
set_unit_value_ssc_double(type807_powerblock,"HtrParPF" ); //, 1); // csp.tr.par.hb.partload
set_unit_value_ssc_double(type807_powerblock,"HtrParF0" ); //, 0.483); // csp.tr.par.hb.f0
set_unit_value_ssc_double(type807_powerblock,"HtrParF1" ); //, 0.517); // csp.tr.par.hb.f1
set_unit_value_ssc_double(type807_powerblock,"HtrParF2" ); //, 0.0); // csp.tr.par.hb.f2
set_unit_value_ssc_double(type807_powerblock,"LHVBoilEff" ); //, 0.9); // csp.tr.pwrb.boiler_lhv_eff
//set_unit_value_ssc_double(type807_powerblock,"TOUPeriod", 1 ); //, 1 );// uniform dispatch
set_unit_value_ssc_double(type807_powerblock,"CtOpF" ); //, 1); // csp.tr.par.operation_mode
bConnected &= connect(type805_solarfield, "Qdesign", type807_powerblock, "Qdesign", 0.1, -1);
bConnected &= connect(type805_solarfield, "Edesign", type807_powerblock,"Edesign", 0.1, -1);
bConnected &= connect(type806_storage,"Qtpb", type807_powerblock,"Qtpb", 0.1,-1);
bConnected &= connect(type806_storage,"Qfts",type807_powerblock,"Qfts", 0.1,-1);
bConnected &= connect(weather, "twet",type807_powerblock,"Twetbulb", 0.1, -1 );
bConnected &= connect( weather, "tdry", type807_powerblock,"Tdrybulb", 0.1, -1 );
bConnected &= connect(type805_solarfield, "SFTotPar", type807_powerblock,"SFTotPar", 0.1, -1 );
bConnected &= connect(type806_storage, "EparHhtf", type807_powerblock,"EparHhtf", 0.1, -1 );
bConnected &= connect( tou, "tou_value", type807_powerblock, "TOUPeriod");
// check if all connections worked
if ( !bConnected )
throw exec_error( "tcstrough_empirical", util::format("there was a problem connecting outputs of one unit to inputs of another for the simulation.") );
// Run simulation
size_t hours = 8760;
if (0 > simulate(3600.0, hours*3600.0, 3600.0) )
throw exec_error( "tcstrough_empirical", util::format("there was a problem simulating in tcstrough_empirical.") );
// get the outputs
if (!set_all_output_arrays() )
throw exec_error( "tcstrough_empirical", util::format("there was a problem returning the results from the simulation.") );
// outputs for other compute modules
assign("system_use_lifetime_output", 0);
//1.7.15, twn: Need to calculated the conversion factor before the performance adjustments are applied to "hourly energy"
accumulate_annual("Enet", "annual_energy",1000.0); // kWh
accumulate_annual("Egr", "annual_W_cycle_gross",1000.0); // kWh
// Calculated outputs
ssc_number_t ae = as_number("annual_energy");
ssc_number_t pg = as_number("annual_W_cycle_gross");
ssc_number_t convfactor = (pg != 0) ? 100 * ae / pg : 0;
assign("conversion_factor", convfactor);
// performance adjustement factors
adjustment_factors haf(this, "adjust");
if (!haf.setup())
throw exec_error("tcstrough_empirical", "failed to setup adjustment factors: " + haf.error());
// hourly_energy output
ssc_number_t *p_hourly_energy = allocate("gen", 8760);
// set hourly energy = tcs output Enet
size_t count;
ssc_number_t *hourly_energy = as_array("Enet", &count);//MWh
if (count != 8760)
{
std::stringstream msg;
msg << "gen count incorrect (should be 8760): " << count;
throw exec_error("tcstrough_empirical", msg.str());
}
// apply performance adjustments and convert from MWh to kWh
for (size_t i = 0; i < count; i++)
{
p_hourly_energy[i] = hourly_energy[i] * (ssc_number_t)(haf(i) * 1000.0);
}
ssc_number_t* p_annual_energy_dist_time = gen_heatmap(this, 1);
accumulate_annual("gen", "annual_energy"); // already in kWh
accumulate_monthly("gen", "monthly_energy"); // already in kWh
// metric outputs moved to technology
double kWhperkW = 0.0;
double nameplate = as_double("system_capacity");
double annual_energy = 0.0;
for (int i = 0; i < 8760; i++) {
annual_energy += p_hourly_energy[i];
}
if (nameplate > 0) kWhperkW = annual_energy / nameplate;
assign("capacity_factor", var_data((ssc_number_t)(kWhperkW / 87.6)));
assign("kwh_per_kw", var_data((ssc_number_t)kWhperkW));
assign("system_heat_rate", (ssc_number_t)3.413); // samsim tcstrough_physical
accumulate_annual("Qgas", "annual_fuel_usage", 1000.0); // MWht to kWht
}
};
DEFINE_TCS_MODULE_ENTRY( tcstrough_empirical, "CSP model using the emperical trough TCS types.", 4 )
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/toolbar/browser_actions_bar_browsertest.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_toolbar_model.h"
#include "components/crx_file/id_util.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/value_builder.h"
namespace {
scoped_refptr<const extensions::Extension> CreateExtension(
const std::string& name,
bool has_browser_action) {
extensions::DictionaryBuilder manifest;
manifest.Set("name", name).
Set("description", "an extension").
Set("manifest_version", 2).
Set("version", "1.0");
if (has_browser_action)
manifest.Set("browser_action", extensions::DictionaryBuilder().Pass());
return extensions::ExtensionBuilder().
SetManifest(manifest.Pass()).
SetID(crx_file::id_util::GenerateId(name)).
Build();
}
} // namespace
BrowserActionsBarBrowserTest::BrowserActionsBarBrowserTest() {
}
BrowserActionsBarBrowserTest::~BrowserActionsBarBrowserTest() {
}
void BrowserActionsBarBrowserTest::SetUpCommandLine(
base::CommandLine* command_line) {
BrowserActionTestUtil::DisableAnimations();
ExtensionBrowserTest::SetUpCommandLine(command_line);
}
void BrowserActionsBarBrowserTest::SetUpOnMainThread() {
ExtensionBrowserTest::SetUpOnMainThread();
browser_actions_bar_.reset(new BrowserActionTestUtil(browser()));
}
void BrowserActionsBarBrowserTest::TearDownOnMainThread() {
BrowserActionTestUtil::EnableAnimations();
ExtensionBrowserTest::TearDownOnMainThread();
}
void BrowserActionsBarBrowserTest::LoadExtensions() {
// Create three extensions with browser actions.
extension_a_ = CreateExtension("alpha", true);
extension_b_ = CreateExtension("beta", true);
extension_c_ = CreateExtension("gamma", true);
const extensions::Extension* extensions[] =
{ extension_a(), extension_b(), extension_c() };
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile());
// Add each, and verify that it is both correctly added to the extension
// registry and to the browser actions container.
for (size_t i = 0; i < arraysize(extensions); ++i) {
extension_service()->AddExtension(extensions[i]);
EXPECT_TRUE(registry->enabled_extensions().GetByID(extensions[i]->id())) <<
extensions[i]->name();
EXPECT_EQ(static_cast<int>(i + 1),
browser_actions_bar_->NumberOfBrowserActions());
EXPECT_TRUE(browser_actions_bar_->HasIcon(i));
EXPECT_EQ(static_cast<int>(i + 1),
browser_actions_bar()->VisibleBrowserActions());
}
}
// Test the basic functionality.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest, Basic) {
// Load an extension with no browser action.
extension_service()->AddExtension(CreateExtension("alpha", false).get());
// This extension should not be in the model (has no browser action).
EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());
// Load an extension with a browser action.
extension_service()->AddExtension(CreateExtension("beta", true).get());
EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
EXPECT_TRUE(browser_actions_bar()->HasIcon(0));
// Unload the extension.
std::string id = browser_actions_bar()->GetExtensionId(0);
UnloadExtension(id);
EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());
}
// Test moving various browser actions. This is not to check the logic of the
// move (that's in the toolbar model tests), but just to check our ui.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest, MoveBrowserActions) {
LoadExtensions();
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
extensions::ExtensionToolbarModel* model =
extensions::ExtensionToolbarModel::Get(profile());
ASSERT_TRUE(model);
// Order is now A B C.
EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));
EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(1));
EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(2));
// Move C to first position. Order is C A B.
model->MoveExtensionIcon(extension_c()->id(), 0);
EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(0));
EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(1));
EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(2));
// Move B to third position. Order is still C A B.
model->MoveExtensionIcon(extension_b()->id(), 2);
EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(0));
EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(1));
EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(2));
// Move B to middle position. Order is C B A.
model->MoveExtensionIcon(extension_b()->id(), 1);
EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(0));
EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(1));
EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(2));
}
// Test that explicitly hiding an extension action results in it disappearing
// from the browser actions bar.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest, ForceHide) {
LoadExtensions();
EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));
// Force hide one of the extensions' browser action.
extensions::ExtensionActionAPI::SetBrowserActionVisibility(
extensions::ExtensionPrefs::Get(browser()->profile()),
extension_a()->id(),
false);
// The browser action for Extension A should be removed.
EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(0));
}
|
#pragma once
#include <crea/schema/schema_types/flat_map.hpp>
#include <crea/schema/schema_types/flat_set.hpp>
#include <crea/schema/schema_types/static_variant.hpp>
#include <crea/schema/schema_types/optional.hpp>
#include <crea/schema/schema_types/pair.hpp>
#include <crea/schema/schema_types/vector.hpp>
|
#pragma once
#include <PP/pack/apply_template.hpp>
#include <PP/template_t.hpp>
namespace PP::detail
{
template <typename T>
using add_const_t = const T;
}
namespace PP
{
PP_CIA add_const = Template<detail::add_const_t>;
}
|
#include<iostream>
using namespace std;
int Time[105];
int value[105];
int f[1005];
int main(void){
int T, M;
cin>>T>>M;
for(int i=1; i<=M; i++) {
cin>>Time[i]>>value[i];
}
for(int i=1; i<=M; i++) {
for(int t=T; t>=Time[i]; t--){
f[t] = max(f[t], f[t-Time[i]]+value[i]);
}
}
cout<<f[T]<<endl;
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <vector>
// template <class InputIter> vector(InputIter first, InputIter last,
// const allocator_type& a);
#include <vector>
#include <cassert>
#include <cstddef>
#include "test_macros.h"
#include "test_iterators.h"
#include "test_allocator.h"
#include "min_allocator.h"
#include "asan_testing.h"
#if TEST_STD_VER >= 11
#include "emplace_constructible.h"
#include "container_test_types.h"
#endif
template <class C, class Iterator, class A>
void test(Iterator first, Iterator last, const A& a) {
C c(first, last, a);
LIBCPP_ASSERT(c.__invariants());
assert(c.size() == static_cast<std::size_t>(std::distance(first, last)));
LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
for (typename C::const_iterator i = c.cbegin(), e = c.cend(); i != e;
++i, ++first)
assert(*i == *first);
}
#if TEST_STD_VER >= 11
template <class T>
struct implicit_conv_allocator : min_allocator<T> {
implicit_conv_allocator(void*) {}
implicit_conv_allocator(const implicit_conv_allocator&) = default;
template <class U>
implicit_conv_allocator(implicit_conv_allocator<U>) {}
};
#endif
void basic_tests() {
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 1, 0};
int* an = a + sizeof(a) / sizeof(a[0]);
std::allocator<int> alloc;
test<std::vector<int> >(cpp17_input_iterator<const int*>(a),
cpp17_input_iterator<const int*>(an), alloc);
test<std::vector<int> >(forward_iterator<const int*>(a),
forward_iterator<const int*>(an), alloc);
test<std::vector<int> >(bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an), alloc);
test<std::vector<int> >(random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an), alloc);
test<std::vector<int> >(a, an, alloc);
}
#if TEST_STD_VER >= 11
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 1, 0};
int* an = a + sizeof(a) / sizeof(a[0]);
min_allocator<int> alloc;
test<std::vector<int, min_allocator<int> > >(
cpp17_input_iterator<const int*>(a), cpp17_input_iterator<const int*>(an), alloc);
test<std::vector<int, min_allocator<int> > >(
forward_iterator<const int*>(a), forward_iterator<const int*>(an),
alloc);
test<std::vector<int, min_allocator<int> > >(
bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an), alloc);
test<std::vector<int, min_allocator<int> > >(
random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an), alloc);
test<std::vector<int, min_allocator<int> > >(a, an, alloc);
test<std::vector<int, implicit_conv_allocator<int> > >(a, an, nullptr);
}
#endif
}
void emplaceable_concept_tests() {
#if TEST_STD_VER >= 11
int arr1[] = {42};
int arr2[] = {1, 101, 42};
{
using T = EmplaceConstructible<int>;
using It = forward_iterator<int*>;
using Alloc = std::allocator<T>;
Alloc a;
{
std::vector<T> v(It(arr1), It(std::end(arr1)), a);
assert(v[0].value == 42);
}
{
std::vector<T> v(It(arr2), It(std::end(arr2)), a);
assert(v[0].value == 1);
assert(v[1].value == 101);
assert(v[2].value == 42);
}
}
{
using T = EmplaceConstructibleAndMoveInsertable<int>;
using It = cpp17_input_iterator<int*>;
using Alloc = std::allocator<T>;
Alloc a;
{
std::vector<T> v(It(arr1), It(std::end(arr1)), a);
assert(v[0].copied == 0);
assert(v[0].value == 42);
}
{
std::vector<T> v(It(arr2), It(std::end(arr2)), a);
assert(v[0].value == 1);
assert(v[1].value == 101);
assert(v[2].copied == 0);
assert(v[2].value == 42);
}
}
#endif
}
void test_ctor_under_alloc() {
#if TEST_STD_VER >= 11
int arr1[] = {42};
int arr2[] = {1, 101, 42};
{
using C = TCT::vector<>;
using It = forward_iterator<int*>;
using Alloc = typename C::allocator_type;
Alloc a;
{
ExpectConstructGuard<int&> G(1);
C v(It(arr1), It(std::end(arr1)), a);
}
{
ExpectConstructGuard<int&> G(3);
C v(It(arr2), It(std::end(arr2)), a);
}
}
{
using C = TCT::vector<>;
using It = cpp17_input_iterator<int*>;
using Alloc = typename C::allocator_type;
Alloc a;
{
ExpectConstructGuard<int&> G(1);
C v(It(arr1), It(std::end(arr1)), a);
}
{
//ExpectConstructGuard<int&> G(3);
//C v(It(arr2), It(std::end(arr2)), a);
}
}
#endif
}
int main(int, char**) {
basic_tests();
emplaceable_concept_tests(); // See PR34898
test_ctor_under_alloc();
return 0;
}
|
/*
* OGF/Graphite: Geometry and Graphics Programming Library + Utilities
* Copyright (C) 2000-2005 INRIA - Project ALICE
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy - levy@loria.fr
*
* Project ALICE
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
* Note that the GNU General Public License does not permit incorporating
* the Software into proprietary programs.
*
* As an exception to the GPL, Graphite can be linked with the following (non-GPL) libraries:
* Qt, SuperLU, WildMagic and CGAL
*/
#include <OGF/math/geometry/average_direction.h>
#include <OGF/math/linear_algebra/matrix_util.h>
namespace OGF {
//______________________________________________________________
AverageDirection::AverageDirection() {
result_is_valid_ = false ;
}
void AverageDirection::begin() {
for(int i=0; i<6; i++) {
M_[i] = 0.0 ;
}
}
void AverageDirection::add_vector(const Vector3d& e) {
M_[0] += e.x() * e.x() ;
M_[1] += e.x() * e.y() ;
M_[2] += e.y() * e.y() ;
M_[3] += e.x() * e.z() ;
M_[4] += e.y() * e.z() ;
M_[5] += e.z() * e.z() ;
}
void AverageDirection::end() {
double eigen_vectors[9] ;
double eigen_values[6] ;
MatrixUtil::semi_definite_symmetric_eigen(M_, 3, eigen_vectors, eigen_values) ;
// Sort the eigen vectors
int i[3] ;
i[0] = 0 ;
i[1] = 1 ;
i[2] = 2 ;
double l0 = ::fabs(eigen_values[0]) ;
double l1 = ::fabs(eigen_values[1]) ;
double l2 = ::fabs(eigen_values[2]) ;
if(l1 > l0) {
ogf_swap(l0 , l1 ) ;
ogf_swap(i[0], i[1]) ;
}
if(l2 > l1) {
ogf_swap(l1 , l2 ) ;
ogf_swap(i[1], i[2]) ;
}
if(l1 > l0) {
ogf_swap(l0 , l1 ) ;
ogf_swap(i[0],i[1]) ;
}
int k = 0 ;
result_ = Vector3d(
eigen_vectors[3*i[k] ],
eigen_vectors[3*i[k]+1],
eigen_vectors[3*i[k]+2]
) ;
result_is_valid_ = true ;
}
//______________________________________________________________
AverageDirection2d::AverageDirection2d() {
result_is_valid_ = false ;
}
void AverageDirection2d::begin() {
for(int i=0; i<3; i++) {
M_[i] = 0.0 ;
}
}
void AverageDirection2d::add_vector(const Vector2d& e) {
M_[0] += e.x() * e.x() ;
M_[1] += e.x() * e.y() ;
M_[2] += e.y() * e.y() ;
}
void AverageDirection2d::end() {
double eigen_vectors[4] ;
double eigen_values[2] ;
MatrixUtil::semi_definite_symmetric_eigen(M_, 2, eigen_vectors, eigen_values) ;
int k = 0 ;
result_ = Vector2d(
eigen_vectors[2*k],
eigen_vectors[2*k+1]
) ;
result_is_valid_ = true ;
}
//______________________________________________________________
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
// Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/StdList>
#include <Eigen/Geometry>
template<typename MatrixType>
void check_stdlist_matrix(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
Index rows = m.rows();
Index cols = m.cols();
MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);
std::list<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<MatrixType,Eigen::aligned_allocator<MatrixType> >::iterator vi = v.begin();
typename std::list<MatrixType,Eigen::aligned_allocator<MatrixType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
template<typename TransformType>
void check_stdlist_transform(const TransformType&)
{
typedef typename TransformType::MatrixType MatrixType;
TransformType x(MatrixType::Random()), y(MatrixType::Random());
std::list<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<TransformType,Eigen::aligned_allocator<TransformType> >::iterator vi = v.begin();
typename std::list<TransformType,Eigen::aligned_allocator<TransformType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
template<typename QuaternionType>
void check_stdlist_quaternion(const QuaternionType&)
{
typedef typename QuaternionType::Coefficients Coefficients;
QuaternionType x(Coefficients::Random()), y(Coefficients::Random());
std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y);
v.front() = x;
w.front() = w.back();
VERIFY_IS_APPROX(w.front(), w.back());
v = w;
typename std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> >::iterator vi = v.begin();
typename std::list<QuaternionType,Eigen::aligned_allocator<QuaternionType> >::iterator wi = w.begin();
for(int i = 0; i < 20; i++)
{
VERIFY_IS_APPROX(*vi, *wi);
++vi;
++wi;
}
v.resize(21);
v.back() = x;
VERIFY_IS_APPROX(v.back(), x);
v.resize(22,y);
VERIFY_IS_APPROX(v.back(), y);
v.push_back(x);
VERIFY_IS_APPROX(v.back(), x);
}
void test_stdlist()
{
// some non vectorizable fixed sizes
CALL_SUBTEST_1(check_stdlist_matrix(Vector2f()));
CALL_SUBTEST_1(check_stdlist_matrix(Matrix3f()));
CALL_SUBTEST_2(check_stdlist_matrix(Matrix3d()));
// some vectorizable fixed sizes
CALL_SUBTEST_1(check_stdlist_matrix(Matrix2f()));
CALL_SUBTEST_1(check_stdlist_matrix(Vector4f()));
CALL_SUBTEST_1(check_stdlist_matrix(Matrix4f()));
CALL_SUBTEST_2(check_stdlist_matrix(Matrix4d()));
// some dynamic sizes
CALL_SUBTEST_3(check_stdlist_matrix(MatrixXd(1,1)));
CALL_SUBTEST_3(check_stdlist_matrix(VectorXd(20)));
CALL_SUBTEST_3(check_stdlist_matrix(RowVectorXf(20)));
CALL_SUBTEST_3(check_stdlist_matrix(MatrixXcf(10,10)));
// some Transform
CALL_SUBTEST_4(check_stdlist_transform(Affine2f()));
CALL_SUBTEST_4(check_stdlist_transform(Affine3f()));
CALL_SUBTEST_4(check_stdlist_transform(Affine3d()));
// some Quaternion
CALL_SUBTEST_5(check_stdlist_quaternion(Quaternionf()));
CALL_SUBTEST_5(check_stdlist_quaternion(Quaterniond()));
}
|
#ifndef STAN_MATH_FWD_SCAL_FUN_COSH_HPP
#define STAN_MATH_FWD_SCAL_FUN_COSH_HPP
#include <stan/math/fwd/meta.hpp>
#include <stan/math/fwd/core.hpp>
#include <cmath>
namespace stan {
namespace math {
template <typename T>
inline fvar<T> cosh(const fvar<T>& x) {
using std::cosh;
using std::sinh;
return fvar<T>(cosh(x.val_), x.d_ * sinh(x.val_));
}
} // namespace math
} // namespace stan
#endif
|
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_BIT_FLIPBIT_HPP
#define SPROUT_BIT_FLIPBIT_HPP
#include <type_traits>
#include <sprout/config.hpp>
namespace sprout {
//
// flipbit
//
template<typename Integral>
inline SPROUT_CONSTEXPR typename std::enable_if<
std::is_integral<Integral>::value,
Integral
>::type
flipbit(Integral x, int b) SPROUT_NOEXCEPT {
return x ^ (Integral(1) << b);
}
} // namespace sprout
#endif // #ifndef SPROUT_BIT_FLIPBIT_HPP
|
#include <sstream>
#include <vector>
#include <algorithm>
#include "algol/stream/istream_range.hpp"
#include "gtest/gtest.h"
using istream_range = algol::stream::istream_range<uint32_t>;
class istream_range_fixture : public ::testing::Test {
protected:
std::istringstream sin_empty {""};
istream_range ir_empty {sin_empty};
std::istringstream sin {"1 2 3 4 5 6"};
istream_range ir {sin};
};
TEST_F(istream_range_fixture, empty)
{
EXPECT_EQ(std::begin(ir_empty), std::end(ir_empty));
EXPECT_FALSE(ir_empty);
EXPECT_TRUE(!ir_empty);
}
TEST_F(istream_range_fixture, not_empty)
{
EXPECT_NE(std::begin(ir), std::end(ir));
EXPECT_TRUE(ir);
EXPECT_FALSE(!ir);
}
TEST_F(istream_range_fixture, iteration)
{
std::vector<uint32_t> val;
std::copy(std::begin(ir), std::end(ir), std::back_inserter(val));
EXPECT_FALSE(ir);
EXPECT_EQ(val.size(), static_cast<std::size_t>(6));
auto minmax = std::minmax_element(std::begin(val), std::end(val));
EXPECT_EQ(*minmax.first, 1u);
EXPECT_EQ(*minmax.second, 6u);
}
|
/*#include <fstream>
#include <utility>
#include <vector>
#include "IdentityFunction.h"
#include "HyperbolicTangent.h"
#include "MultiLayerPerceptron.h"
#include "PerceptronTrainer.h"
int main() {
mlp::MultiLayerPerceptron<double> network(1, {
{17, mlp::HyperbolicTangent<double>()},
{1, mlp::IdentityFunction<double>()},
});
mlp::PerceptronTrainer<double> trainer(1, 1);
trainer.setMaxEpochs(10000);
trainer.setErrorThreshold(0.06);
trainer.setInitialWeightRange(0.25);
trainer.setLearningRate(1e-4);
trainer.setMomentum(0.9);
std::ifstream trainingData("approximation_train_1.txt");
for (double input, output; trainingData >> input >> output;) {
trainer.addTest(&input, &output);
}
trainer.train(network);
std::vector<std::pair<double, double>> data;
std::ifstream testData("approximation_test.txt");
for (double input, output; testData >> input >> output;) {
data.emplace_back(input, output);
}
std::ofstream out("approximation_results_1.txt");
out << "Argument\tExpected\tObtained\n";
for (const auto& inout : data) {
double output;
network.test(&inout.first, &output);
out << inout.first << '\t' << inout.second << '\t' << output << '\n';
}
return 0;
}*/
#include <algorithm>
#include <array>
#include <fstream>
#include <iostream>
#include <random>
#include <utility>
#include "IdentityFunction.h"
#include "LogisticFunction.h"
#include "MultiLayerPerceptron.h"
#include "RandomNumberGenerator.h"
#include "PerceptronTrainer.h"
int main() {
mlp::MultiLayerPerceptron<double> network(4, {
{17, mlp::LogisticFunction<double>()},
{3, mlp::LogisticFunction<double>()},
});
mlp::PerceptronTrainer<double> trainer(4, 3);
trainer.setMaxEpochs(2000);
trainer.setErrorThreshold(0.01);
trainer.setInitialWeightRange(0.25);
trainer.setLearningRate(1e-3);
trainer.setMomentum(0.8);
std::ifstream trainingData("classification_train.txt");
for (double input[4]; trainingData >> input[0] >> input[1] >> input[2] >> input[3];) {
double output[3] {};
int outcome;
trainingData >> outcome;
output[outcome - 1] = 1.0;
trainer.addTest(input, output);
}
trainer.train(network);
std::vector<std::pair<std::array<double, 4>, int>> data;
std::ifstream testData("classification_test.txt");
for (std::array<double, 4> input; testData >> input[0] >> input[1] >> input[2] >> input[3];) {
int outcome;
testData >> outcome;
data.emplace_back(input, outcome);
}
std::ofstream out("classification_results_1.txt");
out << "Expected\tObtained\n";
int correct = 0;
for (const auto& inout : data) {
double output[3];
network.test(inout.first.begin(), output);
int result = std::max_element(std::begin(output), std::end(output)) - output + 1;
out << inout.second << '\t' << result << '\n';
correct += result == inout.second;
}
std::cout << correct << " out of " << data.size() << " guessed" << std::endl;
return 0;
}
|
/*
* Copyright 2010, Haiku, Inc. All rights reserved.
* Copyright 2008, Pier Luigi Fiorini.
* Distributed under the terms of the MIT License.
*
* Authors:
* Pier Luigi Fiorini <pierluigi.fiorini@gmail.com>
* Stephan Aรmus <superstippi@gmx.de>
*/
#include <stdio.h>
#include <stdlib.h>
#include <Application.h>
#include <Bitmap.h>
#include <IconUtils.h>
#include <List.h>
#include <Mime.h>
#include <Notification.h>
#include <Path.h>
#include <TranslationUtils.h>
const char* kSignature = "application/x-vnd.Haiku-notify";
const char* kSmallIconAttribute = "BEOS:M:STD_ICON";
const char* kLargeIconAttribute = "BEOS:L:STD_ICON";
const char* kIconAttribute = "BEOS:ICON";
const char *kTypeNames[] = {
"information",
"important",
"error",
"progress",
NULL
};
const int32 kErrorInitFail = 127;
const int32 kErrorArgumentsFail = 126;
class NotifyApp : public BApplication {
public:
NotifyApp();
virtual ~NotifyApp();
virtual void ReadyToRun();
virtual void ArgvReceived(int32 argc, char** argv);
bool HasGoodArguments() const
{ return fHasGoodArguments; }
private:
bool fHasGoodArguments;
notification_type fType;
BString fGroup;
BString fTitle;
BString fMsgId;
float fProgress;
bigtime_t fTimeout;
BString fIconFile;
entry_ref fFileRef;
BString fContent;
BString fOnClickApp;
bool fHasFile;
entry_ref fFile;
BList* fRefs;
BList* fArgv;
void _Usage() const;
BBitmap* _GetBitmap(const entry_ref* ref) const;
};
NotifyApp::NotifyApp()
:
BApplication(kSignature),
fHasGoodArguments(false),
fType(B_INFORMATION_NOTIFICATION),
fProgress(0.0f),
fTimeout(-1),
fHasFile(false)
{
fRefs = new BList();
fArgv = new BList();
}
NotifyApp::~NotifyApp()
{
for (int32 i = 0; void* item = fRefs->ItemAt(i); i++)
delete (BEntry*)item;
delete fRefs;
for (int32 i = 0; void* item = fArgv->ItemAt(i); i++)
delete (BString*)item;
delete fArgv;
}
void
NotifyApp::ArgvReceived(int32 argc, char** argv)
{
const uint32 kArgCount = argc - 1;
uint32 index = 1;
// Look for valid options
for (; index <= kArgCount; ++index) {
if (argv[index][0] == '-' && argv[index][1] == '-') {
const char* option = argv[index] + 2;
if (++index > kArgCount) {
// No argument to option
fprintf(stderr, "Missing argument to option --%s\n\n", option);
return;
}
const char* argument = argv[index];
if (strcmp(option, "type") == 0) {
for (int32 i = 0; kTypeNames[i]; i++) {
if (strncmp(kTypeNames[i], argument, strlen(argument)) == 0)
fType = (notification_type)i;
}
} else if (strcmp(option, "group") == 0)
fGroup = argument;
else if (strcmp(option, "title") == 0)
fTitle = argument;
else if (strcmp(option, "messageID") == 0)
fMsgId = argument;
else if (strcmp(option, "progress") == 0)
fProgress = atof(argument);
else if (strcmp(option, "timeout") == 0)
fTimeout = atol(argument) * 1000000;
else if (strcmp(option, "icon") == 0) {
fIconFile = argument;
if (get_ref_for_path(fIconFile.String(), &fFileRef) < B_OK) {
fprintf(stderr, "Bad icon path!\n\n");
return;
}
} else if (strcmp(option, "onClickApp") == 0)
fOnClickApp = argument;
else if (strcmp(option, "onClickFile") == 0) {
if (get_ref_for_path(argument, &fFile) != B_OK) {
fprintf(stderr, "Bad path for --onClickFile!\n\n");
return;
}
fHasFile = true;
} else if (strcmp(option, "onClickRef") == 0) {
entry_ref ref;
if (get_ref_for_path(argument, &ref) != B_OK) {
fprintf(stderr, "Bad path for --onClickRef!\n\n");
return;
}
fRefs->AddItem(new BEntry(&ref));
} else if (strcmp(option, "onClickArgv") == 0)
fArgv->AddItem(new BString(argument));
else {
// Unrecognized option
fprintf(stderr, "Unrecognized option --%s\n\n", option);
return;
}
} else {
// Option doesn't start with '--'
break;
}
if (index == kArgCount) {
// No text argument provided, only '--' arguments
fprintf(stderr, "Missing message argument!\n\n");
return;
}
}
fContent = argv[index];
fHasGoodArguments = true;
}
void
NotifyApp::_Usage() const
{
fprintf(stderr, "Usage: notify [OPTION]... [MESSAGE]\n"
"Send notifications to notification_server.\n"
" --type <type>\tNotification type,\n"
" \t <type> - \"information\" is assumed by default: ");
for (int32 i = 0; kTypeNames[i]; i++)
fprintf(stderr, kTypeNames[i + 1] ? "%s|" : "%s\n", kTypeNames[i]);
fprintf(stderr,
" --group <group>\tGroup\n"
" --title <title>\tMessage title\n"
" --messageID <msg id>\tMessage ID\n"
" --progress <float>\tProgress, value between 0.0 and 1.0 - if type is set to progress\n"
" --timeout <secs>\tSpecify timeout\n"
" --onClickApp <signature>\tApplication to open when notification is clicked\n"
" --onClickFile <fullpath>\tFile to open when notification is clicked\n"
" --onClickRef <fullpath>\tFile to open with the application when notification is clicked\n"
" --onClickArgv <arg>\tArgument to the application when notification is clicked\n"
" --icon <icon file> Icon\n");
}
BBitmap*
NotifyApp::_GetBitmap(const entry_ref* ref) const
{
// First try by contents
BBitmap* bitmap = BTranslationUtils::GetBitmap(ref);
if (bitmap)
return bitmap;
// Then, try reading its attribute
BNode node(BPath(ref).Path());
bitmap = new BBitmap(BRect(0, 0, (float)B_LARGE_ICON - 1,
(float)B_LARGE_ICON - 1), B_RGBA32);
if (BIconUtils::GetIcon(&node, kIconAttribute, kSmallIconAttribute,
kLargeIconAttribute, B_LARGE_ICON, bitmap) != B_OK) {
delete bitmap;
bitmap = NULL;
}
return bitmap;
}
void
NotifyApp::ReadyToRun()
{
if (HasGoodArguments()) {
BNotification notification(fType);
if (fGroup != "")
notification.SetGroup(fGroup);
if (fTitle != "")
notification.SetTitle(fTitle);
if (fContent != "")
notification.SetContent(fContent);
if (fMsgId != "")
notification.SetMessageID(fMsgId);
if (fType == B_PROGRESS_NOTIFICATION)
notification.SetProgress(fProgress);
if (fIconFile != "") {
BBitmap* bitmap = _GetBitmap(&fFileRef);
if (bitmap) {
notification.SetIcon(bitmap);
delete bitmap;
}
}
if (fOnClickApp != "")
notification.SetOnClickApp(fOnClickApp);
if (fHasFile)
notification.SetOnClickFile(&fFile);
for (int32 i = 0; void* item = fRefs->ItemAt(i); i++) {
BEntry* entry = (BEntry*)item;
entry_ref ref;
if (entry->GetRef(&ref) == B_OK)
notification.AddOnClickRef(&ref);
}
for (int32 i = 0; void* item = fArgv->ItemAt(i); i++) {
BString* arg = (BString*)item;
notification.AddOnClickArg(arg->String());
}
status_t ret = notification.Send(fTimeout);
if (ret != B_OK) {
fprintf(stderr, "Failed to deliver notification: %s\n",
strerror(ret));
}
} else
_Usage();
Quit();
}
int
main(int argc, char** argv)
{
NotifyApp app;
if (app.InitCheck() != B_OK)
return kErrorInitFail;
app.Run();
if (!app.HasGoodArguments())
return kErrorArgumentsFail;
return 0;
}
|
# /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_DEBUG_ERROR_HPP
# define BOOST_PREPROCESSOR_DEBUG_ERROR_HPP
#
# include <boost/preprocessor/cat.hpp>
# include <boost/preprocessor/config/config.hpp>
#
# /* BOOST_PP_ERROR */
#
# if BOOST_PP_CONFIG_ERRORS
# define BOOST_PP_ERROR(code) BOOST_PP_CAT(BOOST_PP_ERROR_, code)
# endif
#
# define BOOST_PP_ERROR_0x0000 BOOST_PP_ERROR(0x0000, BOOST_PP_INDEX_OUT_OF_BOUNDS)
# define BOOST_PP_ERROR_0x0001 BOOST_PP_ERROR(0x0001, BOOST_PP_WHILE_OVERFLOW)
# define BOOST_PP_ERROR_0x0002 BOOST_PP_ERROR(0x0002, BOOST_PP_FOR_OVERFLOW)
# define BOOST_PP_ERROR_0x0003 BOOST_PP_ERROR(0x0003, BOOST_PP_REPEAT_OVERFLOW)
# define BOOST_PP_ERROR_0x0004 BOOST_PP_ERROR(0x0004, BOOST_PP_LIST_FOLD_OVERFLOW)
# define BOOST_PP_ERROR_0x0005 BOOST_PP_ERROR(0x0005, BOOST_PP_SEQ_FOLD_OVERFLOW)
# define BOOST_PP_ERROR_0x0006 BOOST_PP_ERROR(0x0006, BOOST_PP_ARITHMETIC_OVERFLOW)
# define BOOST_PP_ERROR_0x0007 BOOST_PP_ERROR(0x0007, BOOST_PP_DIVISION_BY_ZERO)
#
# endif
|
//===- FunctionComparator.cpp - Unit tests for FunctionComparator ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/FunctionComparator.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;
/// Generates a simple test function.
struct TestFunction {
Function *F;
BasicBlock *BB;
Constant *C;
Instruction *I;
Type *T;
TestFunction(LLVMContext &Ctx, Module &M, int addVal) {
IRBuilder<> B(Ctx);
T = B.getInt8Ty();
F = Function::Create(FunctionType::get(T, {B.getInt8PtrTy()}, false),
GlobalValue::ExternalLinkage, "F", &M);
BB = BasicBlock::Create(Ctx, "", F);
B.SetInsertPoint(BB);
Argument *PointerArg = &*F->arg_begin();
LoadInst *LoadInst = B.CreateLoad(PointerArg);
C = B.getInt8(addVal);
I = cast<Instruction>(B.CreateAdd(LoadInst, C));
B.CreateRet(I);
}
};
/// A class for testing the FunctionComparator API.
///
/// The main purpose is to test if the required protected functions are
/// accessible from a derived class of FunctionComparator.
class TestComparator : public FunctionComparator {
public:
TestComparator(const Function *F1, const Function *F2,
GlobalNumberState *GN)
: FunctionComparator(F1, F2, GN) {
}
bool testFunctionAccess(const Function *F1, const Function *F2) {
// Test if FnL and FnR are accessible.
return F1 == FnL && F2 == FnR;
}
int testCompare() {
return compare();
}
int testCompareSignature() {
beginCompare();
return compareSignature();
}
int testCmpBasicBlocks(BasicBlock *BBL, BasicBlock *BBR) {
beginCompare();
return cmpBasicBlocks(BBL, BBR);
}
int testCmpConstants(const Constant *L, const Constant *R) {
beginCompare();
return cmpConstants(L, R);
}
int testCmpGlobalValues(GlobalValue *L, GlobalValue *R) {
beginCompare();
return cmpGlobalValues(L, R);
}
int testCmpValues(const Value *L, const Value *R) {
beginCompare();
return cmpValues(L, R);
}
int testCmpOperations(const Instruction *L, const Instruction *R,
bool &needToCmpOperands) {
beginCompare();
return cmpOperations(L, R, needToCmpOperands);
}
int testCmpTypes(Type *TyL, Type *TyR) {
beginCompare();
return cmpTypes(TyL, TyR);
}
int testCmpPrimitives() {
beginCompare();
return
cmpNumbers(2, 3) +
cmpAPInts(APInt(32, 2), APInt(32, 3)) +
cmpAPFloats(APFloat(2.0), APFloat(3.0)) +
cmpMem("2", "3");
}
};
/// A sanity check for the FunctionComparator API.
TEST(FunctionComparatorTest, TestAPI) {
LLVMContext C;
Module M("test", C);
TestFunction F1(C, M, 27);
TestFunction F2(C, M, 28);
GlobalNumberState GN;
TestComparator Cmp(F1.F, F2.F, &GN);
EXPECT_TRUE(Cmp.testFunctionAccess(F1.F, F2.F));
EXPECT_EQ(Cmp.testCompare(), -1);
EXPECT_EQ(Cmp.testCompareSignature(), 0);
EXPECT_EQ(Cmp.testCmpBasicBlocks(F1.BB, F2.BB), -1);
EXPECT_EQ(Cmp.testCmpConstants(F1.C, F2.C), -1);
EXPECT_EQ(Cmp.testCmpGlobalValues(F1.F, F2.F), -1);
EXPECT_EQ(Cmp.testCmpValues(F1.I, F2.I), 0);
bool needToCmpOperands = false;
EXPECT_EQ(Cmp.testCmpOperations(F1.I, F2.I, needToCmpOperands), 0);
EXPECT_TRUE(needToCmpOperands);
EXPECT_EQ(Cmp.testCmpTypes(F1.T, F2.T), 0);
EXPECT_EQ(Cmp.testCmpPrimitives(), -4);
}
|
/****************************************************************************
*
* Copyright (c) 2021 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file sht3x.c
*
* I2C driver for temperature/humidity sensor SHT3x by senserion
*
* @author Roman Dvorak <dvorakroman@thunderfly.cz>
*
*/
#include "sht3x.h"
SHT3X::SHT3X(const I2CSPIDriverConfig &config) :
I2C(config),
ModuleParams(nullptr),
I2CSPIDriver(config)
{
}
uint8_t SHT3X::calc_crc(uint8_t data[2])
{
uint8_t crc = 0xFF;
for (int i = 0; i < 2; i++) {
crc ^= data[i];
for (uint8_t bit = 8; bit > 0; --bit) {
if (crc & 0x80) {
crc = (crc << 1) ^ 0x31u;
} else {
crc = (crc << 1);
}
}
}
return crc;
}
int SHT3X::set_pointer(uint16_t command)
{
if (_last_command != command) {
uint8_t cmd[2];
cmd[0] = static_cast<uint8_t>(command >> 8);
cmd[1] = static_cast<uint8_t>(command & 0xff);
_last_command = command;
return transfer(&cmd[0], 2, nullptr, 0);
} else {
return 0;
}
}
int SHT3X::read_data(uint16_t command, uint8_t *data_ptr, uint8_t length)
{
set_pointer(command);
uint8_t raw_data[length];
transfer(nullptr, 0, &raw_data[0], length);
uint8_t crc_err = 0;
for (int i = 0; i < length / 3; ++i) {
uint8_t crc_data[2] = {raw_data[i * 3], raw_data[i * 3 + 1]};
if (raw_data[i * 3 + 2] != calc_crc(crc_data)) {
crc_err ++;
}
*(data_ptr + i * 2) = raw_data[i * 3];
*(data_ptr + i * 2 + 1) = raw_data[i * 3 + 1];
}
return crc_err;
}
int SHT3X::write_data(uint16_t command, uint8_t buffer[], uint8_t length)
{
_last_command = command;
uint8_t cmd[2 + 3 * length / 2];
cmd[0] = static_cast<uint8_t>(command >> 8);
cmd[1] = static_cast<uint8_t>(command & 0xff);
for (int i = 0; i < length / 2; ++i) {
cmd[2 + 3 * i] = buffer[2 * i];
cmd[2 + 3 * i + 1] = buffer[2 * i + 1];
uint8_t crc_data[2] = {buffer[2 * i], buffer[2 * i + 1]};
cmd[2 + 3 * i + 2] = calc_crc(crc_data);
}
return transfer(&cmd[0], sizeof(cmd), nullptr, 0);
}
void SHT3X::sensor_compouse_msg(bool send)
{
uint8_t data[4];
int error = read_data(SHT3x_CMD_FETCH_DATA, &data[0], 6);
if (error == PX4_OK) {
measurement_time = hrt_absolute_time();
measurement_index ++;
measured_temperature = (float) 175 * (data[0] << 8 | data[1]) / 65535 - 45;
measured_humidity = (float) 100 * (data[2] << 8 | data[3]) / 65535;
if (send) {
sensor_hygrometer_s msg{};
msg.timestamp = hrt_absolute_time();
msg.timestamp_sample = measurement_time;
msg.temperature = measured_temperature;
msg.humidity = measured_humidity;
msg.device_id = _sht_info.serial_number;
_sensor_hygrometer_pub.publish(msg);
}
}
}
int
SHT3X::probe()
{
uint8_t type[2];
uint8_t nvalid;
nvalid = read_data(SHT3X_CMD_READ_STATUS, &type[0], 3);
return (!(nvalid == PX4_OK));
// 0 means I can see sensor
}
int SHT3X::init()
{
if (I2C::init() != PX4_OK) {
return PX4_ERROR;
}
_sensor_hygrometer_pub.advertise();
ScheduleOnInterval(50000);
return PX4_OK;
}
int SHT3X::init_sensor()
{
set_pointer(SHT3X_CMD_CLEAR_STATUS);
px4_usleep(2000);
// Get sensor serial number
uint8_t serial[4];
read_data(SHT3x_CMD_READ_SN, &serial[0], 6);
_sht_info.serial_number = ((uint32_t)serial[0] << 24
| (uint32_t)serial[1] << 16
| (uint32_t)serial[2] << 8
| (uint32_t)serial[3]);
set_pointer(SHT3x_CMD_PERIODIC_2HZ_MEDIUM);
px4_usleep(2000);
probe();
PX4_INFO("Connected to SHT3x sensor, SN: %ld", _sht_info.serial_number);
return PX4_OK;
}
void SHT3X::RunImpl()
{
switch (_state) {
case sht3x_state::INIT:
probe();
init_sensor();
_state = sht3x_state::MEASUREMENT;
break;
case sht3x_state::MEASUREMENT:
if ((hrt_absolute_time() - measurement_time) > 200000) {
sensor_compouse_msg(1);
}
if ((hrt_absolute_time() - measurement_time) > 3000000) {
_state = sht3x_state::ERROR_READOUT;
}
break;
case sht3x_state::ERROR_GENERAL:
case sht3x_state::ERROR_READOUT: {
if (_last_state != _state) {
PX4_INFO("I cant get new data. The sensor may be disconnected.");
}
if (probe() == PX4_OK) {
_state = sht3x_state::INIT;
}
}
break;
}
if (_last_state != _state) {
_time_in_state = hrt_absolute_time();
_last_state = _state;
}
}
void
SHT3X::custom_method(const BusCLIArguments &cli)
{
switch (cli.custom1) {
case 1: {
PX4_INFO("Last measured values (%.3fs ago, #%d)", (double)(hrt_absolute_time() - measurement_time) / 1000000.0,
measurement_index);
PX4_INFO("Temp: %.3f, Hum: %.3f", (double)measured_temperature, (double)measured_humidity);
}
break;
case 2: {
_state = sht3x_state::INIT;
}
break;
}
}
void SHT3X::print_status()
{
PX4_INFO("SHT3X sensor");
I2CSPIDriverBase::print_status();
PX4_INFO("SN: %ld", _sht_info.serial_number);
PX4_INFO("Status: %s", sht_state_names[_state]);
}
void SHT3X::print_usage()
{
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
SHT3x Temperature and Humidity Sensor Driver by Senserion.
### Examples
CLI usage example:
$ sht3x start -X
Start the sensor driver on the external bus
$ sht3x status
Print driver status
$ sht3x values
Print last measured values
$ sht3x reset
Reinitialize senzor, reset flags
)DESCR_STR");
PRINT_MODULE_USAGE_NAME("sht3x", "driver");
PRINT_MODULE_USAGE_COMMAND("start");
PRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false);
PRINT_MODULE_USAGE_PARAMS_I2C_ADDRESS(0x44);
PRINT_MODULE_USAGE_PARAMS_I2C_KEEP_RUNNING_FLAG();
PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
PRINT_MODULE_USAGE_COMMAND_DESCR("values", "Print actual data");
PRINT_MODULE_USAGE_COMMAND_DESCR("reset", "Reinitialize sensor");
}
int sht3x_main(int argc, char *argv[])
{
using ThisDriver = SHT3X;
BusCLIArguments cli{true, false};
cli.default_i2c_frequency = 400000;
cli.i2c_address = 0x44;
cli.support_keep_running = true;
const char *verb = cli.parseDefaultArguments(argc, argv);
if (!verb) {
ThisDriver::print_usage();
return -1;
}
BusInstanceIterator iterator(MODULE_NAME, cli, DRV_HYGRO_DEVTYPE_SHT3X);
if (!strcmp(verb, "start")) {
return ThisDriver::module_start(cli, iterator);
}
if (!strcmp(verb, "stop")) {
return ThisDriver::module_stop(iterator);
}
if (!strcmp(verb, "status")) {
return ThisDriver::module_status(iterator);
}
if (!strcmp(verb, "values")) {
cli.custom1 = 1;
return ThisDriver::module_custom_method(cli, iterator, false);
}
if (!strcmp(verb, "reset")) {
cli.custom1 = 2;
return ThisDriver::module_custom_method(cli, iterator, false);
}
ThisDriver::print_usage();
return -1;
}
|
#include "config_functions.h"
#if USE_H3
#include <Columns/ColumnsNumber.h>
#include <DataTypes/DataTypesNumber.h>
#include <Functions/FunctionFactory.h>
#include <Functions/IFunction.h>
#include <IO/WriteHelpers.h>
#include <Common/typeid_cast.h>
#include <base/range.h>
#include <constants.h>
#include <h3api.h>
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int ARGUMENT_OUT_OF_BOUND;
extern const int ILLEGAL_COLUMN;
}
namespace
{
class FunctionH3HexAreaM2 : public IFunction
{
public:
static constexpr auto name = "h3HexAreaM2";
static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionH3HexAreaM2>(); }
std::string getName() const override { return name; }
size_t getNumberOfArguments() const override { return 1; }
bool useDefaultImplementationForConstants() const override { return true; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }
DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
const auto * arg = arguments[0].get();
if (!WhichDataType(arg).isUInt8())
throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Illegal type {} of argument {} of function {}. Must be UInt8",
arg->getName(), 1, getName());
return std::make_shared<DataTypeFloat64>();
}
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{
const auto * column = checkAndGetColumn<ColumnUInt8>(arguments[0].column.get());
if (!column)
throw Exception(
ErrorCodes::ILLEGAL_COLUMN,
"Illegal type {} of argument {} of function {}. Must be UInt8",
arguments[0].column->getName(),
1,
getName());
const auto & data = column->getData();
auto dst = ColumnVector<Float64>::create();
auto & dst_data = dst->getData();
dst_data.resize(input_rows_count);
for (size_t row = 0; row < input_rows_count; ++row)
{
const UInt8 resolution = data[row];
if (resolution > MAX_H3_RES)
throw Exception(
ErrorCodes::ARGUMENT_OUT_OF_BOUND,
"The argument 'resolution' ({}) of function {} is out of bounds because the maximum resolution in H3 library is ",
toString(resolution),
getName(),
MAX_H3_RES);
Float64 res = getHexagonAreaAvgM2(resolution);
dst_data[row] = res;
}
return dst;
}
};
}
void registerFunctionH3HexAreaM2(FunctionFactory & factory)
{
factory.registerFunction<FunctionH3HexAreaM2>();
}
}
#endif
|
#include "ValueComboBox.hpp"
#include <iostream>
namespace protobuf_decoder
{
ValueComboBox::ValueComboBox(const std::vector<std::string>& iValues)
{
setValues(iValues);
set_margin_bottom(20);
}
void ValueComboBox::setValues(const std::vector<std::string>& iValues)
{
// Set up tree model.
_refTreeModel = Gtk::ListStore::create(_columns);
set_model(_refTreeModel);
std::cout << "ABAB1" << std::endl;
_refTreeModel->clear();
std::cout << "ABAB1" << std::endl;
// Fill rows with values.
for (auto aValue : iValues)
{
std::cout << "ABAB1" << std::endl;
Gtk::TreeModel::Row row = *(_refTreeModel->append());
row[_columns._name] = aValue;
//set_active(row);
}
clear();
pack_start(_columns._name);
}
std::string ValueComboBox::getActive()
{
Gtk::TreeModel::iterator iter = get_active();
if(iter)
{
Gtk::TreeModel::Row row = *iter;
if(row)
{
Glib::ustring aValue = row[_columns._name];
return aValue;
}
}
return "";
}
void ValueComboBox::setActive(const std::string& iValue)
{
std::cout << "set active: " << iValue << std::endl;
for (auto aRow : _refTreeModel->children())
{
std::cout << "set active: " << iValue << std::endl;
if (aRow[_columns._name] == iValue)
{
std::cout << "set active: " << iValue << std::endl;
set_active(*aRow);
}
}
}
}
|
#include "iostream"
#include "linkedlist.h"
#include "doublylinkedlist.h"
using namespace linkedlist;
int main()
{
LinkedList linkedList;
linkedList.print();
std::cout << "is linkedlist empty=" << std::boolalpha << linkedList.empty() << std::endl;
linkedList.add(3);
linkedList.add(1);
linkedList.add(5);
linkedList.add(7);
linkedList.add(13);
linkedList.print();
linkedList.remove_value(5);
linkedList.print();
linkedList.push_before(2, 31);
linkedList.print();
linkedList.push_after(1, 17);
linkedList.print();
std::cout << "is linkedlist empty=" << std::boolalpha << linkedList.empty() << std::endl;
linkedList.reverse();
std::cout << "After reversing the linked list" << std::endl;
linkedList.print();
linkedList.reverse();
std::cout << "After reversing the linked list" << std::endl;
linkedList.print();
linkedList.erase(4);
linkedList.print();
std::cout << "First: " << linkedList.front() << " --- Last: " << linkedList.back() << std::endl;
linkedList.reverse();
linkedList.print();
std::cout << "First: " << linkedList.front() << " --- Last: " << linkedList.back() << std::endl;
try
{
//linkedList.remove_value(23);
Node* node = linkedList.at(7);
}
catch (std::exception &e)
{
std::cout << "Exception catched: " << e.what() << std::endl;
}
doublylinkedlist::DoublyLinkedList dll;
dll.print();
std::cout << "is linkedlist empty=" << std::boolalpha << dll.empty() << std::endl;
dll.add(3);
dll.add(1);
dll.add(5);
dll.add(7);
dll.add(13);
dll.print();
dll.remove_value(5);
dll.print();
dll.push_before(2, 31);
dll.print();
dll.push_after(1, 17);
dll.print();
std::cout << "is linkedlist empty=" << std::boolalpha << dll.empty() << std::endl;
dll.erase(4);
dll.print();
std::cout << "First: " << dll.front() << " --- Last: " << dll.back() << std::endl;
dll.reverse();
dll.print();
std::cout << "First: " << dll.front() << " --- Last: " << dll.back() << std::endl;
try
{
//dll.remove_value(23);
doublylinkedlist::Node* node = dll.at(7);
}
catch (std::exception & e)
{
std::cout << "Exception catched: " << e.what() << std::endl;
}
return 0;
}
|
//
// XYO Win Library
//
// Copyright (c) 2018-2019 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#ifndef XYO_WIN_REGISTRY_H
#define XYO_WIN_REGISTRY_H
#ifndef XYO_WIN_HPP
#include "xyo-win.hpp"
#endif
namespace XYO
{
namespace Win
{
namespace Registry
{
XYO_WIN_EXPORT BOOL createKey(HKEY, char *);
XYO_WIN_EXPORT BOOL createKeyVolatile(HKEY, char *);
XYO_WIN_EXPORT BOOL writeString(HKEY, char *, char *, char *);
XYO_WIN_EXPORT BOOL writeDWord(HKEY, char *, char *, unsigned long int);
XYO_WIN_EXPORT BOOL readString(HKEY, char *, char *, char *, unsigned long int, char *);
XYO_WIN_EXPORT BOOL readDWord(HKEY, char *, char *, unsigned long int *, unsigned long int);
XYO_WIN_EXPORT BOOL deleteKey(HKEY, char *, char *, BOOL);
XYO_WIN_EXPORT BOOL getStringLength(HKEY masterkey, char *key, char *reg, LPDWORD out);
XYO_WIN_EXPORT BOOL createKeyW(HKEY, wchar_t *);
XYO_WIN_EXPORT BOOL createKeyVolatileW(HKEY, wchar_t *);
XYO_WIN_EXPORT BOOL writeStringW(HKEY, wchar_t *, wchar_t *, wchar_t *);
XYO_WIN_EXPORT BOOL writeDWordW(HKEY, wchar_t *, wchar_t *, unsigned long int);
XYO_WIN_EXPORT BOOL readStringW(HKEY, wchar_t *, wchar_t *, wchar_t *, unsigned long int, wchar_t *);
XYO_WIN_EXPORT BOOL readDWordW(HKEY, wchar_t *, wchar_t *, unsigned long int *, unsigned long int);
XYO_WIN_EXPORT BOOL deleteKeyW(HKEY, wchar_t *, wchar_t *, BOOL);
XYO_WIN_EXPORT BOOL getStringLengthW(HKEY masterkey, wchar_t *key, wchar_t *reg, LPDWORD out);
};
};
};
#endif
|
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qactiongroup.h"
#ifndef QT_NO_ACTION
#include "qaction_p.h"
#include "qapplication.h"
#include "qevent.h"
#include "qlist.h"
QT_BEGIN_NAMESPACE
class QActionGroupPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QActionGroup)
public:
QActionGroupPrivate() : exclusive(1), enabled(1), visible(1) { }
QList<QAction *> actions;
QPointer<QAction> current;
uint exclusive : 1;
uint enabled : 1;
uint visible : 1;
private:
void _q_actionTriggered(); //private slot
void _q_actionChanged(); //private slot
void _q_actionHovered(); //private slot
};
void QActionGroupPrivate::_q_actionChanged()
{
Q_Q(QActionGroup);
QAction *action = qobject_cast<QAction*>(q->sender());
Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionChanged", "internal error");
if(exclusive) {
if (action->isChecked()) {
if (action != current) {
if(current)
current->setChecked(false);
current = action;
}
} else if (action == current) {
current = 0;
}
}
}
void QActionGroupPrivate::_q_actionTriggered()
{
Q_Q(QActionGroup);
QAction *action = qobject_cast<QAction*>(q->sender());
Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionTriggered", "internal error");
emit q->triggered(action);
emit q->selected(action);
}
void QActionGroupPrivate::_q_actionHovered()
{
Q_Q(QActionGroup);
QAction *action = qobject_cast<QAction*>(q->sender());
Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionHovered", "internal error");
emit q->hovered(action);
}
/*!
\class QActionGroup
\brief The QActionGroup class groups actions together.
\ingroup mainwindow-classes
In some situations it is useful to group QAction objects together.
For example, if you have a \gui{Left Align} action, a \gui{Right
Align} action, a \gui{Justify} action, and a \gui{Center} action,
only one of these actions should be active at any one time. One
simple way of achieving this is to group the actions together in
an action group.
Here's a example (from the \l{mainwindows/menus}{Menus} example):
\snippet examples/mainwindows/menus/mainwindow.cpp 6
Here we create a new action group. Since the action group is
exclusive by default, only one of the actions in the group is
checked at any one time.
\img qactiongroup-align.png Alignment options in a QMenu
A QActionGroup emits an triggered() signal when one of its
actions is chosen. Each action in an action group emits its
triggered() signal as usual.
As stated above, an action group is \l exclusive by default; it
ensures that only one checkable action is active at any one time.
If you want to group checkable actions without making them
exclusive, you can turn of exclusiveness by calling
setExclusive(false).
Actions can be added to an action group using addAction(), but it
is usually more convenient to specify a group when creating
actions; this ensures that actions are automatically created with
a parent. Actions can be visually separated from each other by
adding a separator action to the group; create an action and use
QAction's \l {QAction::}{setSeparator()} function to make it
considered a separator. Action groups are added to widgets with
the QWidget::addActions() function.
\sa QAction
*/
/*!
Constructs an action group for the \a parent object.
The action group is exclusive by default. Call setExclusive(false)
to make the action group non-exclusive.
*/
QActionGroup::QActionGroup(QObject* parent) : QObject(*new QActionGroupPrivate, parent)
{
}
/*!
Destroys the action group.
*/
QActionGroup::~QActionGroup()
{
}
/*!
\fn QAction *QActionGroup::addAction(QAction *action)
Adds the \a action to this group, and returns it.
Normally an action is added to a group by creating it with the
group as its parent, so this function is not usually used.
\sa QAction::setActionGroup()
*/
QAction *QActionGroup::addAction(QAction* a)
{
Q_D(QActionGroup);
if(!d->actions.contains(a)) {
d->actions.append(a);
QObject::connect(a, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
QObject::connect(a, SIGNAL(changed()), this, SLOT(_q_actionChanged()));
QObject::connect(a, SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
}
if(!a->d_func()->forceDisabled) {
a->setEnabled(d->enabled);
a->d_func()->forceDisabled = false;
}
if(!a->d_func()->forceInvisible) {
a->setVisible(d->visible);
a->d_func()->forceInvisible = false;
}
if(a->isChecked())
d->current = a;
QActionGroup *oldGroup = a->d_func()->group;
if(oldGroup != this) {
if (oldGroup)
oldGroup->removeAction(a);
a->d_func()->group = this;
}
return a;
}
/*!
Creates and returns an action with \a text. The newly created
action is a child of this action group.
Normally an action is added to a group by creating it with the
group as parent, so this function is not usually used.
\sa QAction::setActionGroup()
*/
QAction *QActionGroup::addAction(const QString &text)
{
return new QAction(text, this);
}
/*!
Creates and returns an action with \a text and an \a icon. The
newly created action is a child of this action group.
Normally an action is added to a group by creating it with the
group as its parent, so this function is not usually used.
\sa QAction::setActionGroup()
*/
QAction *QActionGroup::addAction(const QIcon &icon, const QString &text)
{
return new QAction(icon, text, this);
}
/*!
Removes the \a action from this group. The action will have no
parent as a result.
\sa QAction::setActionGroup()
*/
void QActionGroup::removeAction(QAction *action)
{
Q_D(QActionGroup);
if (d->actions.removeAll(action)) {
if (action == d->current)
d->current = 0;
QObject::disconnect(action, SIGNAL(triggered()), this, SLOT(_q_actionTriggered()));
QObject::disconnect(action, SIGNAL(changed()), this, SLOT(_q_actionChanged()));
QObject::disconnect(action, SIGNAL(hovered()), this, SLOT(_q_actionHovered()));
action->d_func()->group = 0;
}
}
/*!
Returns the list of this groups's actions. This may be empty.
*/
QList<QAction*> QActionGroup::actions() const
{
Q_D(const QActionGroup);
return d->actions;
}
/*!
\property QActionGroup::exclusive
\brief whether the action group does exclusive checking
If exclusive is true, only one checkable action in the action group
can ever be active at any time. If the user chooses another
checkable action in the group, the one they chose becomes active and
the one that was active becomes inactive.
\sa QAction::checkable
*/
void QActionGroup::setExclusive(bool b)
{
Q_D(QActionGroup);
d->exclusive = b;
}
bool QActionGroup::isExclusive() const
{
Q_D(const QActionGroup);
return d->exclusive;
}
/*!
\fn void QActionGroup::setDisabled(bool b)
This is a convenience function for the \l enabled property, that
is useful for signals--slots connections. If \a b is true the
action group is disabled; otherwise it is enabled.
*/
/*!
\property QActionGroup::enabled
\brief whether the action group is enabled
Each action in the group will be enabled or disabled unless it
has been explicitly disabled.
\sa QAction::setEnabled()
*/
void QActionGroup::setEnabled(bool b)
{
Q_D(QActionGroup);
d->enabled = b;
for(QList<QAction*>::const_iterator it = d->actions.constBegin(); it != d->actions.constEnd(); ++it) {
if(!(*it)->d_func()->forceDisabled) {
(*it)->setEnabled(b);
(*it)->d_func()->forceDisabled = false;
}
}
}
bool QActionGroup::isEnabled() const
{
Q_D(const QActionGroup);
return d->enabled;
}
/*!
Returns the currently checked action in the group, or 0 if none
are checked.
*/
QAction *QActionGroup::checkedAction() const
{
Q_D(const QActionGroup);
return d->current;
}
/*!
\property QActionGroup::visible
\brief whether the action group is visible
Each action in the action group will match the visible state of
this group unless it has been explicitly hidden.
\sa QAction::setEnabled()
*/
void QActionGroup::setVisible(bool b)
{
Q_D(QActionGroup);
d->visible = b;
for(QList<QAction*>::Iterator it = d->actions.begin(); it != d->actions.end(); ++it) {
if(!(*it)->d_func()->forceInvisible) {
(*it)->setVisible(b);
(*it)->d_func()->forceInvisible = false;
}
}
}
bool QActionGroup::isVisible() const
{
Q_D(const QActionGroup);
return d->visible;
}
/*!
\fn void QActionGroup::triggered(QAction *action)
This signal is emitted when the given \a action in the action
group is activated by the user; for example, when the user clicks
a menu option, toolbar button, or presses an action's shortcut key
combination.
Connect to this signal for command actions.
\sa QAction::activate()
*/
/*!
\fn void QActionGroup::hovered(QAction *action)
This signal is emitted when the given \a action in the action
group is highlighted by the user; for example, when the user
pauses with the cursor over a menu option, toolbar button, or
presses an action's shortcut key combination.
\sa QAction::activate()
*/
/*!
\fn void QActionGroup::add(QAction* a)
Use addAction() instead.
*/
/*!
\fn void QActionGroup::addSeparator()
Normally you add a separator to the menus or widgets to which
actions are added, so this function is very rarely needed.
\oldcode
actionGroup->addSeparator();
\newcode
QAction *separator = new QAction(this);
separator->setSeparator(true);
actionGroup->addAction(separator);
\endcode
*/
/*!
\fn bool QActionGroup::addTo(QWidget *widget)
\oldcode
actionGroup->addTo(widget);
\newcode
widget->addActions(actionGroup->actions());
\endcode
*/
/*!
\fn void QActionGroup::selected(QAction *action);
Use triggered() instead.
*/
QT_END_NAMESPACE
#include "moc_qactiongroup.cpp"
#endif // QT_NO_ACTION
|
/*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berryWorkbenchAdvisor.h"
#include <Poco/Exception.h>
namespace berry
{
WorkbenchAdvisor::WorkbenchAdvisor()
{
// do nothing
}
WorkbenchAdvisor::~WorkbenchAdvisor()
{
}
void WorkbenchAdvisor::InternalBasicInitialize(IWorkbenchConfigurer::Pointer configurer)
{
if (workbenchConfigurer.IsNotNull())
{
throw Poco::IllegalStateException();
}
this->workbenchConfigurer = configurer;
this->Initialize(configurer);
}
void WorkbenchAdvisor::Initialize(IWorkbenchConfigurer::Pointer /*configurer*/)
{
// do nothing
}
IWorkbenchConfigurer::Pointer WorkbenchAdvisor::GetWorkbenchConfigurer()
{
return workbenchConfigurer;
}
void WorkbenchAdvisor::PreStartup()
{
// do nothing
}
void WorkbenchAdvisor::PostStartup()
{
// do nothing
}
bool WorkbenchAdvisor::PreShutdown()
{
return true;
}
void WorkbenchAdvisor::PostShutdown()
{
// do nothing
}
IAdaptable* WorkbenchAdvisor::GetDefaultPageInput()
{
// default: no input
return 0;
}
std::string WorkbenchAdvisor::GetMainPreferencePageId()
{
// default: no opinion
return "";
}
bool WorkbenchAdvisor::OpenWindows()
{
// final Display display = PlatformUI.getWorkbench().getDisplay();
// final boolean result [] = new boolean[1];
//
// // spawn another init thread. For API compatibility We guarantee this method is called from
// // the UI thread but it could take enough time to disrupt progress reporting.
// // spawn a new thread to do the grunt work of this initialization and spin the event loop
// // ourselves just like it's done in Workbench.
// final boolean[] initDone = new boolean[]{false};
// final Throwable [] error = new Throwable[1];
// Thread initThread = new Thread() {
// /* (non-Javadoc)
// * @see java.lang.Thread#run()
// */
// void run() {
// try {
// //declare us to be a startup thread so that our syncs will be executed
// UISynchronizer.startupThread.set(Boolean.TRUE);
// final IWorkbenchConfigurer [] myConfigurer = new IWorkbenchConfigurer[1];
// StartupThreading.runWithoutExceptions(new StartupRunnable() {
//
// void runWithException() throws Throwable {
// myConfigurer[0] = getWorkbenchConfigurer();
//
// }});
//
// IStatus status = myConfigurer[0].restoreState();
// if (!status.isOK()) {
// if (status.getCode() == IWorkbenchConfigurer.RESTORE_CODE_EXIT) {
// result[0] = false;
// return;
// }
// if (status.getCode() == IWorkbenchConfigurer.RESTORE_CODE_RESET) {
// myConfigurer[0].openFirstTimeWindow();
// }
// }
// result[0] = true;
// } catch (Throwable e) {
// error[0] = e;
// }
// finally {
// initDone[0] = true;
// display.wake();
// }
// }};
// initThread.start();
//
// while (true) {
// if (!display.readAndDispatch()) {
// if (initDone[0])
// break;
// display.sleep();
// }
//
// }
//
// // can only be a runtime or error
// if (error[0] instanceof Error)
// throw (Error)error[0];
// else if (error[0] instanceof RuntimeException)
// throw (RuntimeException)error[0];
//
// return result[0];
IWorkbenchConfigurer::Pointer myConfigurer = this->GetWorkbenchConfigurer();
bool status = myConfigurer->RestoreState();
if (!status)
{
myConfigurer->OpenFirstTimeWindow();
}
return true;
}
bool WorkbenchAdvisor::SaveState(IMemento::Pointer /*memento*/)
{
return true;
}
bool WorkbenchAdvisor::RestoreState(IMemento::Pointer /*memento*/)
{
return true;
}
}
|
#include <hackerrank_gtest.h>
#include "angry_professor.h"
namespace hackerrank {
namespace bmgandre {
namespace algorithms {
namespace implementation {
using angry_professor_test = hackerrank::bmgandre::tests::hackerrank_gtest;
TEST_F(angry_professor_test, test_case_1) {
input_stream << "2\n4 3\n-1 -3 4 2\n4 2\n0 - 1 2 1\n";
angry_professor::solve();
std::string output = output_stream.str();
ASSERT_EQ(output, "YES\nNO\n");
}
} // namespace implementation
} // namespace algorithms
} // namespace bmgandre
} // namespace hackerrank
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
* Copyright (c) 2011-2021, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dart/common/VersionCounter.hpp"
#include <cassert>
#include <iostream>
#include "dart/common/Console.hpp"
namespace dart {
namespace common {
//==============================================================================
VersionCounter::VersionCounter() : mVersion(0), mDependent(nullptr)
{
// Do nothing
}
//==============================================================================
std::size_t VersionCounter::incrementVersion()
{
++mVersion;
if (mDependent)
mDependent->incrementVersion();
return mVersion;
}
//==============================================================================
std::size_t VersionCounter::getVersion() const
{
return mVersion;
}
//==============================================================================
void VersionCounter::setVersionDependentObject(VersionCounter* dependent)
{
VersionCounter* next = dependent;
do
{
if (next == this)
{
dterr
<< "[VersionCounter::setVersionDependentObject] Attempting to "
<< "create a circular version dependency with the following loop:\n";
next = dependent;
while (next != this)
{
std::cerr << " -- " << next << "\n";
next = next->mDependent;
}
std::cerr << " -- " << this << "\n";
assert(false);
return;
}
next = next->mDependent;
} while (next);
mDependent = dependent;
}
} // namespace common
} // namespace dart
|
//=================================================================================================
/*!
// \file src/mathtest/dvecdvecsub/V5bV5b.cpp
// \brief Source file for the V5bV5b dense vector/dense vector subtraction math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecdvecsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V5bV5b'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
using V5b = blaze::StaticVector<TypeB,5UL>;
// Creator type definitions
using CV5b = blazetest::Creator<V5b>;
// Running the tests
RUN_DVECDVECSUB_OPERATION_TEST( CV5b(), CV5b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/api/api-inl.h"
#include "src/codegen/assembler-inl.h"
#include "src/execution/isolate.h"
#include "src/heap/factory.h"
#include "src/heap/heap-inl.h"
#include "src/ic/handler-configuration.h"
#include "src/objects/data-handler-inl.h"
#include "src/objects/smi.h"
#include "test/cctest/cctest.h"
#include "test/cctest/heap/heap-tester.h"
#include "test/cctest/heap/heap-utils.h"
namespace v8 {
namespace internal {
namespace heap {
Handle<LoadHandler> CreateLoadHandlerForTest(
Factory* factory, AllocationType allocation = AllocationType::kYoung) {
Handle<LoadHandler> result = factory->NewLoadHandler(1, allocation);
result->set_smi_handler(Smi::zero());
result->set_validity_cell(Smi::zero());
result->set_data1(MaybeObject::FromSmi(Smi::zero()));
return result;
}
TEST(WeakReferencesBasic) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh = CreateLoadHandlerForTest(factory);
if (!FLAG_single_generation) CHECK(Heap::InYoungGeneration(*lh));
MaybeObject code_object = lh->data1();
CHECK(code_object->IsSmi());
CcTest::CollectAllGarbage();
CHECK(!Heap::InYoungGeneration(*lh));
CHECK_EQ(code_object, lh->data1());
{
HandleScope inner_scope(isolate);
// Create a new Code.
Assembler assm(AssemblerOptions{});
assm.nop(); // supported on all architectures
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<CodeT> code = ToCodeT(
Factory::CodeBuilder(isolate, desc, CodeKind::FOR_TESTING).Build(),
isolate);
CHECK(code->IsCodeT());
lh->set_data1(HeapObjectReference::Weak(*code));
HeapObject code_heap_object;
CHECK(lh->data1()->GetHeapObjectIfWeak(&code_heap_object));
CHECK_EQ(*code, code_heap_object);
CcTest::CollectAllGarbage();
CHECK(lh->data1()->GetHeapObjectIfWeak(&code_heap_object));
CHECK_EQ(*code, code_heap_object);
} // code will go out of scope.
CcTest::CollectAllGarbage();
CHECK(lh->data1()->IsCleared());
}
TEST(WeakReferencesOldToOld) {
if (FLAG_enable_third_party_heap) return;
// Like WeakReferencesBasic, but the updated weak slot is in the old space,
// and referring to an old space object.
ManualGCScope manual_gc_scope;
FLAG_manual_evacuation_candidates_selection = true;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh =
CreateLoadHandlerForTest(factory, AllocationType::kOld);
CHECK(heap->InOldSpace(*lh));
// Create a new FixedArray which the LoadHandler will point to.
Handle<FixedArray> fixed_array =
factory->NewFixedArray(1, AllocationType::kOld);
CHECK(heap->InOldSpace(*fixed_array));
lh->set_data1(HeapObjectReference::Weak(*fixed_array));
Page* page_before_gc = Page::FromHeapObject(*fixed_array);
heap::ForceEvacuationCandidate(page_before_gc);
CcTest::CollectAllGarbage();
CHECK(heap->InOldSpace(*fixed_array));
HeapObject heap_object;
CHECK(lh->data1()->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(heap_object, *fixed_array);
}
TEST(WeakReferencesOldToNew) {
// Like WeakReferencesBasic, but the updated weak slot is in the old space,
// and referring to an new space object.
if (FLAG_single_generation) return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh =
CreateLoadHandlerForTest(factory, AllocationType::kOld);
CHECK(heap->InOldSpace(*lh));
// Create a new FixedArray which the LoadHandler will point to.
Handle<FixedArray> fixed_array = factory->NewFixedArray(1);
CHECK(Heap::InYoungGeneration(*fixed_array));
lh->set_data1(HeapObjectReference::Weak(*fixed_array));
CcTest::CollectAllGarbage();
HeapObject heap_object;
CHECK(lh->data1()->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(heap_object, *fixed_array);
}
TEST(WeakReferencesOldToNewScavenged) {
if (FLAG_single_generation) return;
// Like WeakReferencesBasic, but the updated weak slot is in the old space,
// and referring to an new space object, which is then scavenged.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh =
CreateLoadHandlerForTest(factory, AllocationType::kOld);
CHECK(heap->InOldSpace(*lh));
// Create a new FixedArray which the LoadHandler will point to.
Handle<FixedArray> fixed_array = factory->NewFixedArray(1);
CHECK(Heap::InYoungGeneration(*fixed_array));
lh->set_data1(HeapObjectReference::Weak(*fixed_array));
CcTest::CollectGarbage(NEW_SPACE);
HeapObject heap_object;
CHECK(lh->data1()->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(heap_object, *fixed_array);
}
TEST(WeakReferencesOldToCleared) {
// Like WeakReferencesBasic, but the updated weak slot is in the old space,
// and is cleared.
ManualGCScope manual_gc_scope;
FLAG_manual_evacuation_candidates_selection = true;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh =
CreateLoadHandlerForTest(factory, AllocationType::kOld);
CHECK(heap->InOldSpace(*lh));
lh->set_data1(HeapObjectReference::ClearedValue(isolate));
CcTest::CollectAllGarbage();
CHECK(lh->data1()->IsCleared());
}
TEST(ObjectMovesBeforeClearingWeakField) {
if (!FLAG_incremental_marking || FLAG_single_generation ||
FLAG_separate_gc_phases) {
return;
}
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh = CreateLoadHandlerForTest(factory);
CHECK(InCorrectGeneration(*lh));
LoadHandler lh_location = *lh;
{
HandleScope inner_scope(isolate);
// Create a new FixedArray which the LoadHandler will point to.
Handle<FixedArray> fixed_array = factory->NewFixedArray(1);
CHECK(Heap::InYoungGeneration(*fixed_array));
lh->set_data1(HeapObjectReference::Weak(*fixed_array));
// inner_scope will go out of scope, so when marking the next time,
// *fixed_array will stay white.
}
// Do marking steps; this will store *lh into the list for later processing
// (since it points to a white object).
SimulateIncrementalMarking(heap, true);
// Scavenger will move *lh.
CcTest::CollectGarbage(NEW_SPACE);
LoadHandler new_lh_location = *lh;
CHECK_NE(lh_location, new_lh_location);
CHECK(lh->data1()->IsWeak());
// Now we try to clear *lh.
CcTest::CollectAllGarbage();
CHECK(lh->data1()->IsCleared());
}
TEST(ObjectWithWeakFieldDies) {
if (!FLAG_incremental_marking) {
return;
}
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
{
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh = CreateLoadHandlerForTest(factory);
CHECK(InCorrectGeneration(*lh));
{
HandleScope inner_scope(isolate);
// Create a new FixedArray which the LoadHandler will point to.
Handle<FixedArray> fixed_array = factory->NewFixedArray(1);
CHECK(InCorrectGeneration(*fixed_array));
lh->set_data1(HeapObjectReference::Weak(*fixed_array));
// inner_scope will go out of scope, so when marking the next time,
// *fixed_array will stay white.
}
// Do marking steps; this will store *lh into the list for later processing
// (since it points to a white object).
SimulateIncrementalMarking(heap, true);
} // outer_scope goes out of scope
// lh will die
CcTest::CollectGarbage(NEW_SPACE);
// This used to crash when processing the dead weak reference.
CcTest::CollectAllGarbage();
}
TEST(ObjectWithWeakReferencePromoted) {
if (FLAG_single_generation) return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh = CreateLoadHandlerForTest(factory);
CHECK(Heap::InYoungGeneration(*lh));
// Create a new FixedArray which the LoadHandler will point to.
Handle<FixedArray> fixed_array = factory->NewFixedArray(1);
CHECK(Heap::InYoungGeneration(*fixed_array));
lh->set_data1(HeapObjectReference::Weak(*fixed_array));
CcTest::CollectGarbage(NEW_SPACE);
CcTest::CollectGarbage(NEW_SPACE);
CHECK(heap->InOldSpace(*lh));
CHECK(heap->InOldSpace(*fixed_array));
HeapObject heap_object;
CHECK(lh->data1()->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(heap_object, *fixed_array);
}
TEST(ObjectWithClearedWeakReferencePromoted) {
if (FLAG_single_generation || FLAG_stress_incremental_marking) return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh = CreateLoadHandlerForTest(factory);
CHECK(Heap::InYoungGeneration(*lh));
lh->set_data1(HeapObjectReference::ClearedValue(isolate));
CcTest::CollectGarbage(NEW_SPACE);
CHECK(Heap::InYoungGeneration(*lh));
CHECK(lh->data1()->IsCleared());
CcTest::CollectGarbage(NEW_SPACE);
CHECK(heap->InOldSpace(*lh));
CHECK(lh->data1()->IsCleared());
CcTest::CollectAllGarbage();
CHECK(lh->data1()->IsCleared());
}
TEST(WeakReferenceWriteBarrier) {
if (!FLAG_incremental_marking) {
return;
}
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<LoadHandler> lh = CreateLoadHandlerForTest(factory);
CHECK(InCorrectGeneration(*lh));
v8::Global<Value> global_lh(CcTest::isolate(), Utils::ToLocal(lh));
{
HandleScope inner_scope(isolate);
// Create a new FixedArray which the LoadHandler will point to.
Handle<FixedArray> fixed_array1 = factory->NewFixedArray(1);
CHECK(InCorrectGeneration(*fixed_array1));
lh->set_data1(HeapObjectReference::Weak(*fixed_array1));
SimulateIncrementalMarking(heap, true);
Handle<FixedArray> fixed_array2 = factory->NewFixedArray(1);
CHECK(InCorrectGeneration(*fixed_array2));
// This write will trigger the write barrier.
lh->set_data1(HeapObjectReference::Weak(*fixed_array2));
}
CcTest::CollectAllGarbage();
// Check that the write barrier treated the weak reference as strong.
CHECK(lh->data1()->IsWeak());
}
TEST(EmptyWeakArray) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope outer_scope(isolate);
Handle<WeakFixedArray> array = factory->empty_weak_fixed_array();
CHECK(array->IsWeakFixedArray());
CHECK(!array->IsFixedArray());
CHECK_EQ(array->length(), 0);
}
TEST(WeakArraysBasic) {
if (FLAG_single_generation) return;
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
const int length = 4;
Handle<WeakFixedArray> array = factory->NewWeakFixedArray(length);
CHECK(array->IsWeakFixedArray());
CHECK(!array->IsFixedArray());
CHECK_EQ(array->length(), length);
CHECK(Heap::InYoungGeneration(*array));
for (int i = 0; i < length; ++i) {
HeapObject heap_object;
CHECK(array->Get(i)->GetHeapObjectIfStrong(&heap_object));
CHECK_EQ(heap_object, ReadOnlyRoots(heap).undefined_value());
}
Handle<HeapObject> saved;
{
HandleScope inner_scope(isolate);
Handle<FixedArray> index0 = factory->NewFixedArray(1);
index0->set(0, Smi::FromInt(2016));
Handle<FixedArray> index1 = factory->NewFixedArray(1);
index1->set(0, Smi::FromInt(2017));
Handle<FixedArray> index2 = factory->NewFixedArray(1);
index2->set(0, Smi::FromInt(2018));
Handle<FixedArray> index3 = factory->NewFixedArray(1);
index3->set(0, Smi::FromInt(2019));
array->Set(0, HeapObjectReference::Weak(*index0));
array->Set(1, HeapObjectReference::Weak(*index1));
array->Set(2, HeapObjectReference::Strong(*index2));
array->Set(3, HeapObjectReference::Weak(*index3));
saved = inner_scope.CloseAndEscape(index1);
} // inner_scope goes out of scope.
// The references are only cleared by the mark-compact (scavenger treats weak
// references as strong). Thus we need to GC until the array reaches old
// space.
// TODO(marja): update this when/if we do handle weak references in the new
// space.
CcTest::CollectGarbage(NEW_SPACE);
HeapObject heap_object;
CHECK(array->Get(0)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2016);
CHECK(array->Get(1)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2017);
CHECK(array->Get(2)->GetHeapObjectIfStrong(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2018);
CHECK(array->Get(3)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2019);
CcTest::CollectAllGarbage();
CHECK(heap->InOldSpace(*array));
CHECK(array->Get(0)->IsCleared());
CHECK(array->Get(1)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2017);
CHECK(array->Get(2)->GetHeapObjectIfStrong(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2018);
CHECK(array->Get(3)->IsCleared());
}
TEST(WeakArrayListBasic) {
if (FLAG_single_generation) return;
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<WeakArrayList> array(ReadOnlyRoots(heap).empty_weak_array_list(),
isolate);
CHECK(array->IsWeakArrayList());
CHECK(!array->IsFixedArray());
CHECK(!array->IsWeakFixedArray());
CHECK_EQ(array->length(), 0);
Handle<FixedArray> index2 = factory->NewFixedArray(1);
index2->set(0, Smi::FromInt(2017));
Handle<HeapObject> saved;
{
HandleScope inner_scope(isolate);
Handle<FixedArray> index0 = factory->NewFixedArray(1);
index0->set(0, Smi::FromInt(2016));
Handle<FixedArray> index4 = factory->NewFixedArray(1);
index4->set(0, Smi::FromInt(2018));
Handle<FixedArray> index6 = factory->NewFixedArray(1);
index6->set(0, Smi::FromInt(2019));
array = WeakArrayList::AddToEnd(isolate, array,
MaybeObjectHandle::Weak(index0));
array = WeakArrayList::AddToEnd(
isolate, array, MaybeObjectHandle(Smi::FromInt(1), isolate));
CHECK_EQ(array->length(), 2);
array = WeakArrayList::AddToEnd(isolate, array,
MaybeObjectHandle::Weak(index2));
array = WeakArrayList::AddToEnd(
isolate, array, MaybeObjectHandle(Smi::FromInt(3), isolate));
CHECK_EQ(array->length(), 4);
array = WeakArrayList::AddToEnd(isolate, array,
MaybeObjectHandle::Weak(index4));
array = WeakArrayList::AddToEnd(
isolate, array, MaybeObjectHandle(Smi::FromInt(5), isolate));
CHECK_EQ(array->length(), 6);
array = WeakArrayList::AddToEnd(isolate, array,
MaybeObjectHandle::Weak(index6));
array = WeakArrayList::AddToEnd(
isolate, array, MaybeObjectHandle(Smi::FromInt(7), isolate));
CHECK_EQ(array->length(), 8);
CHECK(InCorrectGeneration(*array));
CHECK_EQ(array->Get(0), HeapObjectReference::Weak(*index0));
CHECK_EQ(array->Get(1).ToSmi().value(), 1);
CHECK_EQ(array->Get(2), HeapObjectReference::Weak(*index2));
CHECK_EQ(array->Get(3).ToSmi().value(), 3);
CHECK_EQ(array->Get(4), HeapObjectReference::Weak(*index4));
CHECK_EQ(array->Get(5).ToSmi().value(), 5);
CHECK_EQ(array->Get(6), HeapObjectReference::Weak(*index6));
array = inner_scope.CloseAndEscape(array);
} // inner_scope goes out of scope.
// The references are only cleared by the mark-compact (scavenger treats weak
// references as strong). Thus we need to GC until the array reaches old
// space.
// TODO(marja): update this when/if we do handle weak references in the new
// space.
CcTest::CollectGarbage(NEW_SPACE);
HeapObject heap_object;
CHECK_EQ(array->length(), 8);
CHECK(array->Get(0)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2016);
CHECK_EQ(array->Get(1).ToSmi().value(), 1);
CHECK(array->Get(2)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2017);
CHECK_EQ(array->Get(3).ToSmi().value(), 3);
CHECK(array->Get(4)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2018);
CHECK_EQ(array->Get(5).ToSmi().value(), 5);
CHECK(array->Get(6)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2019);
CHECK_EQ(array->Get(7).ToSmi().value(), 7);
CcTest::CollectAllGarbage();
CHECK(heap->InOldSpace(*array));
CHECK_EQ(array->length(), 8);
CHECK(array->Get(0)->IsCleared());
CHECK_EQ(array->Get(1).ToSmi().value(), 1);
CHECK(array->Get(2)->GetHeapObjectIfWeak(&heap_object));
CHECK_EQ(Smi::cast(FixedArray::cast(heap_object).get(0)).value(), 2017);
CHECK_EQ(array->Get(3).ToSmi().value(), 3);
CHECK(array->Get(4)->IsCleared());
CHECK_EQ(array->Get(5).ToSmi().value(), 5);
CHECK(array->Get(6)->IsCleared());
CHECK_EQ(array->Get(7).ToSmi().value(), 7);
}
TEST(WeakArrayListRemove) {
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<WeakArrayList> array(ReadOnlyRoots(heap).empty_weak_array_list(),
isolate);
Handle<FixedArray> elem0 = factory->NewFixedArray(1);
Handle<FixedArray> elem1 = factory->NewFixedArray(1);
Handle<FixedArray> elem2 = factory->NewFixedArray(1);
array =
WeakArrayList::AddToEnd(isolate, array, MaybeObjectHandle::Weak(elem0));
array =
WeakArrayList::AddToEnd(isolate, array, MaybeObjectHandle::Weak(elem1));
array =
WeakArrayList::AddToEnd(isolate, array, MaybeObjectHandle::Weak(elem2));
CHECK_EQ(array->length(), 3);
CHECK_EQ(array->Get(0), HeapObjectReference::Weak(*elem0));
CHECK_EQ(array->Get(1), HeapObjectReference::Weak(*elem1));
CHECK_EQ(array->Get(2), HeapObjectReference::Weak(*elem2));
CHECK(array->RemoveOne(MaybeObjectHandle::Weak(elem1)));
CHECK_EQ(array->length(), 2);
CHECK_EQ(array->Get(0), HeapObjectReference::Weak(*elem0));
CHECK_EQ(array->Get(1), HeapObjectReference::Weak(*elem2));
CHECK(!array->RemoveOne(MaybeObjectHandle::Weak(elem1)));
CHECK_EQ(array->length(), 2);
CHECK_EQ(array->Get(0), HeapObjectReference::Weak(*elem0));
CHECK_EQ(array->Get(1), HeapObjectReference::Weak(*elem2));
CHECK(array->RemoveOne(MaybeObjectHandle::Weak(elem0)));
CHECK_EQ(array->length(), 1);
CHECK_EQ(array->Get(0), HeapObjectReference::Weak(*elem2));
CHECK(array->RemoveOne(MaybeObjectHandle::Weak(elem2)));
CHECK_EQ(array->length(), 0);
}
TEST(Regress7768) {
i::FLAG_allow_natives_syntax = true;
i::FLAG_turbo_inlining = false;
if (!FLAG_incremental_marking) {
return;
}
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
LocalContext context;
Isolate* isolate = CcTest::i_isolate();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
// Create an optimized code which will contain a weak reference to another
// function ("f"). The weak reference is the only reference to the function.
CompileRun(
"function myfunc(f) { f(); } "
"%PrepareFunctionForOptimization(myfunc); "
"(function wrapper() { "
" function f() {}; myfunc(f); myfunc(f); "
" %OptimizeFunctionOnNextCall(myfunc); myfunc(f); "
" %ClearFunctionFeedback(wrapper);"
"})(); "
"%ClearFunctionFeedback(myfunc);");
// Do marking steps; this will store the objects pointed by myfunc for later
// processing.
SimulateIncrementalMarking(heap, true);
// Deoptimize the code; now the pointers inside it will be replaced with
// undefined, and the weak_objects_in_code is the only place pointing to the
// function f.
CompileRun("%DeoptimizeFunction(myfunc);");
// The object pointed to by the weak reference won't be scavenged.
CcTest::CollectGarbage(NEW_SPACE);
// Make sure the memory where it's stored is invalidated, so that we'll crash
// if we try to access it.
HeapTester::UncommitUnusedMemory(heap);
// This used to crash when processing the dead weak reference.
CcTest::CollectAllGarbage();
}
TEST(PrototypeUsersBasic) {
CcTest::InitializeVM();
LocalContext context;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<WeakArrayList> array(ReadOnlyRoots(heap).empty_weak_array_list(),
isolate);
// Add some objects into the array.
int index = -1;
{
Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map, &index);
CHECK_EQ(array->length(), index + 1);
}
CHECK_EQ(index, 1);
int empty_index = index;
PrototypeUsers::MarkSlotEmpty(*array, empty_index);
// Even though we have an empty slot, we still add to the end.
int last_index = index;
int old_capacity = array->capacity();
while (!array->IsFull()) {
Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map, &index);
CHECK_EQ(index, last_index + 1);
CHECK_EQ(array->length(), index + 1);
last_index = index;
}
// The next addition will fill the empty slot.
{
Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map, &index);
}
CHECK_EQ(index, empty_index);
// The next addition will make the arrow grow again.
{
Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map, &index);
CHECK_EQ(array->length(), index + 1);
last_index = index;
}
CHECK_GT(array->capacity(), old_capacity);
// Make multiple slots empty.
int empty_index1 = 1;
int empty_index2 = 2;
PrototypeUsers::MarkSlotEmpty(*array, empty_index1);
PrototypeUsers::MarkSlotEmpty(*array, empty_index2);
// Fill the array (still adding to the end)
old_capacity = array->capacity();
while (!array->IsFull()) {
Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map, &index);
CHECK_EQ(index, last_index + 1);
CHECK_EQ(array->length(), index + 1);
last_index = index;
}
// Make sure we use the empty slots in (reverse) order.
{
Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map, &index);
}
CHECK_EQ(index, empty_index2);
{
Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map, &index);
}
CHECK_EQ(index, empty_index1);
}
namespace {
HeapObject saved_heap_object;
static void TestCompactCallback(HeapObject value, int old_index,
int new_index) {
saved_heap_object = value;
CHECK_EQ(old_index, 2);
CHECK_EQ(new_index, 1);
}
} // namespace
TEST(PrototypeUsersCompacted) {
ManualGCScope manual_gc_scope;
CcTest::InitializeVM();
LocalContext context;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Heap* heap = isolate->heap();
HandleScope outer_scope(isolate);
Handle<WeakArrayList> array(ReadOnlyRoots(heap).empty_weak_array_list(),
isolate);
// Add some objects into the array.
int index = -1;
Handle<Map> map_cleared_by_user =
factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, map_cleared_by_user, &index);
CHECK_EQ(index, 1);
Handle<Map> live_map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, live_map, &index);
CHECK_EQ(index, 2);
{
HandleScope inner_scope(isolate);
Handle<Map> soon_dead_map =
factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
array = PrototypeUsers::Add(isolate, array, soon_dead_map, &index);
CHECK_EQ(index, 3);
array = inner_scope.CloseAndEscape(array);
}
PrototypeUsers::MarkSlotEmpty(*array, 1);
CcTest::CollectAllGarbage();
CHECK(array->Get(3)->IsCleared());
CHECK_EQ(array->length(), 3 + PrototypeUsers::kFirstIndex);
WeakArrayList new_array =
PrototypeUsers::Compact(array, heap, TestCompactCallback);
CHECK_EQ(new_array.length(), 1 + PrototypeUsers::kFirstIndex);
CHECK_EQ(saved_heap_object, *live_map);
}
} // namespace heap
} // namespace internal
} // namespace v8
|
/*
ะงัะพ ะฑัะดะตั ะฒ ัะฐะบะพะผ ัะปััะฐะต?)
ะกะบะพะปัะบะพ ัะฐะท ะฑัะดะตั ะฒัะทะฒะฐะฝ ะดะตััััะบัะพั.
ะะพะณะดะฐ ััะพ ะฟัะธะฒะตะดะตั ะบ ะพัะธะฑะบะต, ะฐ ะบะพะณะดะฐ ะฝะตั?
*/
struct A{
A(){}
~A(){}
};
int main()
{
A a;
a.~A();
return 0;
}
|
// ไธญ็ญ ๆ่ทฏๆฏๆ็๏ผไธ็ดๅไธ็ด้๏ผๅไบ60ๅ้
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
if (n < 1) return res;
int num = (n + 1) / 2;
int cur = 0;
for (int i = 0; i < num; i++) {
int len = n - i * 2;
int c = max(1, len * 4 - 4);
for (int j = 0; j < c; j++) {
cur++;
int row = 0, col = 0;
if (j < len) {
row = i;
col = j+i;
}
else if (j >= len && j < len * 2 - 2) {
row = j - len + 1 + i;
col = n - i - 1;
}
else if (j >= len * 2 - 2 && j < len * 3 - 2) {
row = n - i - 1;
col = n - (j - len * 2 + 2) - 1 - i;
}
else {
row = n - (j - len * 3 + 3) - 1 - i;
col = i;
}
res[row][col] = cur;
}
}
return res;
}
};
// ๆๆดไผ้
็ๆนๆณ๏ผๅฎไน4ไธชๅ้๏ผl/r/t/b่กจ็คบ4ไธช่พน็
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
if (n < 1) return res;
int l = 0, r = n - 1, t = 0, b = n - 1;
int cur = 0, tar = n*n;
while (cur<tar)
{
for (int i = l; i <= r; i++) res[t][i] = ++cur;
t++;
for (int i = t; i <= b; i++) res[i][r] = ++cur;
r--;
for (int i = r; i >= l; i--) res[b][i] = ++cur;
b--;
for (int i = b; i >= t; i--) res[i][l] = ++cur;
l++;
}
return res;
}
};
// ๅทงๅฆ็ๆนๆณ๏ผไฝ้พๆณ
/*
ๅ่ๅคง็ๅ็, ๅคๆญไฝๆถ่ฝฌๅ็ๆๆณๅพๅทงๅฆ
1, ๆไธคไธชๆนๅ, ๆไปฅไฝฟ็จไบ็ปดๅ
็ปๅญๅจๆนๅ็ถๆ
ไธๅณ : (0, 1), ๅณไธ(1, 0), ไธๅทฆ(0, -1), ๅทฆไธ(-1, 0)
2, ๅคๆญๅฆไฝ่ฝฌๅ
่ฏปๅๆฐๆฎๆถ, ๆฏ่ก, ๅ็ๆๅไธไธชๅ
็ด ๆฏๅฐ่ฆ่ฏปๅ็ๅ, ่ก็่ตท็น.
่ตท็นๅทฒ็ป่ขซ่ฏปๅ, ๅฐฑๆณๅฐๅๆจกๆไฝๅฏไปฅๅพๅฐๅฝๅๅ, ่ก็ไธไธๆญฅ็ถๆ.
*/
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
if (n < 1) return res;
int x = 0, y = 0, dx = 0, dy = 1;
for (int i = 1; i <= n*n; i++) {
res[x][y] = i;
if (res[(x + dx) % n][(y + dy) % n]>0) {
int tmp = dx;
dx = dy;
dy = -tmp;
}
x += dx;
y += dy;
}
return res;
}
};
|
#include "simple_cpp/some_lib/some_lib.hpp"
#include <cassert>
#include <iostream>
int main()
{
fly::SomeClass sc(15);
assert(sc() == 15);
std::cout << "Passed!\n";
return 0;
}
|
/*
* Copyright (C) 2020-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/helpers/aligned_memory.h"
#include "shared/test/common/mocks/mock_gmm_resource_info.h"
namespace NEO {
GmmResourceInfo *GmmResourceInfo::create(GmmClientContext *clientContext, GMM_RESCREATE_PARAMS *resourceCreateParams) {
if (resourceCreateParams->Type == GMM_RESOURCE_TYPE::RESOURCE_INVALID) {
return nullptr;
}
return new MockGmmResourceInfo(resourceCreateParams);
}
GmmResourceInfo *GmmResourceInfo::create(GmmClientContext *clientContext, GMM_RESOURCE_INFO *inputGmmResourceInfo) {
return new MockGmmResourceInfo(inputGmmResourceInfo);
}
MockGmmResourceInfo::MockGmmResourceInfo(GMM_RESCREATE_PARAMS *resourceCreateParams) {
mockResourceCreateParams = *resourceCreateParams;
setupDefaultActions();
}
MockGmmResourceInfo::MockGmmResourceInfo(GMM_RESOURCE_INFO *inputGmmResourceInfo) {
mockResourceCreateParams = reinterpret_cast<MockGmmResourceInfo *>(inputGmmResourceInfo)->mockResourceCreateParams;
setupDefaultActions();
};
// Simulate GMM behaviour. We dont want to test 3rd party lib
void MockGmmResourceInfo::setupDefaultActions() {
setSurfaceFormat();
if (surfaceFormatInfo == nullptr) {
return;
}
computeRowPitch();
size = rowPitch;
size *= static_cast<size_t>(mockResourceCreateParams.BaseHeight);
qPitch = alignUp((uint32_t)size, 64);
size *= mockResourceCreateParams.Depth ? static_cast<size_t>(mockResourceCreateParams.Depth) : 1;
size *= mockResourceCreateParams.ArraySize ? static_cast<size_t>(mockResourceCreateParams.ArraySize) : 1;
size = alignUp(size, MemoryConstants::pageSize);
}
GMM_STATUS MockGmmResourceInfo::getOffset(GMM_REQ_OFFSET_INFO &reqOffsetInfo) {
arrayIndexPassedToGetOffset = reqOffsetInfo.ArrayIndex;
getOffsetCalled++;
reqOffsetInfo.Lock.Offset = 16;
reqOffsetInfo.Lock.Pitch = 2;
reqOffsetInfo.Render.YOffset = 1;
if (mockResourceCreateParams.Format == GMM_RESOURCE_FORMAT::GMM_FORMAT_NV12) {
reqOffsetInfo.Render.XOffset = 32;
reqOffsetInfo.Render.Offset = 64;
}
if (reqOffsetInfo.Slice == 1) {
reqOffsetInfo.Render.YOffset = mockResourceCreateParams.BaseHeight;
}
if (reqOffsetInfo.MipLevel > 0) {
reqOffsetInfo.Lock.Offset = 32;
}
return GMM_SUCCESS;
}
void MockGmmResourceInfo::computeRowPitch() {
if (mockResourceCreateParams.OverridePitch) {
rowPitch = mockResourceCreateParams.OverridePitch;
} else {
rowPitch = static_cast<size_t>(mockResourceCreateParams.BaseWidth64 * (surfaceFormatInfo->ImageElementSizeInBytes));
rowPitch = alignUp(rowPitch, 64);
}
}
uint32_t MockGmmResourceInfo::getBitsPerPixel() {
return static_cast<uint32_t>(surfaceFormatInfo->ImageElementSizeInBytes * 8);
}
void MockGmmResourceInfo::setUnifiedAuxTranslationCapable() {
mockResourceCreateParams.Flags.Gpu.CCS = 1;
mockResourceCreateParams.Flags.Gpu.UnifiedAuxSurface = 1;
mockResourceCreateParams.Flags.Info.RenderCompressed = 1;
}
void MockGmmResourceInfo::setMultisampleControlSurface() {
mockResourceCreateParams.Flags.Gpu.MCS = 1;
}
void MockGmmResourceInfo::setUnifiedAuxPitchTiles(uint32_t value) {
this->unifiedAuxPitch = value;
}
void MockGmmResourceInfo::setAuxQPitch(uint32_t value) {
this->auxQPitch = value;
}
uint32_t MockGmmResourceInfo::getTileModeSurfaceState() {
if (mockResourceCreateParams.Flags.Info.Linear == 1) {
return 0;
}
if (mockResourceCreateParams.Type == GMM_RESOURCE_TYPE::RESOURCE_2D ||
mockResourceCreateParams.Type == GMM_RESOURCE_TYPE::RESOURCE_3D) {
return yMajorTileModeValue;
} else {
return 0;
}
}
MockGmmResourceInfo::MockGmmResourceInfo() {}
MockGmmResourceInfo::~MockGmmResourceInfo() {}
} // namespace NEO
|
/*
O Despertar da Forรงa
https://www.urionlinejudge.com.br/judge/pt/problems/view/2163
*/
#include <iostream>
#include <utility>
using namespace std;
typedef pair<int, int> ii;
ii procurar(const int **terreno, int N, int M);
bool procurar_arredores(const int **terreno, int i, int j);
int main(void) {
ios::sync_with_stdio(false);
int N, M;
cin >> N >> M;
int **terreno = new int*[N];
for (int i = 0; i < N; i++) terreno[i] = new int[M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> terreno[i][j];
}
}
ii local = procurar((const int**)terreno, N, M);
cout << local.first << ' ' << local.second << endl;
return 0;
}
ii procurar(const int **terreno, int N, int M) {
for (int i = 1; i < N - 1; i++) {
for (int j = 1; j < M - 1; j++) {
if (terreno[i][j] == 42 && procurar_arredores(terreno, i, j)) return make_pair(i + 1, j + 1);
}
}
return make_pair(0, 0);
}
bool procurar_arredores(const int **terreno, int i, int j) {
for (int m = i - 1; m < i + 2; m++) {
for (int n = j - 1; n < j + 2; n++) {
if (m == i && n == j) continue;
if (terreno[m][n] != 7) return false;
}
}
return true;
}
|
#include "stdafx.h"
#include "UIOption.h"
namespace DuiLib
{
COptionUI::COptionUI() : m_bSelected(false), m_dwSelectedTextColor(0)
{
}
COptionUI::~COptionUI()
{
if( !m_sGroupName.IsEmpty() && m_pManager ) m_pManager->RemoveOptionGroup(m_sGroupName, this);
}
LPCTSTR COptionUI::GetClass() const
{
return _T("OptionUI");
}
LPVOID COptionUI::GetInterface(LPCTSTR pstrName)
{
if( _tcscmp(pstrName, DUI_CTR_OPTION) == 0 ) return static_cast<COptionUI*>(this);
return CButtonUI::GetInterface(pstrName);
}
void COptionUI::SetManager(CPaintManagerUI* pManager, CControlUI* pParent, bool bInit)
{
CControlUI::SetManager(pManager, pParent, bInit);
if( bInit && !m_sGroupName.IsEmpty() ) {
if (m_pManager) m_pManager->AddOptionGroup(m_sGroupName, this);
}
}
LPCTSTR COptionUI::GetGroup() const
{
return m_sGroupName;
}
void COptionUI::SetGroup(LPCTSTR pStrGroupName)
{
if( pStrGroupName == NULL ) {
if( m_sGroupName.IsEmpty() ) return;
m_sGroupName.Empty();
}
else {
if( m_sGroupName == pStrGroupName ) return;
if (!m_sGroupName.IsEmpty() && m_pManager) m_pManager->RemoveOptionGroup(m_sGroupName, this);
m_sGroupName = pStrGroupName;
}
if( !m_sGroupName.IsEmpty() ) {
if (m_pManager) m_pManager->AddOptionGroup(m_sGroupName, this);
}
else {
if (m_pManager) m_pManager->RemoveOptionGroup(m_sGroupName, this);
}
Selected(m_bSelected);
}
bool COptionUI::IsSelected() const
{
return m_bSelected;
}
void COptionUI::Selected(bool bSelected)
{
if( m_bSelected == bSelected ) return;
m_bSelected = bSelected;
if( m_bSelected ) m_uButtonState |= UISTATE_SELECTED;
else m_uButtonState &= ~UISTATE_SELECTED;
if( m_pManager != NULL ) {
if( !m_sGroupName.IsEmpty() ) {
if( m_bSelected ) {
CStdPtrArray* aOptionGroup = m_pManager->GetOptionGroup(m_sGroupName);
for( int i = 0; i < aOptionGroup->GetSize(); i++ ) {
COptionUI* pControl = static_cast<COptionUI*>(aOptionGroup->GetAt(i));
if( pControl != this ) {
pControl->Selected(false);
}
}
m_pManager->SendNotify(this, DUI_MSGTYPE_SELECTCHANGED);
}
}
else {
m_pManager->SendNotify(this, DUI_MSGTYPE_SELECTCHANGED);
}
}
Invalidate();
}
bool COptionUI::Activate()
{
if( !CButtonUI::Activate() ) return false;
if( !m_sGroupName.IsEmpty() ) Selected(true);
else Selected(!m_bSelected);
return true;
}
void COptionUI::SetEnabled(bool bEnable)
{
CControlUI::SetEnabled(bEnable);
if( !IsEnabled() ) {
if( m_bSelected ) m_uButtonState = UISTATE_SELECTED;
else m_uButtonState = 0;
}
}
LPCTSTR COptionUI::GetSelectedImage()
{
return m_sSelectedImage;
}
void COptionUI::SetSelectedImage(LPCTSTR pStrImage)
{
m_sSelectedImage = pStrImage;
Invalidate();
}
//************************************
// Method: GetSelectedHotImage
// FullName: COptionUI::GetSelectedHotImage
// Access: public
// Returns: LPCTSTR
// Qualifier:
// Node:
//************************************
LPCTSTR COptionUI::GetSelectedHotImage()
{
return m_sSelectedHotImage;
}
//************************************
// Method: SetSelectedHotImage
// FullName: COptionUI::SetSelectedHotImage
// Access: public
// Returns: void
// Qualifier:
// Parameter: LPCTSTR pStrImage
// Node:
//************************************
void COptionUI::SetSelectedHotImage( LPCTSTR pStrImage )
{
m_sSelectedHotImage = pStrImage;
Invalidate();
}
void COptionUI::SetSelectedTextColor(DWORD dwTextColor)
{
m_dwSelectedTextColor = dwTextColor;
}
DWORD COptionUI::GetSelectedTextColor()
{
if (m_dwSelectedTextColor == 0) m_dwSelectedTextColor = m_pManager->GetDefaultFontColor();
return m_dwSelectedTextColor;
}
//************************************
// Method: SetSelectedBkColor
// FullName: COptionUI::SetSelectedBkColor
// Access: public
// Returns: void
// Qualifier:
// Parameter: DWORD dwBkColor
// Note:
//************************************
void COptionUI::SetSelectedBkColor( DWORD dwBkColor )
{
m_dwSelectedBkColor = dwBkColor;
}
//************************************
// Method: GetSelectBkColor
// FullName: COptionUI::GetSelectBkColor
// Access: public
// Returns: DWORD
// Qualifier:
// Note:
//************************************
DWORD COptionUI::GetSelectBkColor()
{
return m_dwSelectedBkColor;
}
LPCTSTR COptionUI::GetForeImage()
{
return m_sForeImage;
}
void COptionUI::SetForeImage(LPCTSTR pStrImage)
{
m_sForeImage = pStrImage;
Invalidate();
}
SIZE COptionUI::EstimateSize(SIZE szAvailable)
{
if( m_cxyFixed.cy == 0 ) return CDuiSize(m_cxyFixed.cx, m_pManager->GetFontInfo(GetFont())->tm.tmHeight + 8);
return CControlUI::EstimateSize(szAvailable);
}
void COptionUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
if( _tcscmp(pstrName, _T("group")) == 0 ) SetGroup(pstrValue);
else if( _tcscmp(pstrName, _T("selected")) == 0 ) Selected(_tcscmp(pstrValue, _T("true")) == 0);
else if( _tcscmp(pstrName, _T("selectedimage")) == 0 ) SetSelectedImage(pstrValue);
else if( _tcscmp(pstrName, _T("selectedhotimage")) == 0 ) SetSelectedHotImage(pstrValue);
else if( _tcscmp(pstrName, _T("foreimage")) == 0 ) SetForeImage(pstrValue);
else if( _tcscmp(pstrName, _T("selectedbkcolor")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetSelectedBkColor(clrColor);
}
else if( _tcscmp(pstrName, _T("selectedtextcolor")) == 0 ) {
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetSelectedTextColor(clrColor);
}
else CButtonUI::SetAttribute(pstrName, pstrValue);
}
void COptionUI::PaintStatusImage(HDC hDC)
{
m_uButtonState &= ~UISTATE_PUSHED;
if( (m_uButtonState & UISTATE_HOT) != 0 && IsSelected() && !m_sSelectedHotImage.IsEmpty()) {
if( !DrawImage(hDC, (LPCTSTR)m_sSelectedHotImage) )
m_sSelectedHotImage.Empty();
else goto Label_ForeImage;
}
else if( (m_uButtonState & UISTATE_SELECTED) != 0 ) {
if( !m_sSelectedImage.IsEmpty() ) {
if( !DrawImage(hDC, (LPCTSTR)m_sSelectedImage) ) m_sSelectedImage.Empty();
else goto Label_ForeImage;
}
else if(m_dwSelectedBkColor != 0) {
CRenderEngine::DrawColor(hDC, m_rcPaint, GetAdjustColor(m_dwSelectedBkColor));
return;
}
}
CButtonUI::PaintStatusImage(hDC);
Label_ForeImage:
if( !m_sForeImage.IsEmpty() ) {
if( !DrawImage(hDC, (LPCTSTR)m_sForeImage) ) m_sForeImage.Empty();
}
}
void COptionUI::PaintText(HDC hDC)
{
if( (m_uButtonState & UISTATE_SELECTED) != 0 )
{
DWORD oldTextColor = m_dwTextColor;
if( m_dwSelectedTextColor != 0 ) m_dwTextColor = m_dwSelectedTextColor;
if( m_dwTextColor == 0 ) m_dwTextColor = m_pManager->GetDefaultFontColor();
if( m_dwDisabledTextColor == 0 ) m_dwDisabledTextColor = m_pManager->GetDefaultDisabledColor();
if( m_sText.IsEmpty() ) return;
int nLinks = 0;
RECT rc = m_rcItem;
rc.left += m_rcTextPadding.left;
rc.right -= m_rcTextPadding.right;
rc.top += m_rcTextPadding.top;
rc.bottom -= m_rcTextPadding.bottom;
if( m_bShowHtml )
CRenderEngine::DrawHtmlText(hDC, m_pManager, rc, m_sText, IsEnabled()?m_dwTextColor:m_dwDisabledTextColor, \
NULL, NULL, nLinks, m_uTextStyle);
else
CRenderEngine::DrawText(hDC, m_pManager, rc, m_sText, IsEnabled()?m_dwTextColor:m_dwDisabledTextColor, \
m_iFont, m_uTextStyle);
m_dwTextColor = oldTextColor;
}
else
CButtonUI::PaintText(hDC);
}
}
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/profiler/convert/xplane_to_step_events.h"
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/protobuf/xplane.pb.h"
#include "tensorflow/core/profiler/utils/event_span.h"
#include "tensorflow/core/profiler/utils/group_events.h"
#include "tensorflow/core/profiler/utils/xplane_builder.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"
#include "tensorflow/core/profiler/utils/xplane_test_utils.h"
namespace tensorflow {
namespace profiler {
namespace {
// Tests with a sample profile with two steps captured on the host but only one
// step on the device. On the host, each step consists of TraceContext ->
// FunctionRun -> ExecutorState::Process -> matmul. On the host, each step
// consists of matmul. The host's step db should be created only for the step
// observed on the host.
TEST(ConvertXPlaneToOpStats, CpuOnlyStepDbTest) {
constexpr int64 kFirstStepNum = 123;
constexpr int64 kSecondStepNum = 456;
constexpr int64 kFirstStepId = 0;
constexpr int64 kSecondStepId = 1;
constexpr int64 kFirstCorrelationId = 100;
constexpr int64 kSecondCorrelationId = 200;
XSpace space;
XPlane* host_plane = space.add_planes();
XPlaneBuilder host_plane_builder(host_plane);
host_plane_builder.SetName(kHostThreads);
host_plane_builder.ReserveLines(2);
auto main_thread = host_plane_builder.GetOrCreateLine(0);
CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kTraceContext,
0, 100, {{StatType::kStepNum, kFirstStepNum}});
CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun,
10, 90, {{StatType::kStepId, kFirstStepId}});
CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kTraceContext,
300, 100, {{StatType::kStepNum, kSecondStepNum}});
CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun,
310, 90, {{StatType::kStepId, kSecondStepId}});
auto tf_executor_thread = host_plane_builder.GetOrCreateLine(1);
CreateXEvent(&host_plane_builder, &tf_executor_thread,
HostEventType::kExecutorStateProcess, 20, 20,
{{StatType::kStepId, kFirstStepId}});
CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 10,
{{StatType::kCorrelationId, kFirstCorrelationId}});
CreateXEvent(&host_plane_builder, &tf_executor_thread,
HostEventType::kExecutorStateProcess, 320, 20,
{{StatType::kStepId, kSecondStepId}});
CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 330, 10,
{{StatType::kCorrelationId, kSecondCorrelationId}});
XPlane* device_plane = space.add_planes();
XPlaneBuilder device_plane_builder(device_plane);
device_plane_builder.ReserveLines(1);
auto stream = device_plane_builder.GetOrCreateLine(0);
CreateXEvent(&device_plane_builder, &stream, "matmul", 50, 40,
{{StatType::kCorrelationId, kFirstCorrelationId}});
GroupTfEvents(&space, nullptr);
StepEvents device_step_events =
ConvertDeviceTraceXPlaneToStepEvents(*device_plane);
EXPECT_EQ(device_step_events.size(), 1);
EXPECT_EQ(device_step_events[0].Events().size(), 1);
StepEvents host_step_events = ConvertHostThreadsXPlaneToStepEvents(
*host_plane, true, device_step_events);
// Should contain only the step which is also present on the device.
EXPECT_EQ(host_step_events.size(), 1);
// TraceContext should be added as a step marker.
EXPECT_EQ(host_step_events[0].Markers().size(), 1);
// FunctionRun shouldn't be added.
EXPECT_EQ(host_step_events[0].Events().size(), 2);
}
} // namespace
} // namespace profiler
} // namespace tensorflow
|
#include "drpch.h"
#include "Renderer.h"
namespace Dray
{
void Renderer::BeginScene()
{
}
void Renderer::EndScene()
{
}
void Renderer::Submit(const std::shared_ptr<VertexArray>& vao)
{
RenderCommand::DrawIndexed(vao);
}
}
|
#include <iostream>
using namespace std;
int maior_numero_com_digitos_de(string num){
char aux;
while(true){
bool troca = false;
for(int i=0; i < num.length()-1; i++){
if(num[i] < num[i+1]){
aux = num[i];
num[i] = num[i+1];
num[i+1] = aux;
troca = true;
}
}
if(!troca)
break;
}
return stoi(num);
}
int menor_numero_com_digitos_de(string num){
char aux;
while(true){
bool troca = false;
for(int i=0; i < num.length()-1; i++){
if(num[i] > num[i+1]){
aux = num[i];
num[i] = num[i+1];
num[i+1] = aux;
troca = true;
}
}
if(!troca)
break;
}
return stoi(num);
}
string retifica(int X){
string num = to_string(X);
int length = num.length();
if(length < 4){
for(int i=0; i <= 4-length; i++){
num.insert(0,"0");
}
}
return num;
}
bool condicao(int X){
string num = retifica(X);
for(int i=0; i<num.length()-1; i++){
for(int j=0; j<num.length()-1; j++){
if(num[i] != num[j])
return true;
}
}
return false;
}
int krapekar(int X) {
if(condicao(X) == false)
return -1;
int cnt = 0;
string num;
while (X != 6174) {
num = retifica(X);
int maior = maior_numero_com_digitos_de(num);
int menor = menor_numero_com_digitos_de(num);
X = maior - menor;
cout << X << endl;
cnt = cnt + 1;
}
return cnt;
}
int main(){
int T, X;
cin >> T;
for(int i=1; i<=T; i++){
cin >> X;
cout << "Caso #" << i << ": " << krapekar(X) << endl;
}
}
|
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 %s
void foo() {
}
bool foobool(int argc) {
return argc;
}
struct S1; // expected-note {{declared here}}
template <class T, class S> // expected-note {{declared here}}
int tmain(T argc, S **argv) {
int i;
#pragma omp target simd if // expected-error {{expected '(' after 'if'}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if () // expected-error {{expected expression}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc)) // expected-warning {{extra tokens at the end of '#pragma omp target simd' are ignored}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc > 0 ? argv[1] : argv[2])
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (foobool(argc)), if (true) // expected-error {{directive '#pragma omp target simd' cannot contain more than one 'if' clause}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (S) // expected-error {{'S' does not refer to a value}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc argc) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(argc)
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc)
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc) if (simd:argc) // expected-error {{directive name modifier 'simd' is not allowed for '#pragma omp target simd'}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc) if (target :argc) // expected-error {{directive '#pragma omp target simd' cannot contain more than one 'if' clause with 'target' name modifier}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc) if (argc) // expected-note {{previous clause with directive name modifier specified here}} expected-error {{no more 'if' clause is allowed}}
for (i = 0; i < argc; ++i) foo();
return 0;
}
int main(int argc, char **argv) {
int i;
#pragma omp target simd if // expected-error {{expected '(' after 'if'}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if () // expected-error {{expected expression}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc)) // expected-warning {{extra tokens at the end of '#pragma omp target simd' are ignored}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc > 0 ? argv[1] : argv[2])
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (foobool(argc)), if (true) // expected-error {{directive '#pragma omp target simd' cannot contain more than one 'if' clause}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (S1) // expected-error {{'S1' does not refer to a value}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (argc argc) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if (1 0) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(if(tmain(argc, argv) // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc) if (simd:argc) // expected-error {{directive name modifier 'simd' is not allowed for '#pragma omp target simd'}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc) if (target :argc) // expected-error {{directive '#pragma omp target simd' cannot contain more than one 'if' clause with 'target' name modifier}}
for (i = 0; i < argc; ++i) foo();
#pragma omp target simd if(target : argc) if (argc) // expected-note {{previous clause with directive name modifier specified here}} expected-error {{no more 'if' clause is allowed}}
for (i = 0; i < argc; ++i) foo();
return tmain(argc, argv);
}
|
//===- unittest/Tooling/CleanupTest.cpp - Include insertion/deletion tests ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Inclusions/HeaderIncludes.h"
#include "../Tooling/ReplacementTest.h"
#include "../Tooling/RewriterTestContext.h"
#include "clang/Format/Format.h"
#include "clang/Tooling/Core/Replacement.h"
#include "gtest/gtest.h"
using clang::tooling::ReplacementTest;
using clang::tooling::toReplacements;
namespace clang {
namespace tooling {
namespace {
class HeaderIncludesTest : public ::testing::Test {
protected:
std::string insert(llvm::StringRef Code, llvm::StringRef Header) {
HeaderIncludes Includes(FileName, Code, Style);
assert(Header.startswith("\"") || Header.startswith("<"));
auto R = Includes.insert(Header.trim("\"<>"), Header.startswith("<"));
if (!R)
return Code;
auto Result = applyAllReplacements(Code, Replacements(*R));
EXPECT_TRUE(static_cast<bool>(Result));
return *Result;
}
std::string remove(llvm::StringRef Code, llvm::StringRef Header) {
HeaderIncludes Includes(FileName, Code, Style);
assert(Header.startswith("\"") || Header.startswith("<"));
auto Replaces = Includes.remove(Header.trim("\"<>"), Header.startswith("<"));
auto Result = applyAllReplacements(Code, Replaces);
EXPECT_TRUE(static_cast<bool>(Result));
return *Result;
}
const std::string FileName = "fix.cpp";
IncludeStyle Style = format::getLLVMStyle().IncludeStyle;
};
TEST_F(HeaderIncludesTest, NoExistingIncludeWithoutDefine) {
std::string Code = "int main() {}";
std::string Expected = "#include \"a.h\"\n"
"int main() {}";
EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
}
TEST_F(HeaderIncludesTest, NoExistingIncludeWithDefine) {
std::string Code = "#ifndef A_H\n"
"#define A_H\n"
"class A {};\n"
"#define MMM 123\n"
"#endif";
std::string Expected = "#ifndef A_H\n"
"#define A_H\n"
"#include \"b.h\"\n"
"class A {};\n"
"#define MMM 123\n"
"#endif";
EXPECT_EQ(Expected, insert(Code, "\"b.h\""));
}
TEST_F(HeaderIncludesTest, InsertBeforeCategoryWithLowerPriority) {
std::string Code = "#ifndef A_H\n"
"#define A_H\n"
"\n"
"\n"
"\n"
"#include <vector>\n"
"class A {};\n"
"#define MMM 123\n"
"#endif";
std::string Expected = "#ifndef A_H\n"
"#define A_H\n"
"\n"
"\n"
"\n"
"#include \"a.h\"\n"
"#include <vector>\n"
"class A {};\n"
"#define MMM 123\n"
"#endif";
EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
}
TEST_F(HeaderIncludesTest, InsertAfterMainHeader) {
std::string Code = "#include \"fix.h\"\n"
"\n"
"int main() {}";
std::string Expected = "#include \"fix.h\"\n"
"#include <a>\n"
"\n"
"int main() {}";
Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp)
.IncludeStyle;
EXPECT_EQ(Expected, insert(Code, "<a>"));
}
TEST_F(HeaderIncludesTest, InsertBeforeSystemHeaderLLVM) {
std::string Code = "#include <memory>\n"
"\n"
"int main() {}";
std::string Expected = "#include \"z.h\"\n"
"#include <memory>\n"
"\n"
"int main() {}";
EXPECT_EQ(Expected, insert(Code, "\"z.h\""));
}
TEST_F(HeaderIncludesTest, InsertAfterSystemHeaderGoogle) {
std::string Code = "#include <memory>\n"
"\n"
"int main() {}";
std::string Expected = "#include <memory>\n"
"#include \"z.h\"\n"
"\n"
"int main() {}";
Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp)
.IncludeStyle;
EXPECT_EQ(Expected, insert(Code, "\"z.h\""));
}
TEST_F(HeaderIncludesTest, InsertOneIncludeLLVMStyle) {
std::string Code = "#include \"x/fix.h\"\n"
"#include \"a.h\"\n"
"#include \"b.h\"\n"
"#include \"clang/Format/Format.h\"\n"
"#include <memory>\n";
std::string Expected = "#include \"x/fix.h\"\n"
"#include \"a.h\"\n"
"#include \"b.h\"\n"
"#include \"clang/Format/Format.h\"\n"
"#include \"llvm/x/y.h\"\n"
"#include <memory>\n";
EXPECT_EQ(Expected, insert(Code, "\"llvm/x/y.h\""));
}
TEST_F(HeaderIncludesTest, InsertIntoBlockSorted) {
std::string Code = "#include \"x/fix.h\"\n"
"#include \"a.h\"\n"
"#include \"c.h\"\n"
"#include <memory>\n";
std::string Expected = "#include \"x/fix.h\"\n"
"#include \"a.h\"\n"
"#include \"b.h\"\n"
"#include \"c.h\"\n"
"#include <memory>\n";
EXPECT_EQ(Expected, insert(Code, "\"b.h\""));
}
TEST_F(HeaderIncludesTest, InsertIntoFirstBlockOfSameKind) {
std::string Code = "#include \"x/fix.h\"\n"
"#include \"c.h\"\n"
"#include \"e.h\"\n"
"#include \"f.h\"\n"
"#include <memory>\n"
"#include <vector>\n"
"#include \"m.h\"\n"
"#include \"n.h\"\n";
std::string Expected = "#include \"x/fix.h\"\n"
"#include \"c.h\"\n"
"#include \"d.h\"\n"
"#include \"e.h\"\n"
"#include \"f.h\"\n"
"#include <memory>\n"
"#include <vector>\n"
"#include \"m.h\"\n"
"#include \"n.h\"\n";
EXPECT_EQ(Expected, insert(Code, "\"d.h\""));
}
TEST_F(HeaderIncludesTest, InsertIntoSystemBlockSorted) {
std::string Code = "#include \"x/fix.h\"\n"
"#include \"a.h\"\n"
"#include \"c.h\"\n"
"#include <a>\n"
"#include <z>\n";
std::string Expected = "#include \"x/fix.h\"\n"
"#include \"a.h\"\n"
"#include \"c.h\"\n"
"#include <a>\n"
"#include <vector>\n"
"#include <z>\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, InsertNewSystemIncludeGoogleStyle) {
std::string Code = "#include \"x/fix.h\"\n"
"\n"
"#include \"y/a.h\"\n"
"#include \"z/b.h\"\n";
// FIXME: inserting after the empty line following the main header might be
// preferred.
std::string Expected = "#include \"x/fix.h\"\n"
"#include <vector>\n"
"\n"
"#include \"y/a.h\"\n"
"#include \"z/b.h\"\n";
Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp)
.IncludeStyle;
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, NotConfusedByDefine) {
std::string Code = "void f() {}\n"
"#define A \\\n"
" int i;";
std::string Expected = "#include <vector>\n"
"void f() {}\n"
"#define A \\\n"
" int i;";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, SkippedTopComment) {
std::string Code = "// comment\n"
"\n"
" // comment\n";
std::string Expected = "// comment\n"
"\n"
" // comment\n"
"#include <vector>\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, SkippedMixedComments) {
std::string Code = "// comment\n"
"// comment \\\n"
" comment continued\n"
"/*\n"
"* comment\n"
"*/\n";
std::string Expected = "// comment\n"
"// comment \\\n"
" comment continued\n"
"/*\n"
"* comment\n"
"*/\n"
"#include <vector>\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, MultipleBlockCommentsInOneLine) {
std::string Code = "/*\n"
"* comment\n"
"*/ /* comment\n"
"*/\n"
"\n\n"
"/* c1 */ /*c2 */\n";
std::string Expected = "/*\n"
"* comment\n"
"*/ /* comment\n"
"*/\n"
"\n\n"
"/* c1 */ /*c2 */\n"
"#include <vector>\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, CodeAfterComments) {
std::string Code = "/*\n"
"* comment\n"
"*/ /* comment\n"
"*/\n"
"\n\n"
"/* c1 */ /*c2 */\n"
"\n"
"int x;\n";
std::string Expected = "/*\n"
"* comment\n"
"*/ /* comment\n"
"*/\n"
"\n\n"
"/* c1 */ /*c2 */\n"
"\n"
"#include <vector>\n"
"int x;\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, FakeHeaderGuardIfDef) {
std::string Code = "// comment \n"
"#ifdef X\n"
"#define X\n";
std::string Expected = "// comment \n"
"#include <vector>\n"
"#ifdef X\n"
"#define X\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, RealHeaderGuardAfterComments) {
std::string Code = "// comment \n"
"#ifndef X\n"
"#define X\n"
"int x;\n"
"#define Y 1\n";
std::string Expected = "// comment \n"
"#ifndef X\n"
"#define X\n"
"#include <vector>\n"
"int x;\n"
"#define Y 1\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, IfNDefWithNoDefine) {
std::string Code = "// comment \n"
"#ifndef X\n"
"int x;\n"
"#define Y 1\n";
std::string Expected = "// comment \n"
"#include <vector>\n"
"#ifndef X\n"
"int x;\n"
"#define Y 1\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, FakeHeaderGuard) {
std::string Code = "// comment \n"
"#ifndef X\n"
"#define 1\n";
std::string Expected = "// comment \n"
"#include <vector>\n"
"#ifndef X\n"
"#define 1\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, HeaderGuardWithComment) {
std::string Code = "// comment \n"
"#ifndef X // comment\n"
"// comment\n"
"/* comment\n"
"*/\n"
"/* comment */ #define X\n"
"int x;\n"
"#define Y 1\n";
std::string Expected = "// comment \n"
"#ifndef X // comment\n"
"// comment\n"
"/* comment\n"
"*/\n"
"/* comment */ #define X\n"
"#include <vector>\n"
"int x;\n"
"#define Y 1\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, EmptyCode) {
std::string Code = "";
std::string Expected = "#include <vector>\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, NoNewLineAtTheEndOfCode) {
std::string Code = "#include <map>";
std::string Expected = "#include <map>\n#include <vector>\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
}
TEST_F(HeaderIncludesTest, SkipExistingHeaders) {
std::string Code = "#include \"a.h\"\n"
"#include <vector>\n";
std::string Expected = "#include \"a.h\"\n"
"#include <vector>\n";
EXPECT_EQ(Expected, insert(Code, "<vector>"));
EXPECT_EQ(Expected, insert(Code, "\"a.h\""));
}
TEST_F(HeaderIncludesTest, AddIncludesWithDifferentForms) {
std::string Code = "#include <vector>\n";
// FIXME: this might not be the best behavior.
std::string Expected = "#include \"vector\"\n"
"#include <vector>\n";
EXPECT_EQ(Expected, insert(Code, "\"vector\""));
}
TEST_F(HeaderIncludesTest, NoInsertionAfterCode) {
std::string Code = "#include \"a.h\"\n"
"void f() {}\n"
"#include \"b.h\"\n";
std::string Expected = "#include \"a.h\"\n"
"#include \"c.h\"\n"
"void f() {}\n"
"#include \"b.h\"\n";
EXPECT_EQ(Expected, insert(Code, "\"c.h\""));
}
TEST_F(HeaderIncludesTest, NoInsertionInStringLiteral) {
std::string Code = "#include \"a.h\"\n"
"const char[] = R\"(\n"
"#include \"b.h\"\n"
")\";\n";
std::string Expected = "#include \"a.h\"\n"
"#include \"c.h\"\n"
"const char[] = R\"(\n"
"#include \"b.h\"\n"
")\";\n";
EXPECT_EQ(Expected, insert(Code, "\"c.h\""));
}
TEST_F(HeaderIncludesTest, NoInsertionAfterOtherDirective) {
std::string Code = "#include \"a.h\"\n"
"#ifdef X\n"
"#include \"b.h\"\n"
"#endif\n";
std::string Expected = "#include \"a.h\"\n"
"#include \"c.h\"\n"
"#ifdef X\n"
"#include \"b.h\"\n"
"#endif\n";
EXPECT_EQ(Expected, insert(Code, "\"c.h\""));
}
TEST_F(HeaderIncludesTest, CanInsertAfterLongSystemInclude) {
std::string Code = "#include \"a.h\"\n"
"// comment\n\n"
"#include <a/b/c/d/e.h>\n";
std::string Expected = "#include \"a.h\"\n"
"// comment\n\n"
"#include <a/b/c/d/e.h>\n"
"#include <x.h>\n";
EXPECT_EQ(Expected, insert(Code, "<x.h>"));
}
TEST_F(HeaderIncludesTest, CanInsertAfterComment) {
std::string Code = "#include \"a.h\"\n"
"// Comment\n"
"\n"
"/* Comment */\n"
"// Comment\n"
"\n"
"#include \"b.h\"\n";
std::string Expected = "#include \"a.h\"\n"
"// Comment\n"
"\n"
"/* Comment */\n"
"// Comment\n"
"\n"
"#include \"b.h\"\n"
"#include \"c.h\"\n";
EXPECT_EQ(Expected, insert(Code, "\"c.h\""));
}
TEST_F(HeaderIncludesTest, LongCommentsInTheBeginningOfFile) {
std::string Code = "// Loooooooooooooooooooooooooong comment\n"
"// Loooooooooooooooooooooooooong comment\n"
"// Loooooooooooooooooooooooooong comment\n"
"#include <string>\n"
"#include <vector>\n"
"\n"
"#include \"a.h\"\n"
"#include \"b.h\"\n";
std::string Expected = "// Loooooooooooooooooooooooooong comment\n"
"// Loooooooooooooooooooooooooong comment\n"
"// Loooooooooooooooooooooooooong comment\n"
"#include <string>\n"
"#include <vector>\n"
"\n"
"#include \"a.h\"\n"
"#include \"b.h\"\n"
"#include \"third.h\"\n";
Style = format::getGoogleStyle(format::FormatStyle::LanguageKind::LK_Cpp)
.IncludeStyle;
EXPECT_EQ(Expected, insert(Code, "\"third.h\""));
}
TEST_F(HeaderIncludesTest, SimpleDeleteInclude) {
std::string Code = "#include \"abc.h\"\n"
"#include \"xyz.h\" // comment\n"
"int x;\n";
std::string Expected = "#include \"abc.h\"\n"
"int x;\n";
EXPECT_EQ(Expected, remove(Code, "\"xyz.h\""));
}
TEST_F(HeaderIncludesTest, DeleteQuotedOnly) {
std::string Code = "#include \"abc.h\"\n"
"#include <abc.h>\n"
"int x;\n";
std::string Expected = "#include <abc.h>\n"
"int x;\n";
EXPECT_EQ(Expected, remove(Code, "\"abc.h\""));
}
TEST_F(HeaderIncludesTest, DeleteAllCode) {
std::string Code = "#include \"xyz.h\"\n";
std::string Expected = "";
EXPECT_EQ(Expected, remove(Code, "\"xyz.h\""));
}
TEST_F(HeaderIncludesTest, DeleteOnlyIncludesWithSameQuote) {
std::string Code = "#include \"xyz.h\"\n"
"#include \"xyz\"\n"
"#include <xyz.h>\n";
std::string Expected = "#include \"xyz.h\"\n"
"#include \"xyz\"\n";
EXPECT_EQ(Expected, remove(Code, "<xyz.h>"));
}
TEST_F(HeaderIncludesTest, CanDeleteAfterCode) {
std::string Code = "#include \"a.h\"\n"
"void f() {}\n"
"#include \"b.h\"\n";
std::string Expected = "#include \"a.h\"\n"
"void f() {}\n";
EXPECT_EQ(Expected, remove(Code, "\"b.h\""));
}
} // namespace
} // namespace tooling
} // namespace clang
|
// Copyright (c) 2018-2020 The PIVX developers
// Copyright (c) 2020-2021 The NestEgg Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zpivchain.h"
#include "guiinterface.h"
#include "invalid.h"
#include "main.h"
#include "txdb.h"
#include "wallet/wallet.h"
#include "zpiv/zpivmodule.h"
// 6 comes from OPCODE (1) + vch.size() (1) + BIGNUM size (4)
#define SCRIPT_OFFSET 6
// For Script size (BIGNUM/Uint256 size)
#define BIGNUM_SIZE 4
std::map<libzerocoin::CoinDenomination, int64_t> mapZerocoinSupply;
bool BlockToMintValueVector(const CBlock& block, const libzerocoin::CoinDenomination denom, std::vector<CBigNum>& vValues)
{
for (const CTransaction& tx : block.vtx) {
if(!tx.HasZerocoinMintOutputs())
continue;
for (const CTxOut& txOut : tx.vout) {
if(!txOut.IsZerocoinMint())
continue;
CValidationState state;
libzerocoin::PublicCoin coin(Params().GetConsensus().Zerocoin_Params(false));
if(!TxOutToPublicCoin(txOut, coin, state))
return false;
if (coin.getDenomination() != denom)
continue;
vValues.push_back(coin.getValue());
}
}
return true;
}
bool BlockToPubcoinList(const CBlock& block, std::list<libzerocoin::PublicCoin>& listPubcoins, bool fFilterInvalid)
{
for (const CTransaction& tx : block.vtx) {
if(!tx.HasZerocoinMintOutputs())
continue;
// Filter out mints that have used invalid outpoints
if (fFilterInvalid) {
bool fValid = true;
for (const CTxIn& in : tx.vin) {
if (!ValidOutPoint(in.prevout, INT_MAX)) {
fValid = false;
break;
}
}
if (!fValid)
continue;
}
uint256 txHash = tx.GetHash();
for (unsigned int i = 0; i < tx.vout.size(); i++) {
//Filter out mints that use invalid outpoints - edge case: invalid spend with minted change
if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX))
break;
const CTxOut txOut = tx.vout[i];
if(!txOut.IsZerocoinMint())
continue;
CValidationState state;
libzerocoin::PublicCoin pubCoin(Params().GetConsensus().Zerocoin_Params(false));
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
listPubcoins.emplace_back(pubCoin);
}
}
return true;
}
//return a list of zerocoin mints contained in a specific block
bool BlockToZerocoinMintList(const CBlock& block, std::list<CZerocoinMint>& vMints, bool fFilterInvalid)
{
for (const CTransaction& tx : block.vtx) {
if(!tx.HasZerocoinMintOutputs())
continue;
// Filter out mints that have used invalid outpoints
if (fFilterInvalid) {
bool fValid = true;
for (const CTxIn& in : tx.vin) {
if (!ValidOutPoint(in.prevout, INT_MAX)) {
fValid = false;
break;
}
}
if (!fValid)
continue;
}
uint256 txHash = tx.GetHash();
for (unsigned int i = 0; i < tx.vout.size(); i++) {
//Filter out mints that use invalid outpoints - edge case: invalid spend with minted change
if (fFilterInvalid && !ValidOutPoint(COutPoint(txHash, i), INT_MAX))
break;
const CTxOut txOut = tx.vout[i];
if(!txOut.IsZerocoinMint())
continue;
CValidationState state;
libzerocoin::PublicCoin pubCoin(Params().GetConsensus().Zerocoin_Params(false));
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
//version should not actually matter here since it is just a reference to the pubcoin, not to the privcoin
uint8_t version = 1;
CZerocoinMint mint = CZerocoinMint(pubCoin.getDenomination(), pubCoin.getValue(), 0, 0, false, version, nullptr);
mint.SetTxHash(tx.GetHash());
vMints.push_back(mint);
}
}
return true;
}
void FindMints(std::vector<CMintMeta> vMintsToFind, std::vector<CMintMeta>& vMintsToUpdate, std::vector<CMintMeta>& vMissingMints)
{
// see which mints are in our public zerocoin database. The mint should be here if it exists, unless
// something went wrong
for (CMintMeta meta : vMintsToFind) {
uint256 txHash;
if (!zerocoinDB->ReadCoinMint(meta.hashPubcoin, txHash)) {
vMissingMints.push_back(meta);
continue;
}
// make sure the txhash and block height meta data are correct for this mint
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(txHash, tx, hashBlock, true)) {
LogPrintf("%s : cannot find tx %s\n", __func__, txHash.GetHex());
vMissingMints.push_back(meta);
continue;
}
if (!mapBlockIndex.count(hashBlock)) {
LogPrintf("%s : cannot find block %s\n", __func__, hashBlock.GetHex());
vMissingMints.push_back(meta);
continue;
}
//see if this mint is spent
uint256 hashTxSpend;
bool fSpent = zerocoinDB->ReadCoinSpend(meta.hashSerial, hashTxSpend);
//if marked as spent, check that it actually made it into the chain
CTransaction txSpend;
uint256 hashBlockSpend;
if (fSpent && !GetTransaction(hashTxSpend, txSpend, hashBlockSpend, true)) {
LogPrintf("%s : cannot find spend tx %s\n", __func__, hashTxSpend.GetHex());
meta.isUsed = false;
vMintsToUpdate.push_back(meta);
continue;
}
//The mint has been incorrectly labelled as spent in zerocoinDB and needs to be undone
int nHeightTx = 0;
uint256 hashSerial = meta.hashSerial;
uint256 txidSpend;
if (fSpent && !IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend)) {
LogPrintf("%s : cannot find block %s. Erasing coinspend from zerocoinDB.\n", __func__, hashBlockSpend.GetHex());
meta.isUsed = false;
vMintsToUpdate.push_back(meta);
continue;
}
// is the denomination correct?
for (auto& out : tx.vout) {
if (!out.IsZerocoinMint())
continue;
libzerocoin::PublicCoin pubcoin(Params().GetConsensus().Zerocoin_Params(meta.nVersion < libzerocoin::PrivateCoin::PUBKEY_VERSION));
CValidationState state;
TxOutToPublicCoin(out, pubcoin, state);
if (GetPubCoinHash(pubcoin.getValue()) == meta.hashPubcoin && pubcoin.getDenomination() != meta.denom) {
LogPrintf("%s: found mismatched denom pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex());
meta.denom = pubcoin.getDenomination();
vMintsToUpdate.emplace_back(meta);
}
}
// if meta data is correct, then no need to update
if (meta.txid == txHash && meta.nHeight == mapBlockIndex[hashBlock]->nHeight && meta.isUsed == fSpent)
continue;
//mark this mint for update
meta.txid = txHash;
meta.nHeight = mapBlockIndex[hashBlock]->nHeight;
meta.isUsed = fSpent;
LogPrintf("%s: found updates for pubcoinhash = %s\n", __func__, meta.hashPubcoin.GetHex());
vMintsToUpdate.push_back(meta);
}
}
bool GetZerocoinMint(const CBigNum& bnPubcoin, uint256& txHash)
{
txHash = UINT256_ZERO;
return zerocoinDB->ReadCoinMint(bnPubcoin, txHash);
}
bool IsPubcoinInBlockchain(const uint256& hashPubcoin, uint256& txid)
{
txid.SetNull();
return zerocoinDB->ReadCoinMint(hashPubcoin, txid);
}
bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx)
{
uint256 txHash;
// if not in zerocoinDB then its not in the blockchain
if (!zerocoinDB->ReadCoinSpend(bnSerial, txHash))
return false;
return IsTransactionInChain(txHash, nHeightTx);
}
bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend)
{
CTransaction tx;
return IsSerialInBlockchain(hashSerial, nHeightTx, txidSpend, tx);
}
bool IsSerialInBlockchain(const uint256& hashSerial, int& nHeightTx, uint256& txidSpend, CTransaction& tx)
{
txidSpend.SetNull();
// if not in zerocoinDB then its not in the blockchain
if (!zerocoinDB->ReadCoinSpend(hashSerial, txidSpend))
return false;
return IsTransactionInChain(txidSpend, nHeightTx, tx);
}
std::string ReindexZerocoinDB()
{
AssertLockHeld(cs_main);
if (!zerocoinDB->WipeCoins("spends") || !zerocoinDB->WipeCoins("mints")) {
return _("Failed to wipe zerocoinDB");
}
uiInterface.ShowProgress(_("Reindexing zerocoin database..."), 0);
// initialize supply to 0
mapZerocoinSupply.clear();
for (auto& denom : libzerocoin::zerocoinDenomList) mapZerocoinSupply.insert(std::make_pair(denom, 0));
const Consensus::Params& consensus = Params().GetConsensus();
const int zc_start_height = consensus.vUpgrades[Consensus::UPGRADE_ZC].nActivationHeight;
CBlockIndex* pindex = chainActive[zc_start_height];
std::vector<std::pair<libzerocoin::CoinSpend, uint256> > vSpendInfo;
std::vector<std::pair<libzerocoin::PublicCoin, uint256> > vMintInfo;
while (pindex) {
uiInterface.ShowProgress(_("Reindexing zerocoin database..."), std::max(1, std::min(99, (int)((double)(pindex->nHeight - zc_start_height) / (double)(chainActive.Height() - zc_start_height) * 100))));
if (pindex->nHeight % 1000 == 0)
LogPrintf("Reindexing zerocoin : block %d...\n", pindex->nHeight);
CBlock block;
if (!ReadBlockFromDisk(block, pindex)) {
return _("Reindexing zerocoin failed");
}
// update supply
UpdateZPIVSupplyConnect(block, pindex, true);
for (const CTransaction& tx : block.vtx) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (tx.IsCoinBase())
break;
if (tx.ContainsZerocoins()) {
uint256 txid = tx.GetHash();
//Record Serials
if (tx.HasZerocoinSpendInputs()) {
for (auto& in : tx.vin) {
bool isPublicSpend = in.IsZerocoinPublicSpend();
if (!in.IsZerocoinSpend() && !isPublicSpend)
continue;
if (isPublicSpend) {
libzerocoin::ZerocoinParams* params = consensus.Zerocoin_Params(false);
PublicCoinSpend publicSpend(params);
CValidationState state;
if (!ZPIVModule::ParseZerocoinPublicSpend(in, tx, state, publicSpend)){
return _("Failed to parse public spend");
}
vSpendInfo.push_back(std::make_pair(publicSpend, txid));
} else {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(in);
vSpendInfo.push_back(std::make_pair(spend, txid));
}
}
}
//Record mints
if (tx.HasZerocoinMintOutputs()) {
for (auto& out : tx.vout) {
if (!out.IsZerocoinMint())
continue;
CValidationState state;
const bool v1params = !consensus.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_ZC_V2);
libzerocoin::PublicCoin coin(consensus.Zerocoin_Params(v1params));
TxOutToPublicCoin(out, coin, state);
vMintInfo.push_back(std::make_pair(coin, txid));
}
}
}
}
}
// Flush the zerocoinDB to disk every 100 blocks
if (pindex->nHeight % 100 == 0) {
if ((!vSpendInfo.empty() && !zerocoinDB->WriteCoinSpendBatch(vSpendInfo)) || (!vMintInfo.empty() && !zerocoinDB->WriteCoinMintBatch(vMintInfo)))
return _("Error writing zerocoinDB to disk");
vSpendInfo.clear();
vMintInfo.clear();
}
pindex = chainActive.Next(pindex);
}
uiInterface.ShowProgress("", 100);
// Final flush to disk in case any remaining information exists
if ((!vSpendInfo.empty() && !zerocoinDB->WriteCoinSpendBatch(vSpendInfo)) || (!vMintInfo.empty() && !zerocoinDB->WriteCoinMintBatch(vMintInfo)))
return _("Error writing zerocoinDB to disk");
uiInterface.ShowProgress("", 100);
return "";
}
bool RemoveSerialFromDB(const CBigNum& bnSerial)
{
return zerocoinDB->EraseCoinSpend(bnSerial);
}
libzerocoin::CoinSpend TxInToZerocoinSpend(const CTxIn& txin)
{
CDataStream serializedCoinSpend = ZPIVModule::ScriptSigToSerializedSpend(txin.scriptSig);
return libzerocoin::CoinSpend(serializedCoinSpend);
}
bool TxOutToPublicCoin(const CTxOut& txout, libzerocoin::PublicCoin& pubCoin, CValidationState& state)
{
CBigNum publicZerocoin;
std::vector<unsigned char> vchZeroMint;
vchZeroMint.insert(vchZeroMint.end(), txout.scriptPubKey.begin() + SCRIPT_OFFSET,
txout.scriptPubKey.begin() + txout.scriptPubKey.size());
publicZerocoin.setvch(vchZeroMint);
libzerocoin::CoinDenomination denomination = libzerocoin::AmountToZerocoinDenomination(txout.nValue);
LogPrint(BCLog::LEGACYZC, "%s : denomination %d for pubcoin %s\n", __func__, denomination, publicZerocoin.GetHex());
if (denomination == libzerocoin::ZQ_ERROR)
return state.DoS(100, error("TxOutToPublicCoin : txout.nValue is not correct"));
libzerocoin::PublicCoin checkPubCoin(Params().GetConsensus().Zerocoin_Params(false), publicZerocoin, denomination);
pubCoin = checkPubCoin;
return true;
}
//return a list of zerocoin spends contained in a specific block, list may have many denominations
std::list<libzerocoin::CoinDenomination> ZerocoinSpendListFromBlock(const CBlock& block, bool fFilterInvalid)
{
std::list<libzerocoin::CoinDenomination> vSpends;
for (const CTransaction& tx : block.vtx) {
if (!tx.HasZerocoinSpendInputs())
continue;
for (const CTxIn& txin : tx.vin) {
bool isPublicSpend = txin.IsZerocoinPublicSpend();
if (!txin.IsZerocoinSpend() && !isPublicSpend)
continue;
if (fFilterInvalid && !isPublicSpend) {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin);
if (invalid_out::ContainsSerial(spend.getCoinSerialNumber()))
continue;
}
libzerocoin::CoinDenomination c = libzerocoin::IntToZerocoinDenomination(txin.nSequence);
vSpends.push_back(c);
}
}
return vSpends;
}
int64_t GetZerocoinSupply()
{
AssertLockHeld(cs_main);
if (mapZerocoinSupply.empty())
return 0;
int64_t nTotal = 0;
for (auto& denom : libzerocoin::zerocoinDenomList) {
nTotal += libzerocoin::ZerocoinDenominationToAmount(denom) * mapZerocoinSupply.at(denom);
}
return nTotal;
}
bool UpdateZPIVSupplyConnect(const CBlock& block, CBlockIndex* pindex, bool fJustCheck)
{
AssertLockHeld(cs_main);
const Consensus::Params& consensus = Params().GetConsensus();
if (!consensus.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_ZC))
return true;
//Add mints to zEGG supply (mints are forever disabled after last checkpoint)
if (pindex->nHeight < consensus.height_last_ZC_AccumCheckpoint) {
std::list<CZerocoinMint> listMints;
std::set<uint256> setAddedToWallet;
BlockToZerocoinMintList(block, listMints, true);
for (const CZerocoinMint& m : listMints) {
mapZerocoinSupply.at(m.GetDenomination())++;
//Remove any of our own mints from the mintpool
if (!fJustCheck && pwalletMain) {
if (pwalletMain->IsMyMint(m.GetValue())) {
pwalletMain->UpdateMint(m.GetValue(), pindex->nHeight, m.GetTxHash(), m.GetDenomination());
// Add the transaction to the wallet
int posInBlock = 0;
for (posInBlock = 0; posInBlock < (int)block.vtx.size(); posInBlock++) {
auto& tx = block.vtx[posInBlock];
uint256 txid = tx.GetHash();
if (setAddedToWallet.count(txid))
continue;
if (txid == m.GetTxHash()) {
CWalletTx wtx(pwalletMain, tx);
wtx.nTimeReceived = block.GetBlockTime();
wtx.SetMerkleBranch(pindex, posInBlock);
pwalletMain->AddToWallet(wtx);
setAddedToWallet.insert(txid);
}
}
}
}
}
}
//Remove spends from zEGG supply
std::list<libzerocoin::CoinDenomination> listDenomsSpent = ZerocoinSpendListFromBlock(block, true);
for (const libzerocoin::CoinDenomination& denom : listDenomsSpent) {
mapZerocoinSupply.at(denom)--;
// zerocoin failsafe
if (mapZerocoinSupply.at(denom) < 0)
return error("Block contains zerocoins that spend more than are in the available supply to spend");
}
// Update Wrapped Serials amount
// A one-time event where only the zEGG supply was off (due to serial duplication off-chain on main net)
if (Params().NetworkID() == CBaseChainParams::MAIN && pindex->nHeight == consensus.height_last_ZC_WrappedSerials + 1) {
for (const libzerocoin::CoinDenomination& denom : libzerocoin::zerocoinDenomList)
mapZerocoinSupply.at(denom) += GetWrapppedSerialInflation(denom);
}
for (const libzerocoin::CoinDenomination& denom : libzerocoin::zerocoinDenomList)
LogPrint(BCLog::LEGACYZC, "%s coins for denomination %d pubcoin %s\n", __func__, denom, mapZerocoinSupply.at(denom));
return true;
}
bool UpdateZPIVSupplyDisconnect(const CBlock& block, CBlockIndex* pindex)
{
AssertLockHeld(cs_main);
const Consensus::Params& consensus = Params().GetConsensus();
if (!consensus.NetworkUpgradeActive(pindex->nHeight, Consensus::UPGRADE_ZC))
return true;
// Undo Update Wrapped Serials amount
// A one-time event where only the zEGG supply was off (due to serial duplication off-chain on main net)
if (Params().NetworkID() == CBaseChainParams::MAIN && pindex->nHeight == consensus.height_last_ZC_WrappedSerials + 1) {
for (const libzerocoin::CoinDenomination& denom : libzerocoin::zerocoinDenomList)
mapZerocoinSupply.at(denom) -= GetWrapppedSerialInflation(denom);
}
// Re-add spends to zEGG supply
std::list<libzerocoin::CoinDenomination> listDenomsSpent = ZerocoinSpendListFromBlock(block, true);
for (const libzerocoin::CoinDenomination& denom : listDenomsSpent) {
mapZerocoinSupply.at(denom)++;
}
// Remove mints from zEGG supply (mints are forever disabled after last checkpoint)
if (pindex->nHeight < consensus.height_last_ZC_AccumCheckpoint) {
std::list<CZerocoinMint> listMints;
std::set<uint256> setAddedToWallet;
BlockToZerocoinMintList(block, listMints, true);
for (const CZerocoinMint& m : listMints) {
const libzerocoin::CoinDenomination denom = m.GetDenomination();
mapZerocoinSupply.at(denom)--;
// zerocoin failsafe
if (mapZerocoinSupply.at(denom) < 0)
return error("Block contains zerocoins that spend more than are in the available supply to spend");
}
}
for (const libzerocoin::CoinDenomination& denom : libzerocoin::zerocoinDenomList)
LogPrint(BCLog::LEGACYZC, "%s coins for denomination %d pubcoin %s\n", __func__, denom, mapZerocoinSupply.at(denom));
return true;
}
|
#include<iostream>
using namespace std;
int main()
{
int i , j;
int array[9][9];
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
cin>>array[i][j];
}
}
return 0;
}
|
//===- CalyxDialect.cpp - Implement the Calyx dialect ---------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the Calyx dialect.
//
//===----------------------------------------------------------------------===//
#include "circt/Dialect/Calyx/CalyxDialect.h"
#include "circt/Dialect/Calyx/CalyxOps.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/DialectImplementation.h"
using namespace circt;
using namespace circt::calyx;
//===----------------------------------------------------------------------===//
// Dialect specification.
//===----------------------------------------------------------------------===//
void CalyxDialect::initialize() {
// Register operations.
addOperations<
#define GET_OP_LIST
#include "circt/Dialect/Calyx/Calyx.cpp.inc"
>();
}
// Provide implementations for the enums and attributes we use.
#include "circt/Dialect/Calyx/CalyxEnums.cpp.inc"
#include "circt/Dialect/Calyx/CalyxAttrs.cpp.inc"
|
//===- lib/Tooling/Execution.cpp - Implements tool execution framework. ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Execution.h"
#include "clang/Tooling/ToolExecutorPluginRegistry.h"
#include "clang/Tooling/Tooling.h"
LLVM_INSTANTIATE_REGISTRY(clang::tooling::ToolExecutorPluginRegistry)
namespace clang {
namespace tooling {
static llvm::cl::opt<std::string>
ExecutorName("executor", llvm::cl::desc("The name of the executor to use."),
llvm::cl::init("standalone"));
void InMemoryToolResults::addResult(StringRef Key, StringRef Value) {
KVResults.push_back({Key.str(), Value.str()});
}
std::vector<std::pair<std::string, std::string>>
InMemoryToolResults::AllKVResults() {
return KVResults;
}
void InMemoryToolResults::forEachResult(
llvm::function_ref<void(StringRef Key, StringRef Value)> Callback) {
for (const auto &KV : KVResults) {
Callback(KV.first, KV.second);
}
}
void ExecutionContext::reportResult(StringRef Key, StringRef Value) {
Results->addResult(Key, Value);
}
llvm::Error
ToolExecutor::execute(std::unique_ptr<FrontendActionFactory> Action) {
return execute(std::move(Action), ArgumentsAdjuster());
}
llvm::Error ToolExecutor::execute(std::unique_ptr<FrontendActionFactory> Action,
ArgumentsAdjuster Adjuster) {
std::vector<
std::pair<std::unique_ptr<FrontendActionFactory>, ArgumentsAdjuster>>
Actions;
Actions.emplace_back(std::move(Action), std::move(Adjuster));
return execute(Actions);
}
namespace internal {
llvm::Expected<std::unique_ptr<ToolExecutor>>
createExecutorFromCommandLineArgsImpl(int &argc, const char **argv,
llvm::cl::OptionCategory &Category,
const char *Overview) {
auto OptionsParser =
CommonOptionsParser::create(argc, argv, Category, llvm::cl::ZeroOrMore,
/*Overview=*/Overview);
if (!OptionsParser)
return OptionsParser.takeError();
for (auto I = ToolExecutorPluginRegistry::begin(),
E = ToolExecutorPluginRegistry::end();
I != E; ++I) {
if (I->getName() != ExecutorName) {
continue;
}
std::unique_ptr<ToolExecutorPlugin> Plugin(I->instantiate());
llvm::Expected<std::unique_ptr<ToolExecutor>> Executor =
Plugin->create(*OptionsParser);
if (!Executor) {
return llvm::make_error<llvm::StringError>(
llvm::Twine("Failed to create '") + I->getName() +
"': " + llvm::toString(Executor.takeError()) + "\n",
llvm::inconvertibleErrorCode());
}
return std::move(*Executor);
}
return llvm::make_error<llvm::StringError>(
llvm::Twine("Executor \"") + ExecutorName + "\" is not registered.",
llvm::inconvertibleErrorCode());
}
} // end namespace internal
llvm::Expected<std::unique_ptr<ToolExecutor>>
createExecutorFromCommandLineArgs(int &argc, const char **argv,
llvm::cl::OptionCategory &Category,
const char *Overview) {
return internal::createExecutorFromCommandLineArgsImpl(argc, argv, Category,
Overview);
}
// This anchor is used to force the linker to link in the generated object file
// and thus register the StandaloneToolExecutorPlugin etc.
extern volatile int StandaloneToolExecutorAnchorSource;
extern volatile int AllTUsToolExecutorAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED StandaloneToolExecutorAnchorDest =
StandaloneToolExecutorAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED AllTUsToolExecutorAnchorDest =
AllTUsToolExecutorAnchorSource;
} // end namespace tooling
} // end namespace clang
|
//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "PluginCanvas.h"
#include "../OrbitPlugin/OrbitSDK.h"
//-----------------------------------------------------------------------------
PluginCanvas::PluginCanvas(Orbit::Plugin* a_Plugin)
: GlCanvas(), m_Plugin(a_Plugin) {}
//-----------------------------------------------------------------------------
PluginCanvas::~PluginCanvas() {}
//-----------------------------------------------------------------------------
void PluginCanvas::OnTimer() { GlCanvas::OnTimer(); }
//-----------------------------------------------------------------------------
void PluginCanvas::ZoomAll() {}
//-----------------------------------------------------------------------------
void PluginCanvas::KeyPressed(unsigned int a_KeyCode, bool a_Ctrl, bool a_Shift,
bool a_Alt) {
if (!m_ImguiActive) {
switch (a_KeyCode) {
case 'A':
ZoomAll();
break;
}
}
ImGuiIO& io = ImGui::GetIO();
io.KeyCtrl = a_Ctrl;
io.KeyShift = a_Shift;
io.KeyAlt = a_Alt;
Orbit_ImGui_KeyCallback(this, a_KeyCode, true);
}
//-----------------------------------------------------------------------------
void PluginCanvas::RenderUI() {
ScopeImguiContext state(m_ImGuiContext);
Orbit_ImGui_NewFrame(this);
if (m_Plugin) {
m_Plugin->Draw(ImGui::GetCurrentContext(), getWidth(), getHeight());
}
// Rendering
glViewport(0, 0, getWidth(), getHeight());
ImGui::Render();
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81_bad.cpp
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-81_bad.tmpl.cpp
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81.h"
#define HELLO_STRING "hello"
namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81
{
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81_bad::action(size_t data) const
{
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
}
#endif /* OMITBAD */
|
#include <QtCore>
#include "currencymodel.h"
CurrencyModel::CurrencyModel(QObject *parent) : QAbstractTableModel(parent) { }
void CurrencyModel::setCurrencyMap(const QMap<QString, double> &map)
{
currencyMap = map;
//reset();
beginResetModel();
endResetModel();
}
int CurrencyModel::rowCount(const QModelIndex & /* parent */) const
{
return static_cast<int>(currencyMap.count());
}
int CurrencyModel::columnCount(const QModelIndex & /* parent */) const
{
return static_cast<int>(currencyMap.count());
}
QVariant CurrencyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (role == Qt::TextAlignmentRole) {
return int(Qt::AlignRight | Qt::AlignVCenter);
}
if (role == Qt::DisplayRole) {
QString rowCurrency = currencyAt(index.row());
QString columnCurrency = currencyAt(index.column());
if (currencyMap.value(rowCurrency) == 0.0) {
return "####";
}
double amount = currencyMap.value(columnCurrency)
/ currencyMap.value(rowCurrency);
return QString("%1").arg(amount, 0, 'f', 4);
}
return QVariant();
}
QVariant CurrencyModel::headerData(
int section, Qt::Orientation /* orientation */, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
return currencyAt(section);
}
QString CurrencyModel::currencyAt(qsizetype offset) const
{
auto iter = currencyMap.begin();
while (offset > 0) {
++iter;
--offset;
}
return iter.key();
}
|
#include "simppl/detail/util.h"
#include <cstring>
#include <cassert>
#include <cstdio>
namespace simppl
{
namespace dbus
{
namespace detail
{
char* create_objectpath(const char* iface, const char* role)
{
size_t capacity = strlen(role) + strlen(iface) + 3;
char* objectpath = new char[capacity];
sprintf(objectpath, "/%s/%s", iface, role);
char* p = objectpath;
while(*p)
{
if (*p == '.')
*p = '/';
++p;
}
return objectpath;
}
char* create_busname(const char* iface, const char* role)
{
size_t capacity = strlen(role) + strlen(iface) + 2;
char* busname = new char[capacity];
sprintf(busname, "%s.%s", iface, role);
return busname;
}
std::vector<std::string> extract_interfaces(std::size_t iface_count, const char* mangled_iface_list)
{
assert(mangled_iface_list);
assert(strcmp(mangled_iface_list, "simppl::make_typelist<") > 0);
// The `mangled_iface` string will be on the form:
//
// simppl::make_typelist<
// ns1::interface1<Args...>,
// ns2::interface2<Args...>
// >
//
// We are just interested in the "ns1::interface1" part.
std::vector<std::string> interfaces;
interfaces.reserve(iface_count);
// skip the "simppl::make_typelist<" part
const char* begin = mangled_iface_list + strlen("simppl::make_typelist<");
do {
const char* end = strchr(begin, '<');
interfaces.push_back(make_interface_name(begin, end));
begin = find_next_interface(end);
} while (begin);
return interfaces;
}
std::string make_interface_name(const char* src, const char* end)
{
assert(end > src);
std::string name(end - src, '\0');
auto dst = name.begin();
for (; src != end; ++dst, ++src) {
if (*src == ':') {
*dst = '.';
++src;
} else {
*dst = *src;
}
}
name.resize(dst-name.begin());
return name;
}
const char* find_next_interface(const char* s) {
assert(s && "input cannot be null");
assert(*s == '<' && "expected '<'");
++s;
int level = 1;
for (; s && level > 0; ++s) {
if (*s == '<') {
++level;
} else if (*s == '>') {
--level;
}
}
assert(level == 0 && "unbalanced angle brackets");
for (; isspace(*s); ++s)
;
if (*s == ',') {
for (++s; isspace(*s); ++s)
;
return s;
} else if (*s == '>') {
return nullptr;
} else {
assert(false && "expected ',' or '>'");
return nullptr;
}
}
char* make_error_name(char* str)
{
char* to = str;
char* from = str;
while(*from)
{
if (*from == ':')
{
*to++ = '.';
from += 2;
}
else
*to++ = *from++;
}
*to = '\0';
return str;
}
} // namespace detail
} // namespace dbus
} // namespace simppl
|
/**
* Copyright 2019-2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "debug/draw.h"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <string>
#include "ir/meta_func_graph.h"
#include "ir/param_info.h"
#include "ir/primitive.h"
#include "ir/graph_utils.h"
#include "utils/utils.h"
#include "frontend/operator/composite/composite.h"
#include "pipeline/jit/parse/resolve.h"
#include "ir/tensor.h"
#include "pipeline/jit/base.h"
#include "debug/common.h"
namespace mindspore {
// namespace to support debug utils
namespace draw {
namespace {
// Only for ValueNode
std::string ValueType(const ValueNodePtr &node) {
if (node == nullptr) {
return "";
}
auto v = node->value();
return v->type_name();
}
std::string ReplaceSpecialChar(const std::string &str) {
std::ostringstream oss;
for (size_t i = 0; i < str.size(); i++) {
if (str[i] == '<') {
oss << "ใ";
} else if (str[i] == '>') {
oss << "ใ";
} else {
oss << str[i];
}
}
return oss.str();
}
} // namespace
// API of debug utils
void DrawNodes(const std::vector<AnfNodePtr> &nodes, OrderedMap<FuncGraphPtr, std::shared_ptr<BaseDigraph>> *sub_graphs,
bool is_user) {
if (sub_graphs == nullptr) {
return;
}
for (auto &nd : nodes) {
MS_EXCEPTION_IF_NULL(nd);
auto sub_graph = nd->func_graph();
if (sub_graph != nullptr) {
auto gsub = (*sub_graphs)[sub_graph];
if (gsub == nullptr) {
if (is_user) {
gsub = std::make_shared<ModelDigraph>(sub_graph->ToString());
} else {
gsub = std::make_shared<Digraph>(sub_graph->ToString());
}
(*sub_graphs)[sub_graph] = gsub;
}
if (!nd->isa<Parameter>()) {
gsub->Node(nd);
}
}
}
}
void DrawValueNodes(const std::vector<AnfNodePtr> &nodes,
OrderedMap<FuncGraphPtr, std::shared_ptr<BaseDigraph>> *sub_graphs) {
if (sub_graphs == nullptr) {
return;
}
int dup_idx = 0;
for (auto &nd : nodes) {
for (auto &t : GetInputs(nd)) {
MS_EXCEPTION_IF_NULL(t);
MS_EXCEPTION_IF_NULL(nd);
if (t->isa<ValueNode>() && (*sub_graphs).find(nd->func_graph()) != (*sub_graphs).end()) {
(*sub_graphs)[nd->func_graph()]->Node(t, dup_idx);
dup_idx++;
} else if (t->isa<Parameter>() && (*sub_graphs).find(t->func_graph()) != (*sub_graphs).end()) {
(*sub_graphs)[t->func_graph()]->Node(t, dup_idx);
dup_idx++;
}
}
}
}
void DrawEdges(const std::vector<AnfNodePtr> &nodes, const std::shared_ptr<BaseDigraph> &digraph, bool is_user) {
if (digraph == nullptr) {
return;
}
int dup_idx = 0;
int offset = 0;
if (is_user) {
offset = 1;
}
// Draw edge
for (auto &nd : nodes) {
auto &succs = GetInputs(nd);
auto num = succs.size();
for (size_t i = 0; i < num; i++) {
auto &t = succs.at(i);
MS_EXCEPTION_IF_NULL(t);
if (t->isa<ValueNode>() || t->isa<Parameter>()) {
if ((!is_user) || (i != 0)) {
// `SizeToInt(i) - offset` is just for printing as text
digraph->Edge(t, nd, SizeToInt(i) - offset, dup_idx);
}
if (IsValueNode<FuncGraph>(t)) {
auto const_graph = GetValueNode<FuncGraphPtr>(t);
digraph->Edge(t, const_graph, dup_idx);
}
dup_idx++;
} else {
digraph->Edge(t, nd, SizeToInt(i) - offset);
}
}
}
}
void DrawByOpt(std::string filename, const FuncGraphPtr &func_graph, bool is_user) {
if (func_graph == nullptr) {
return;
}
auto ret = func_graph->get_return();
auto nodes = DeepScopedGraphSearch(ret);
std::shared_ptr<BaseDigraph> digraph;
OrderedMap<FuncGraphPtr, std::shared_ptr<BaseDigraph>> sub_graphs;
ChangeFileMode(filename, S_IRWXU);
if (is_user) {
digraph = std::make_shared<ModelDigraph>("mindspore", filename);
} else {
digraph = std::make_shared<Digraph>("mindspore", filename);
}
MS_EXCEPTION_IF_NULL(digraph);
digraph->Start();
// Draw nodes
DrawNodes(nodes, &sub_graphs, is_user);
// Draw ValueNodes on CNodes
DrawValueNodes(nodes, &sub_graphs);
// Draw subgraph
for (const auto &gsub : sub_graphs) {
digraph->SubGraph(gsub.first, gsub.second);
}
// Draw edge
DrawEdges(nodes, digraph, is_user);
digraph->End();
// set file mode to read only by user
ChangeFileMode(filename, S_IRUSR);
}
#ifdef ENABLE_DUMP_IR
void Draw(const std::string &filename, const FuncGraphPtr &func_graph) {
const std::string dot_suffix = ".dot";
std::string filename_with_suffix =
(filename.rfind(dot_suffix) != (filename.size() - dot_suffix.size())) ? (filename + dot_suffix) : filename;
DrawByOpt(pipeline::GetSaveGraphsPathName(Common::AddId(filename_with_suffix, dot_suffix)), func_graph, false);
}
void DrawUserFuncGraph(const std::string &filename, const FuncGraphPtr &func_graph) {
DrawByOpt(pipeline::GetSaveGraphsPathName(Common::AddId(filename, ".dot")), func_graph, true);
}
#else
void Draw(const std::string &, const FuncGraphPtr &) {
static bool already_printed = false;
if (already_printed) {
return;
}
already_printed = true;
MS_LOG(WARNING) << "The functionality of dumping function graph IR in graphviz dot format is disabled, "
<< "please recompile source to enable it. See help of building script.";
}
void DrawUserFuncGraph(const std::string &, const FuncGraphPtr &) {
static bool already_printed = false;
if (already_printed) {
return;
}
already_printed = true;
MS_LOG(WARNING) << "The functionality of dumping function graph IR in graphviz dot format is disabled, "
<< "please recompile source to enable it. See help of building script.";
}
#endif
std::string Graphviz::Shape(AnfNodePtr node) {
if (node == nullptr) {
return "";
}
if (node->isa<CNode>()) {
return "plaintext";
}
if (node->isa<Parameter>()) {
return "octagon";
}
if (IsValueNode<FuncGraph>(node)) {
return "oval";
}
return "plaintext";
}
std::string Graphviz::Color(const AnfNodePtr &node) {
if (node == nullptr) {
return "";
}
if (node->isa<CNode>()) {
return "cornsilk";
}
if (node->isa<Parameter>()) {
return "paleturquoise";
}
if (IsValueNode<FuncGraph>(node)) {
return "palegreen";
}
return "lavender";
}
void BaseDigraph::Start() {
buffer_ << "digraph " << name_ << " {" << std::endl;
buffer_ << "compound=true" << std::endl;
}
void BaseDigraph::Head(const AnfNodePtr &node, int id) {
if (node == nullptr) {
return;
}
buffer_ << "node" << node << "_" << id;
if (node->isa<CNode>() || (node->isa<ValueNode>() && !IsValueNode<FuncGraph>(node))) {
buffer_ << ":core";
}
}
void BaseDigraph::Tail(const AnfNodePtr &node, int idx, int id) {
if (node == nullptr) {
return;
}
buffer_ << "node" << node << "_" << id;
buffer_ << ":" << idx;
}
void BaseDigraph::Tail(const FuncGraphPtr &func_graph) {
if (func_graph == nullptr) {
return;
}
buffer_ << "node" << func_graph->get_return() << "_" << 0;
}
void BaseDigraph::Edge(AnfNodePtr start, FuncGraphPtr end, int id_start) {
Head(start, id_start);
buffer_ << "->";
Tail(end);
buffer_ << "[lhead=cluster_" << end;
buffer_ << ",dir=both,arrowhead=dot,style=filled,color=blue]";
buffer_ << std::endl;
}
void BaseDigraph::End() {
buffer_ << "}" << std::endl;
if (fout_.is_open()) {
fout_ << buffer_.str();
}
}
void BaseDigraph::FuncGraphParameters(const FuncGraphPtr &key) {
buffer_ << "parameters_" << key << "[shape=plaintext ";
buffer_ << "label=<<table bgcolor='paleturquoise' cellspacing='0' cellborder='1' border='0'>";
buffer_ << "<tr><td>parameters</td></tr>";
int count = 0;
for (auto ¶meter : key->parameters()) {
buffer_ << "<tr><td>";
buffer_ << parameter->ToString();
auto param = parameter->cast<ParameterPtr>();
if (param->has_default()) {
auto tensor_v = param->default_param();
if (tensor_v && tensor_v->isa<tensor::Tensor>()) {
auto tensor = tensor_v->cast<tensor::TensorPtr>();
auto &shape = tensor->shape();
std::ostringstream shape_str;
std::copy(shape.begin(), shape.end(), std::ostream_iterator<int>(shape_str, ","));
buffer_ << "[" << shape_str.str() << "]";
}
}
buffer_ << "</td></tr>";
count++;
// wrap the text.
if (count % 10 == 0) {
buffer_ << "\n";
}
}
buffer_ << "</table>>,];";
}
void BaseDigraph::SubGraph(const FuncGraphPtr &key, const std::shared_ptr<BaseDigraph> &gsub) {
if (key == nullptr || gsub == nullptr) {
return;
}
std::string label = key->debug_info()->get_full_name();
if (label.empty()) {
label = gsub->name();
}
std::string label_managed = "[managed]";
if (key->manager() == nullptr) {
label_managed = "[not managed]";
}
label += label_managed;
gsub->FuncGraphParameters(key);
buffer_ << "subgraph cluster_" << key << "{" << std::endl;
buffer_ << "id=cluster_" << key << std::endl;
buffer_ << "label=\"" << label << "\"" << std::endl;
buffer_ << "fontname=\"Courier New\"" << std::endl;
buffer_ << gsub->buffer().str();
buffer_ << "}" << std::endl;
}
Digraph::~Digraph() {
try {
if (fout_.is_open()) {
fout_.close();
}
} catch (const std::exception &e) {
MS_LOG(ERROR) << "Exception when closing file " << filename_;
}
}
static std::string ReplaceAll(std::string str, const std::string &from, const std::string &to) {
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
(void)str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;
}
static void DrawValueNode(Graphviz *const graph_obj, const ValueNodePtr &node) {
MS_EXCEPTION_IF_NULL(graph_obj);
graph_obj->buffer() << "label=<<table port='core' cellborder='0' cellspacing='2' bgcolor='" << graph_obj->Color(node)
<< "'>";
graph_obj->buffer() << "<tr><td bgcolor='white'>";
graph_obj->buffer() << ValueType(node);
graph_obj->buffer() << "</td></tr>";
graph_obj->buffer() << "<tr><td>";
if (IsValueNode<MetaFuncGraph>(node)) {
graph_obj->buffer() << node->value()->cast<MetaFuncGraphPtr>()->name();
} else if (IsValueNode<parse::NameSpace>(node)) {
graph_obj->buffer() << node->value()->cast<parse::NameSpacePtr>()->name();
} else if (IsValueNode<parse::Symbol>(node)) {
graph_obj->buffer() << ReplaceSpecialChar(node->value()->cast<parse::SymbolPtr>()->name());
} else {
std::ostringstream ss;
ss << node->value()->ToString();
std::string s = ReplaceAll(ss.str(), ", ", "<br/>");
graph_obj->buffer() << s;
ValuePtr value = node->value();
if (value->isa<Primitive>()) {
PrimitivePtr primitive = value->cast<PrimitivePtr>();
graph_obj->buffer() << "</td></tr>";
graph_obj->buffer() << "<tr><td align='left'>";
if (!primitive->instance_name().empty()) {
graph_obj->buffer() << "instance name:"
<< " ";
graph_obj->buffer() << primitive->instance_name();
graph_obj->buffer() << "<br/>";
}
auto attrs = primitive->attrs();
if (attrs.size() > 0) {
graph_obj->buffer() << "</td></tr>";
graph_obj->buffer() << "<tr><td align='left'>";
int i = 0;
for (const auto &attr : attrs) {
if (i != 0) {
graph_obj->buffer() << "<br/>";
}
graph_obj->buffer() << attr.first << " ";
if (attr.second == nullptr) {
graph_obj->buffer() << " ";
} else {
graph_obj->buffer() << attr.second->ToString();
}
i++;
}
}
}
}
graph_obj->buffer() << "</td></tr>";
graph_obj->buffer() << "</table>>,";
}
static void DrawParallelInfo(Graphviz *const graph_obj, const CNodePtr &node) {
if (graph_obj == nullptr || node == nullptr) {
return;
}
auto distributed_operation_info = node->user_data<parallel::OperatorInfo>();
if (distributed_operation_info != nullptr) {
auto strategyPtr = distributed_operation_info->strategy();
if (strategyPtr != nullptr) {
auto num = node->inputs().size();
graph_obj->buffer() << "<tr><td colspan='" << num << "' ";
graph_obj->buffer() << "bgcolor='" << graph_obj->Color(node) << "'>";
std::vector<ValuePtr> temp = {MakeValue(strategyPtr->GetInputStage()), MakeValue(strategyPtr->GetInputDim())};
ValueTuplePtr strategy_tuple = std::make_shared<ValueTuple>(temp);
graph_obj->buffer() << "Strategy " << strategy_tuple->ToString();
graph_obj->buffer() << "</td></tr>" << std::endl;
}
}
}
static void DrawCNode(Graphviz *const graph_obj, const CNodePtr &node) {
if (graph_obj == nullptr || node == nullptr || node->size() == 0) {
return;
}
auto num = node->size();
bool is_modelgraph = false;
if (typeid(*graph_obj) == typeid(ModelDigraph)) {
is_modelgraph = true;
num -= 1;
}
graph_obj->buffer() << "label=<<table port='core'>" << std::endl;
// Draw ports for CNode
if (num > 0) {
graph_obj->buffer() << "<tr>";
for (size_t i = 0; i < num; i++) {
graph_obj->buffer() << "<td port='" << i << "'>" << i << "</td>";
}
graph_obj->buffer() << "</tr>" << std::endl;
}
// Draw op name
graph_obj->buffer() << "<tr><td";
if (num > 0) {
graph_obj->buffer() << " colspan='" << num << "'";
}
graph_obj->buffer() << " bgcolor='" << graph_obj->Color(node) << "'>";
if (IsValueNode<Primitive>(node->input(0)) && is_modelgraph) {
auto primitive = GetValueNode<PrimitivePtr>(node->input(0));
graph_obj->buffer() << ReplaceAll(primitive->ToString(), ", ", "<br/>");
auto attrs = primitive->attrs();
if (attrs.size() > 0) {
graph_obj->buffer() << "</td></tr>" << std::endl << "<tr><td";
// Draw attrs
if (num > 0) {
graph_obj->buffer() << " colspan='" << num << "'";
}
graph_obj->buffer() << ">";
int i = 0;
for (auto &attr : attrs) {
if (i != 0) {
graph_obj->buffer() << "<br/>";
}
graph_obj->buffer() << attr.first << " " << attr.second->ToString();
i++;
}
}
graph_obj->buffer() << "CNode";
} else {
graph_obj->buffer() << "CNode(" << node->ToString() << ")";
}
graph_obj->buffer() << "</td></tr>" << std::endl;
DrawParallelInfo(graph_obj, node);
graph_obj->buffer() << "</table>>,";
}
void Digraph::Node(AnfNodePtr node, int id) {
if (node == nullptr) {
return;
}
buffer_ << "node" << node << "_" << id;
buffer_ << "[";
// set fontname
buffer_ << "fontname=\"Courier New\",";
// set label and shape
buffer_ << "shape=" << Shape(node) << ",";
if (node->isa<CNode>()) {
DrawCNode(this, node->cast<CNodePtr>());
} else if (node->isa<ValueNode>() && !IsValueNode<FuncGraph>(node)) {
DrawValueNode(this, node->cast<ValueNodePtr>());
} else {
buffer_ << "label=\"" << node->ToString();
if (IsValueNode<FuncGraph>(node)) {
FuncGraphPtr nextNet = GetValueNode<FuncGraphPtr>(node);
std::string nextNetName = nextNet->debug_info()->get_full_name();
if (!nextNetName.empty()) {
buffer_ << "[" << nextNet->debug_info()->get_full_name().c_str() << "]";
}
}
buffer_ << "\","
<< "style=filled,fillcolor=" << Color(node) << ",";
}
// Set URL for func graph
if (IsValueNode<FuncGraph>(node)) {
buffer_ << "URL=\"#cluster_" << GetValueNode(node) << "\",";
}
buffer_ << "]" << std::endl;
}
void Digraph::Edge(AnfNodePtr start, AnfNodePtr end, int idx, int id_start) {
if (start == nullptr || end == nullptr) {
return;
}
Head(start, id_start);
buffer_ << "->";
Tail(end, idx);
buffer_ << "[arrowhead=vee,";
// check how many inputs for end
if (end->isa<CNode>()) {
auto cnode = end->cast<CNodePtr>();
MS_EXCEPTION_IF_NULL(cnode);
auto num = cnode->inputs().size();
if (idx == 0 && num > 1) {
buffer_ << "style=dashed";
}
}
buffer_ << "]" << std::endl;
}
ModelDigraph::~ModelDigraph() {
try {
if (fout_.is_open()) {
fout_.close();
}
} catch (const std::exception &e) {
MS_LOG(ERROR) << "exception when closing file " << filename_;
}
}
std::string ModelDigraph::Shape(AnfNodePtr node) {
if (node == nullptr) {
return "";
}
if (node->isa<CNode>()) {
return "plaintext";
}
if (node->isa<Parameter>()) {
return "ellipse";
}
if (IsValueNode<FuncGraph>(node)) {
return "oval";
}
return "plaintext";
}
void ModelDigraph::Node(AnfNodePtr node, int id) {
if (node == nullptr) {
return;
}
if (IsValueNode<Primitive>(node)) {
return;
}
buffer_ << "node" << node << "_" << id;
buffer_ << "[";
// set fontname
buffer_ << "fontname=\"Courier New\",";
// set label and shape
buffer_ << "shape=" << Shape(node) << ",";
if (node->isa<CNode>()) {
DrawCNode(this, node->cast<CNodePtr>());
} else if (node->isa<ValueNode>() && !IsValueNode<FuncGraph>(node)) {
DrawValueNode(this, node->cast<ValueNodePtr>());
} else {
buffer_ << "label=\"" << node->ToString() << "\",";
buffer_ << "style=filled,fillcolor=" << Color(node) << ",";
}
// Set URL for func graph
if (IsValueNode<FuncGraph>(node)) {
buffer_ << "URL=\"#cluster_" << GetValueNode(node) << "\",";
}
buffer_ << "]" << std::endl;
}
void ModelDigraph::Edge(AnfNodePtr start, AnfNodePtr end, int idx, int id_start) {
if (start == nullptr || end == nullptr) {
return;
}
Head(start, id_start);
buffer_ << "->";
Tail(end, idx);
buffer_ << "[arrowhead=vee,";
buffer_ << "]" << std::endl;
}
struct DrawerRegister {
DrawerRegister() {
FuncGraph::set_drawer(
[](const std::string &filename, const FuncGraphPtr &func_graph) { Draw(filename, func_graph); });
}
~DrawerRegister() = default;
} drawer_regsiter;
} // namespace draw
} // namespace mindspore
|
#include <iostream>
#include <fstream>
#include <cassert>
#include <string.h>
#include <sstream>
#include "cartesian.hpp"
#include "coord.hpp"
#include "fields.hpp"
#include <mpi.h>
using namespace std;
fields::fields(const char* filename, const int ndim_in, const int mode_in, const string material_in, const cartesian& cart) {
// constructor
assert(ndim_in == 2 || ndim_in == 3);
assert(mode_in == 2 || mode_in == 3);
assert(material_in == "elastic" || material_in == "plastic");
// read from input file
string line, loadfile, matfile;
ifstream paramfile(filename, ios::in);
if (paramfile.is_open()) {
// scan to start of fields list
while (getline(paramfile,line)) {
if (line == "[fdfault.fields]") {
break;
}
}
if (paramfile.eof()) {
cerr << "Error reading fields from input file\n";
MPI_Abort(MPI_COMM_WORLD,-1);
} else {
// read problem variables
for (int i=0; i<6; i++) {
paramfile >> s0[i];
}
paramfile >> loadfile;
paramfile >> matfile;
paramfile >> plastic_tensor;
}
} else {
cerr << "Error opening input file in fields.cpp\n";
MPI_Abort(MPI_COMM_WORLD,-1);
}
paramfile.close();
ndim = ndim_in;
mode = mode_in;
material = material_in;
if (ndim == 3) {
nfields = 9;
nmat = 3;
} else if (mode == 2) {
nfields = 5;
nmat = 3;
} else {
nfields = 3;
nmat = 2;
}
if (material == "elastic") {
nfieldsp = 0;
} else {
if (plastic_tensor) {
nfieldsp = 8;
} else {
nfieldsp = 2;
}
if (ndim == 2 && mode == 2) {
nfields = 6;
}
}
for (int i=0; i<ndim; i++) {
c.set_nx(i,cart.get_nx(i));
c.set_nx_loc(i,cart.get_nx_loc(i));
c.set_xm_loc(i,cart.get_xm_loc(i));
c.set_xm_ghost(i,cart.get_xm_ghost(i));
c.set_xp_ghost(i,cart.get_xp_ghost(i));
}
// allocate memory for fields
ndataf = (nfields+nfieldsp)*c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
ndatadf = nfields*c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
ndatax = ndim*c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
ndatametric = ndim*ndim*c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
ndatajac = c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
nxyz = c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
f = new double [ndataf];
df = new double [ndatadf];
x = new double [ndatax];
metric = new double [ndatametric];
jac = new double [ndatajac];
// set fields to zero
for (int i=0; i<ndataf; i++) {
f[i] = 0.;
}
for (int i=0; i<ndatadf; i++) {
df[i] = 0.;
}
// set up information on stress for calculating absolute stress
switch (ndim) {
case 3:
ns = 6;
nv = 3;
index[0] = 0;
index[1] = 1;
index[2] = 2;
index[3] = 3;
index[4] = 4;
index[5] = 5;
break;
case 2:
switch (mode) {
case 2:
ns = 3;
index[0] = 0;
index[1] = 1;
index[2] = 3;
if (material == "plastic") {
ns = 4;
index[3] = 5;
}
nv = 2;
break;
case 3:
ns = 2;
nv = 1;
index[0] = 2;
index[1] = 4;
}
}
// initialize MPI datatypes for exchanging with neighbors
init_exchange(cart);
// if problem heterogeneous, read load data from file
if (loadfile == "none") {
hetstress = false;
} else {
hetstress = true;
read_load(loadfile);
}
if (matfile == "none") {
hetmat = false;
} else {
hetmat = true;
read_mat(matfile);
}
}
fields::~fields() {
delete[] f;
delete[] df;
delete[] x;
delete[] metric;
delete[] jac;
if (hetstress) {
delete[] s;
}
if (hetmat) {
delete[] mat;
}
}
void fields::set_stress() {
// initialize fields to constant initial stress state
for (int i=0; i<ns; i++) {
for (int j=0; j<nxyz; j++) {
f[(nv+i)*nxyz+j] += s0[index[i]];
}
}
if (!hetstress) { return; }
for (int i=0; i<ns; i++) {
for (int j=0; j<nxyz; j++) {
f[(nv+i)*nxyz+j] += s[i*nxyz+j];
}
}
}
void fields::remove_stress() {
// initialize fields to constant initial stress state
for (int i=0; i<ns; i++) {
for (int j=0; j<nxyz; j++) {
f[(nv+i)*nxyz+j] -= s0[index[i]];
}
}
if (!hetstress) { return; }
for (int i=0; i<ns; i++) {
for (int j=0; j<nxyz; j++) {
f[(nv+i)*nxyz+j] -= s[i*nxyz+j];
}
}
}
void fields::init_exchange(const cartesian& cart) {
// copy cartesian parameters
comm = cart.comm;
// get info on neighboring process for different shifts
for (int i=0; i<ndim; i++) {
MPI_Cart_shift(comm,i,1,&shiftp_source[i],&shiftp_dest[i]);
MPI_Cart_shift(comm,i,-1,&shiftm_source[i],&shiftm_dest[i]);
}
// set up strided arrays for sending
MPI_Type_vector(nfields,c.get_xp_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&slicep[0]);
MPI_Type_commit(&slicep[0]);
MPI_Type_vector(nfields,c.get_xm_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&slicem[0]);
MPI_Type_commit(&slicem[0]);
MPI_Type_vector(nfields*c.get_nx_tot(0),c.get_xp_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&slicep[1]);
MPI_Type_commit(&slicep[1]);
MPI_Type_vector(nfields*c.get_nx_tot(0),c.get_xm_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&slicem[1]);
MPI_Type_commit(&slicem[1]);
MPI_Type_vector(nfields*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xp_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&slicep[2]);
MPI_Type_commit(&slicep[2]);
MPI_Type_vector(nfields*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xm_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&slicem[2]);
MPI_Type_commit(&slicem[2]);
// set up indices for destination in fields array
shiftp_source_index[0] = (c.get_max_loc(0)-c.get_xp_ghost(0))*c.get_nx_tot(1)*c.get_nx_tot(2);
shiftp_source_index[1] = (c.get_max_loc(1)-c.get_xp_ghost(1))*c.get_nx_tot(2);
shiftp_source_index[2] = c.get_max_loc(2)-c.get_xp_ghost(2);
shiftp_dest_index[0] = 0;
shiftp_dest_index[1] = 0;
shiftp_dest_index[2] = 0;
shiftm_source_index[0] = c.get_xm_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
shiftm_source_index[1] = c.get_xm_ghost(1)*c.get_nx_tot(2);
shiftm_source_index[2] = c.get_xm_ghost(2);
shiftm_dest_index[0] = c.get_max_loc(0)*c.get_nx_tot(1)*c.get_nx_tot(2);
shiftm_dest_index[1] = c.get_max_loc(1)*c.get_nx_tot(2);
shiftm_dest_index[2] = c.get_max_loc(2);
}
void fields::exchange_neighbors() {
// exchange fields with neighbors
MPI_Status status;
// exchange neighbors as needed
for (int i=0; i<ndim; i++) {
MPI_Sendrecv(&f[shiftp_source_index[i]], 1, slicep[i], shiftp_dest[i], 2*i,
&f[shiftp_dest_index[i]], 1, slicem[i], shiftp_source[i], 2*i, comm, &status);
MPI_Sendrecv(&f[shiftm_source_index[i]], 1, slicem[i], shiftm_dest[i], 2*i+1,
&f[shiftm_dest_index[i]], 1, slicep[i], shiftm_source[i], 2*i+1, comm, &status);
}
}
void fields::scale_df(const double A) {
// scales df by RK coefficient A
for (int i=0; i<ndatadf; i++) {
df[i] *= A;
}
}
void fields::update(const double B) {
// calculates second part of a RK time step (update fields)
for (int i=0; i<ndatadf; i++) {
f[i] += B*df[i];
}
}
void fields::exchange_grid() {
MPI_Status status;
MPI_Datatype gridslicep[3];
MPI_Datatype gridslicem[3];
// set up strided arrays for sending x data
MPI_Type_vector(ndim,c.get_xp_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicep[0]);
MPI_Type_commit(&gridslicep[0]);
MPI_Type_vector(ndim,c.get_xm_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicem[0]);
MPI_Type_commit(&gridslicem[0]);
MPI_Type_vector(ndim*c.get_nx_tot(0),c.get_xp_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[1]);
MPI_Type_commit(&gridslicep[1]);
MPI_Type_vector(ndim*c.get_nx_tot(0),c.get_xm_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[1]);
MPI_Type_commit(&gridslicem[1]);
MPI_Type_vector(ndim*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xp_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[2]);
MPI_Type_commit(&gridslicep[2]);
MPI_Type_vector(ndim*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xm_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[2]);
MPI_Type_commit(&gridslicem[2]);
// exchange x data
for (int i=0; i<ndim; i++) {
MPI_Sendrecv(&x[shiftp_source_index[i]], 1, gridslicep[i], shiftp_dest[i], 2*i,
&x[shiftp_dest_index[i]], 1, gridslicem[i], shiftp_source[i], 2*i, comm, &status);
MPI_Sendrecv(&x[shiftm_source_index[i]], 1, gridslicem[i], shiftm_dest[i], 2*i+1,
&x[shiftm_dest_index[i]], 1, gridslicep[i], shiftm_source[i], 2*i+1, comm, &status);
}
// free strided arrays
MPI_Type_free(&gridslicem[0]);
MPI_Type_free(&gridslicem[1]);
MPI_Type_free(&gridslicem[2]);
MPI_Type_free(&gridslicep[0]);
MPI_Type_free(&gridslicep[1]);
MPI_Type_free(&gridslicep[2]);
// set up strided arrays for sending metric data
MPI_Type_vector(ndim*ndim,c.get_xp_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicep[0]);
MPI_Type_commit(&gridslicep[0]);
MPI_Type_vector(ndim*ndim,c.get_xm_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicem[0]);
MPI_Type_commit(&gridslicem[0]);
MPI_Type_vector(ndim*ndim*c.get_nx_tot(0),c.get_xp_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[1]);
MPI_Type_commit(&gridslicep[1]);
MPI_Type_vector(ndim*ndim*c.get_nx_tot(0),c.get_xm_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[1]);
MPI_Type_commit(&gridslicem[1]);
MPI_Type_vector(ndim*ndim*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xp_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[2]);
MPI_Type_commit(&gridslicep[2]);
MPI_Type_vector(ndim*ndim*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xm_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[2]);
MPI_Type_commit(&gridslicem[2]);
// exchange metric data
for (int i=0; i<ndim; i++) {
MPI_Sendrecv(&metric[shiftp_source_index[i]], 1, gridslicep[i], shiftp_dest[i], 2*i,
&metric[shiftp_dest_index[i]], 1, gridslicem[i], shiftp_source[i], 2*i, comm, &status);
MPI_Sendrecv(&metric[shiftm_source_index[i]], 1, gridslicem[i], shiftm_dest[i], 2*i+1,
&metric[shiftm_dest_index[i]], 1, gridslicep[i], shiftm_source[i], 2*i+1, comm, &status);
}
// free strided arrays
MPI_Type_free(&gridslicem[0]);
MPI_Type_free(&gridslicem[1]);
MPI_Type_free(&gridslicem[2]);
MPI_Type_free(&gridslicep[0]);
MPI_Type_free(&gridslicep[1]);
MPI_Type_free(&gridslicep[2]);
// set up strided arrays for sending jacobian data
MPI_Type_vector(1,c.get_xp_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicep[0]);
MPI_Type_commit(&gridslicep[0]);
MPI_Type_vector(1,c.get_xm_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicem[0]);
MPI_Type_commit(&gridslicem[0]);
MPI_Type_vector(c.get_nx_tot(0),c.get_xp_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[1]);
MPI_Type_commit(&gridslicep[1]);
MPI_Type_vector(c.get_nx_tot(0),c.get_xm_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[1]);
MPI_Type_commit(&gridslicem[1]);
MPI_Type_vector(c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xp_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[2]);
MPI_Type_commit(&gridslicep[2]);
MPI_Type_vector(c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xm_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[2]);
MPI_Type_commit(&gridslicem[2]);
// exchange jacobian data
for (int i=0; i<ndim; i++) {
MPI_Sendrecv(&jac[shiftp_source_index[i]], 1, gridslicep[i], shiftp_dest[i], 2*i,
&jac[shiftp_dest_index[i]], 1, gridslicem[i], shiftp_source[i], 2*i, comm, &status);
MPI_Sendrecv(&jac[shiftm_source_index[i]], 1, gridslicem[i], shiftm_dest[i], 2*i+1,
&jac[shiftm_dest_index[i]], 1, gridslicep[i], shiftm_source[i], 2*i+1, comm, &status);
}
// free strided arrays
MPI_Type_free(&gridslicem[0]);
MPI_Type_free(&gridslicem[1]);
MPI_Type_free(&gridslicem[2]);
MPI_Type_free(&gridslicep[0]);
MPI_Type_free(&gridslicep[1]);
MPI_Type_free(&gridslicep[2]);
}
void fields::free_exchange() {
// free MPI Types for ghost cell exchange
MPI_Type_free(&slicem[0]);
MPI_Type_free(&slicem[1]);
MPI_Type_free(&slicem[2]);
MPI_Type_free(&slicep[0]);
MPI_Type_free(&slicep[1]);
MPI_Type_free(&slicep[2]);
}
void fields::read_load(const string loadfile) {
// read heterogeneous load data from file
// allocate memory for stress
s = new double [ns*nxyz];
// allocate memory for array without ghost cells
double* s_temp;
s_temp = new double [ns*c.get_nx_loc(0)*c.get_nx_loc(1)*c.get_nx_loc(2)];
// create MPI subarray for reading distributed array
int starts[3], nx[3], nx_loc[3];
for (int i=0; i<3; i++) {
starts[i] = c.get_xm_loc(i);
nx[i] = c.get_nx(i);
nx_loc[i] = c.get_nx_loc(i);
}
MPI_Datatype filearray;
MPI_Type_create_subarray(3, nx, nx_loc, starts, MPI_ORDER_C, MPI_DOUBLE, &filearray);
MPI_Type_commit(&filearray);
// open file
int rc;
char* filename;
char filetype[] = "native";
filename = new char [loadfile.size()+1];
strcpy(filename, loadfile.c_str());
MPI_File infile;
rc = MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
delete[] filename;
if(rc != MPI_SUCCESS){
std::cerr << "Error opening stress file in fields.cpp\n";
MPI_Abort(MPI_COMM_WORLD, rc);
}
// set view to beginning
MPI_File_set_view(infile, (MPI_Offset)0, MPI_DOUBLE, filearray, filetype, MPI_INFO_NULL);
// read data
for (int i=0; i<ns; i++) {
MPI_File_read(infile, &s_temp[i*nx_loc[0]*nx_loc[1]*nx_loc[2]], nx_loc[0]*nx_loc[1]*nx_loc[2], MPI_DOUBLE, MPI_STATUS_IGNORE);
}
// copy to appropriate place in s array (avoid ghost cells)
for (int i=0; i<ns; i++) {
for (int j=0; j<nx_loc[0]; j++) {
for (int k=0; k<nx_loc[1]; k++) {
for (int l=0; l<nx_loc[2]; l++) {
s[i*nxyz+(j+c.get_xm_ghost(0))*c.get_nx_tot(1)*c.get_nx_tot(2)+(k+c.get_xm_ghost(1))*c.get_nx_tot(2)+l+c.get_xm_ghost(2)] = s_temp[i*nx_loc[0]*nx_loc[1]*nx_loc[2]+j*nx_loc[1]*nx_loc[2]+k*nx_loc[2]+l];
}
}
}
}
// close file
MPI_File_close(&infile);
MPI_Type_free(&filearray);
// deallocate temporary array
delete[] s_temp;
// exhange data with neighbors to fill in ghost cells
MPI_Status status;
MPI_Datatype gridslicep[3];
MPI_Datatype gridslicem[3];
// set up strided arrays for sending x data
MPI_Type_vector(ns,c.get_xp_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicep[0]);
MPI_Type_commit(&gridslicep[0]);
MPI_Type_vector(ns,c.get_xm_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicem[0]);
MPI_Type_commit(&gridslicem[0]);
MPI_Type_vector(ns*c.get_nx_tot(0),c.get_xp_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[1]);
MPI_Type_commit(&gridslicep[1]);
MPI_Type_vector(ns*c.get_nx_tot(0),c.get_xm_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[1]);
MPI_Type_commit(&gridslicem[1]);
MPI_Type_vector(ns*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xp_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[2]);
MPI_Type_commit(&gridslicep[2]);
MPI_Type_vector(ns*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xm_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[2]);
MPI_Type_commit(&gridslicem[2]);
// exchange stress data
for (int i=0; i<ndim; i++) {
MPI_Sendrecv(&s[shiftp_source_index[i]], 1, gridslicep[i], shiftp_dest[i], 2*i,
&s[shiftp_dest_index[i]], 1, gridslicem[i], shiftp_source[i], 2*i, comm, &status);
MPI_Sendrecv(&s[shiftm_source_index[i]], 1, gridslicem[i], shiftm_dest[i], 2*i+1,
&s[shiftm_dest_index[i]], 1, gridslicep[i], shiftm_source[i], 2*i+1, comm, &status);
}
// free strided arrays
MPI_Type_free(&gridslicem[0]);
MPI_Type_free(&gridslicem[1]);
MPI_Type_free(&gridslicem[2]);
MPI_Type_free(&gridslicep[0]);
MPI_Type_free(&gridslicep[1]);
MPI_Type_free(&gridslicep[2]);
}
void fields::read_mat(const string matfile) {
// read heterogeneous material data from file
// allocate memory for stress
mat = new double [nmat*nxyz];
// allocate memory for array without ghost cells
double* mat_temp;
mat_temp = new double [nmat*c.get_nx_loc(0)*c.get_nx_loc(1)*c.get_nx_loc(2)];
// create MPI subarray for reading distributed array
int starts[3], nx[3], nx_loc[3];
for (int i=0; i<3; i++) {
starts[i] = c.get_xm_loc(i);
nx[i] = c.get_nx(i);
nx_loc[i] = c.get_nx_loc(i);
}
MPI_Datatype filearray;
MPI_Type_create_subarray(3, nx, nx_loc, starts, MPI_ORDER_C, MPI_DOUBLE, &filearray);
MPI_Type_commit(&filearray);
// open file
int rc;
char* filename;
char filetype[] = "native";
filename = new char [matfile.size()+1];
strcpy(filename, matfile.c_str());
MPI_File infile;
rc = MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
delete[] filename;
if(rc != MPI_SUCCESS){
std::cerr << "Error opening material file in fields.cpp\n";
MPI_Abort(MPI_COMM_WORLD, rc);
}
// set view to beginning
MPI_File_set_view(infile, (MPI_Offset)0, MPI_DOUBLE, filearray, filetype, MPI_INFO_NULL);
// read data
for (int i=0; i<nmat; i++) {
MPI_File_read(infile, &mat_temp[i*nx_loc[0]*nx_loc[1]*nx_loc[2]], nx_loc[0]*nx_loc[1]*nx_loc[2], MPI_DOUBLE, MPI_STATUS_IGNORE);
}
// copy to appropriate place in array (avoid ghost cells)
for (int i=0; i<nmat; i++) {
for (int j=0; j<nx_loc[0]; j++) {
for (int k=0; k<nx_loc[1]; k++) {
for (int l=0; l<nx_loc[2]; l++) {
mat[i*nxyz+(j+c.get_xm_ghost(0))*c.get_nx_tot(1)*c.get_nx_tot(2)+(k+c.get_xm_ghost(1))*c.get_nx_tot(2)+l+c.get_xm_ghost(2)] = mat_temp[i*nx_loc[0]*nx_loc[1]*nx_loc[2]+j*nx_loc[1]*nx_loc[2]+k*nx_loc[2]+l];
assert(mat[i*nxyz+(j+c.get_xm_ghost(0))*c.get_nx_tot(1)*c.get_nx_tot(2)+(k+c.get_xm_ghost(1))*c.get_nx_tot(2)+l+c.get_xm_ghost(2)] > 0.); // check that material properties are positive
}
}
}
}
// close file
MPI_File_close(&infile);
MPI_Type_free(&filearray);
// deallocate temporary array
delete[] mat_temp;
// exhange data with neighbors to fill in ghost cells
MPI_Status status;
MPI_Datatype gridslicep[3];
MPI_Datatype gridslicem[3];
// set up strided arrays for sending x data
MPI_Type_vector(nmat,c.get_xp_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicep[0]);
MPI_Type_commit(&gridslicep[0]);
MPI_Type_vector(nmat,c.get_xm_ghost(0)*c.get_nx_tot(1)*c.get_nx_tot(2),c.get_nx_tot(0)*c.get_nx_tot(1)*c.get_nx_tot(2),
MPI_DOUBLE,&gridslicem[0]);
MPI_Type_commit(&gridslicem[0]);
MPI_Type_vector(nmat*c.get_nx_tot(0),c.get_xp_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[1]);
MPI_Type_commit(&gridslicep[1]);
MPI_Type_vector(nmat*c.get_nx_tot(0),c.get_xm_ghost(1)*c.get_nx_tot(2),c.get_nx_tot(1)*c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[1]);
MPI_Type_commit(&gridslicem[1]);
MPI_Type_vector(nmat*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xp_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicep[2]);
MPI_Type_commit(&gridslicep[2]);
MPI_Type_vector(nmat*c.get_nx_tot(0)*c.get_nx_tot(1),c.get_xm_ghost(2),c.get_nx_tot(2),MPI_DOUBLE,&gridslicem[2]);
MPI_Type_commit(&gridslicem[2]);
// exchange stress data
for (int i=0; i<ndim; i++) {
MPI_Sendrecv(&mat[shiftp_source_index[i]], 1, gridslicep[i], shiftp_dest[i], 2*i,
&mat[shiftp_dest_index[i]], 1, gridslicem[i], shiftp_source[i], 2*i, comm, &status);
MPI_Sendrecv(&mat[shiftm_source_index[i]], 1, gridslicem[i], shiftm_dest[i], 2*i+1,
&mat[shiftm_dest_index[i]], 1, gridslicep[i], shiftm_source[i], 2*i+1, comm, &status);
}
// free strided arrays
MPI_Type_free(&gridslicem[0]);
MPI_Type_free(&gridslicem[1]);
MPI_Type_free(&gridslicem[2]);
MPI_Type_free(&gridslicep[0]);
MPI_Type_free(&gridslicep[1]);
MPI_Type_free(&gridslicep[2]);
}
|
/*=========================================================================
Program: ParaView
Module: vtkSMProperty.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSMProperty.h"
#include "vtkClientServerStream.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkPVInstantiator.h"
#include "vtkPVXMLElement.h"
#include "vtkProcessModule.h"
#include "vtkSMDocumentation.h"
#include "vtkSMDomain.h"
#include "vtkSMDomainIterator.h"
#include "vtkSMMessage.h"
#include "vtkSMProperty.h"
#include "vtkSMPropertyLink.h"
#include "vtkSMProxy.h"
#include "vtkSmartPointer.h"
#include <sstream>
#include <vector>
#include "vtkSMPropertyInternals.h"
vtkStandardNewMacro(vtkSMProperty);
vtkCxxSetObjectMacro(vtkSMProperty, InformationProperty, vtkSMProperty);
vtkCxxSetObjectMacro(vtkSMProperty, Documentation, vtkSMDocumentation);
vtkCxxSetObjectMacro(vtkSMProperty, Hints, vtkPVXMLElement);
//---------------------------------------------------------------------------
vtkSMProperty::vtkSMProperty()
{
this->StateIgnored = false;
this->Command = 0;
this->ImmediateUpdate = 0;
this->Animateable = 2; // By default Animateable in advanced mode only.
this->PInternals = new vtkSMPropertyInternals;
this->XMLName = 0;
this->XMLLabel = 0;
this->PanelVisibility = 0;
this->PanelVisibilityDefaultForRepresentation = 0;
this->PanelWidget = 0;
this->DisableSubTrace = 0;
this->DomainIterator = vtkSMDomainIterator::New();
this->DomainIterator->SetProperty(this);
this->Proxy = 0;
this->InformationOnly = 0;
this->InformationProperty = 0;
this->IsInternal = 0;
this->NoCustomDefault = 0;
this->Documentation = 0;
this->Repeatable = 0;
this->IgnoreSynchronization = 0;
this->Links = NULL;
this->Hints = 0;
this->BlockModifiedEvents = false;
this->PendingModifiedEvents = false;
// by default, properties are set to show only in advanced mode
this->SetPanelVisibility("default");
this->Proxy = 0;
// Whenever the property fires UncheckedPropertyModifiedEvent, we update any
// dependent domains.
this->AddObserver(
vtkCommand::UncheckedPropertyModifiedEvent, this, &vtkSMProperty::UpdateDomains);
}
//---------------------------------------------------------------------------
vtkSMProperty::~vtkSMProperty()
{
this->RemoveFromSourceLink();
this->SetCommand(0);
delete this->PInternals;
this->SetXMLName(0);
this->SetXMLLabel(0);
this->DomainIterator->Delete();
this->SetInformationProperty(0);
this->SetDocumentation(0);
this->SetHints(0);
this->SetParent(0);
this->SetPanelVisibility(0);
this->SetPanelVisibilityDefaultForRepresentation(0);
this->SetPanelWidget(0);
this->SetDisableSubTrace(0);
if (this->Links)
{
this->Links->Delete();
this->Links = NULL;
}
}
//-----------------------------------------------------------------------------
// UnRegister is overloaded because the object has a reference to itself
// through the domain iterator.
void vtkSMProperty::UnRegister(vtkObjectBase* obj)
{
if (this->ReferenceCount == 2)
{
this->Superclass::UnRegister(obj);
vtkSMDomainIterator* tmp = this->DomainIterator;
tmp->Register(0);
tmp->SetProperty(0);
tmp->UnRegister(0);
return;
}
this->Superclass::UnRegister(obj);
}
//---------------------------------------------------------------------------
int vtkSMProperty::IsInDomains()
{
return this->IsInDomains(NULL);
}
//---------------------------------------------------------------------------
int vtkSMProperty::IsInDomains(vtkSMDomain** ptr)
{
this->DomainIterator->Begin();
while (!this->DomainIterator->IsAtEnd())
{
if (!this->DomainIterator->GetDomain()->IsInDomain(this))
{
if (ptr)
{
*ptr = this->DomainIterator->GetDomain();
}
return 0;
}
this->DomainIterator->Next();
}
return 1;
}
//---------------------------------------------------------------------------
void vtkSMProperty::AddDomain(const char* name, vtkSMDomain* domain)
{
// Check if the proxy already exists. If it does, we will
// replace it
vtkSMPropertyInternals::DomainMap::iterator it = this->PInternals->Domains.find(name);
if (it != this->PInternals->Domains.end())
{
vtkWarningMacro("Domain " << name << " already exists. Replacing");
it->second->SetProperty(NULL);
}
this->PInternals->Domains[name] = domain;
if (domain)
{
domain->SetProperty(this); // doesn't change reference count.
domain->AddObserver(
vtkCommand::DomainModifiedEvent, this, &vtkSMProperty::InvokeDomainModifiedEvent);
}
}
//---------------------------------------------------------------------------
void vtkSMProperty::AddLinkedProperty(vtkSMProperty* targetProperty)
{
if (!targetProperty)
{
return;
}
// This sets up the target property to take on the value of this property
// whenever it is updated.
if (!this->Links)
{
this->Links = vtkSMPropertyLink::New();
this->Links->AddLinkedProperty(this->GetParent(), this->GetXMLName(), vtkSMLink::INPUT);
}
this->Links->AddLinkedProperty(
targetProperty->GetParent(), targetProperty->GetXMLName(), vtkSMLink::OUTPUT);
targetProperty->PInternals->LinkSourceProperty = this;
}
//---------------------------------------------------------------------------
void vtkSMProperty::RemoveLinkedProperty(vtkSMProperty* targetProperty)
{
if (!targetProperty || !this->Links)
{
return;
}
this->Links->RemoveLinkedProperty(targetProperty->GetParent(), targetProperty->GetXMLName());
}
//---------------------------------------------------------------------------
void vtkSMProperty::RemoveFromSourceLink()
{
if (this->PInternals->LinkSourceProperty)
{
// Remove this instance as a subscriber to the source proxy
this->PInternals->LinkSourceProperty->RemoveLinkedProperty(this);
this->PInternals->LinkSourceProperty = NULL;
}
}
//---------------------------------------------------------------------------
void vtkSMProperty::InvokeDomainModifiedEvent()
{
this->InvokeEvent(vtkCommand::DomainModifiedEvent);
}
//---------------------------------------------------------------------------
vtkSMDomain* vtkSMProperty::GetDomain(const char* name)
{
vtkSMPropertyInternals::DomainMap::iterator it = this->PInternals->Domains.find(name);
if (it == this->PInternals->Domains.end())
{
return 0;
}
return it->second.GetPointer();
}
//---------------------------------------------------------------------------
vtkSMDomain* vtkSMProperty::FindDomain(const char* classname)
{
vtkSmartPointer<vtkSMDomainIterator> iter;
iter.TakeReference(this->NewDomainIterator());
for (iter->Begin(); !iter->IsAtEnd(); iter->Next())
{
if (iter->GetDomain()->IsA(classname))
{
return iter->GetDomain();
}
}
return 0;
}
//---------------------------------------------------------------------------
unsigned int vtkSMProperty::GetNumberOfDomains()
{
return static_cast<unsigned int>(this->PInternals->Domains.size());
}
//---------------------------------------------------------------------------
vtkSMDomainIterator* vtkSMProperty::NewDomainIterator()
{
vtkSMDomainIterator* iter = vtkSMDomainIterator::New();
iter->SetProperty(this);
return iter;
}
//---------------------------------------------------------------------------
void vtkSMProperty::AddDependent(vtkSMDomain* dom)
{
this->PInternals->Dependents.push_back(dom);
}
//---------------------------------------------------------------------------
void vtkSMProperty::RemoveAllDependents()
{
vtkSMPropertyInternals::DependentsVector::iterator iter = this->PInternals->Dependents.begin();
for (; iter != this->PInternals->Dependents.end(); iter++)
{
iter->GetPointer()->RemoveRequiredProperty(this);
}
this->PInternals->Dependents.erase(
this->PInternals->Dependents.begin(), this->PInternals->Dependents.end());
}
//---------------------------------------------------------------------------
void vtkSMProperty::UpdateDomains()
{
// I genuinely doubt when a property changes, its domain should change!!
//// Update own domains
// this->DomainIterator->Begin();
// while(!this->DomainIterator->IsAtEnd())
// {
// this->DomainIterator->GetDomain()->Update(0);
// this->DomainIterator->Next();
// }
// Update other dependent domains
vtkSMPropertyInternals::DependentsVector::iterator iter = this->PInternals->Dependents.begin();
for (; iter != this->PInternals->Dependents.end(); iter++)
{
iter->GetPointer()->Update(this);
}
}
//---------------------------------------------------------------------------
vtkSMProperty* vtkSMProperty::NewProperty(const char* name)
{
if (!this->Proxy)
{
return 0;
}
return this->Proxy->NewProperty(name);
}
//---------------------------------------------------------------------------
void vtkSMProperty::CreateAndSetPrettyLabel(const char* xmlname)
{
const char* label = vtkSMProperty::CreateNewPrettyLabel(xmlname);
this->SetXMLLabel(label);
delete[] label;
}
//---------------------------------------------------------------------------
const char* vtkSMProperty::CreateNewPrettyLabel(const char* xmlname)
{
// Add space before every capital letter not preceded by a capital letter
// or space hence:
// "MySpace" ==> "My Space"
// "MySPACE" ==> "My SPACE"
// "My Space" ==> "My Space"
int max = static_cast<int>(strlen(xmlname));
char* label = new char[2 * max + 10];
char* ptr = label;
bool previous_capital = false;
*ptr = xmlname[0];
ptr++;
for (int cc = 1; cc < max; ++cc)
{
if (xmlname[cc] >= 'A' && xmlname[cc] <= 'Z')
{
if (!previous_capital && *(ptr - 1) != ' ')
{
*ptr = ' ';
ptr++;
}
previous_capital = true;
}
else
{
previous_capital = false;
}
*ptr = xmlname[cc];
ptr++;
}
*ptr = 0;
return label;
}
//---------------------------------------------------------------------------
int vtkSMProperty::ReadXMLAttributes(vtkSMProxy* proxy, vtkPVXMLElement* element)
{
// TODO: some of the attributes are no longer necessary on the proxy-side,
// eg. "Command". We will remove those once we've verified that they are
// present on the PMProperty side.
const char* xmlname = element->GetAttribute("name");
if (xmlname)
{
this->SetXMLName(xmlname);
}
const char* xmllabel = element->GetAttribute("label");
if (xmllabel)
{
this->SetXMLLabel(xmllabel);
}
else
{
this->CreateAndSetPrettyLabel(xmlname);
}
const char* command = element->GetAttribute("command");
if (command)
{
this->SetCommand(command);
}
int repeatable;
int retVal = 1;
if (element->GetScalarAttribute("repeatable", &repeatable) ||
element->GetScalarAttribute("repeat_command", &repeatable))
{
this->Repeatable = repeatable;
}
const char* information_property = element->GetAttribute("information_property");
if (information_property)
{
this->SetInformationProperty(this->NewProperty(information_property));
}
int immediate_update;
retVal = element->GetScalarAttribute("immediate_update", &immediate_update);
if (retVal)
{
this->SetImmediateUpdate(immediate_update);
}
int state_ignored;
retVal = element->GetScalarAttribute("state_ignored", &state_ignored);
if (retVal)
{
this->SetStateIgnored(state_ignored != 0);
}
else
{
this->StateIgnoredOff(); // Default value
}
int information_only;
retVal = element->GetScalarAttribute("information_only", &information_only);
if (retVal)
{
this->SetInformationOnly(information_only);
}
int ignore_synch;
retVal = element->GetScalarAttribute("ignore_synchronization", &ignore_synch);
if (retVal)
{
this->SetIgnoreSynchronization(ignore_synch);
}
int animateable;
retVal = element->GetScalarAttribute("animateable", &animateable);
if (retVal)
{
this->SetAnimateable(animateable);
}
int is_internal;
if (element->GetScalarAttribute("is_internal", &is_internal))
{
this->SetIsInternal(is_internal);
}
int no_custom_default;
if (element->GetScalarAttribute("no_custom_default", &no_custom_default))
{
this->SetNoCustomDefault(no_custom_default);
}
const char* panel_visibility = element->GetAttribute("panel_visibility");
if (panel_visibility)
{
this->SetPanelVisibility(panel_visibility);
}
const char* panel_visibility_default_for_representation =
element->GetAttribute("panel_visibility_default_for_representation");
if (panel_visibility_default_for_representation)
{
this->SetPanelVisibilityDefaultForRepresentation(panel_visibility_default_for_representation);
}
const char* panel_widget = element->GetAttribute("panel_widget");
if (panel_widget)
{
this->SetPanelWidget(panel_widget);
}
const char* disable_sub_trace = element->GetAttribute("disable_sub_trace");
if (disable_sub_trace)
{
this->SetDisableSubTrace(disable_sub_trace);
}
// Manage deprecated XML definition
int deprecated_attr_value;
if (element->GetScalarAttribute("update_self", &deprecated_attr_value))
{
std::ostringstream proxyXML;
element->GetParent()->PrintXML(proxyXML, vtkIndent(1));
vtkWarningMacro(<< "Attribute update_self is not managed anymore."
<< "It is deprecated. " << endl
<< "Please FIX the decalaration of the following Proxy." << endl
<< proxyXML.str().c_str());
}
// Read and create domains.
for (unsigned int i = 0; i < element->GetNumberOfNestedElements(); ++i)
{
vtkPVXMLElement* domainEl = element->GetNestedElement(i);
// These are not domain elements.
if (strcmp(domainEl->GetName(), "Documentation") == 0)
{
vtkSMDocumentation* doc = vtkSMDocumentation::New();
doc->SetDocumentationElement(domainEl);
this->SetDocumentation(doc);
doc->Delete();
continue;
}
else if (strcmp(domainEl->GetName(), "Hints") == 0)
{
this->SetHints(domainEl);
continue;
}
else if (std::string(domainEl->GetName()).find("InformationHelper") != std::string::npos)
{
// InformationHelper are used to extract information from VTK object
// therefore they are not used on the proxy side (SM).
continue;
}
else if (std::string(domainEl->GetName()).find("StringArrayHelper") != std::string::npos)
{
// InformationHelper are used to extract information from VTK object
// therefore they are not used on the proxy side (SM).
continue;
}
// Everything else is assumed to be a domain element.
vtkObject* object = 0;
std::ostringstream name;
name << "vtkSM" << domainEl->GetName() << ends;
object = vtkPVInstantiator::CreateInstance(name.str().c_str());
if (object)
{
vtkSMDomain* domain = vtkSMDomain::SafeDownCast(object);
if (domain)
{
domain->SetSession(proxy->GetSession());
if (domain->ReadXMLAttributes(this, domainEl))
{
const char* dname = domainEl->GetAttribute("name");
if (dname)
{
domain->SetXMLName(dname);
this->AddDomain(dname, domain);
}
}
}
else
{
vtkErrorMacro(
"Object created (type: " << name.str().c_str() << ") is not of a recognized type.");
}
object->Delete();
}
else
{
vtkErrorMacro("Could not create object of type: " << name.str().c_str()
<< ". Did you specify wrong xml element?");
}
}
return 1;
}
//---------------------------------------------------------------------------
void vtkSMProperty::Copy(vtkSMProperty*)
{
}
//---------------------------------------------------------------------------
void vtkSMProperty::WriteTo(vtkSMMessage* msg)
{
ProxyState_Property* prop = msg->AddExtension(ProxyState::property);
prop->set_name(this->GetXMLName());
}
//---------------------------------------------------------------------------
bool vtkSMProperty::ResetToDomainDefaults(bool use_unchecked_values)
{
if (vtkProcessModule::GetProcessModule() &&
vtkProcessModule::GetProcessModule()->GetSymmetricMPIMode())
{
// when using symmetric mpi, we disable domains since they don't always have
// the most updated information.
return false;
}
this->DomainIterator->Begin();
while (!this->DomainIterator->IsAtEnd())
{
if (this->DomainIterator->GetDomain()->SetDefaultValues(this, use_unchecked_values))
{
return true;
}
this->DomainIterator->Next();
}
return false;
}
//---------------------------------------------------------------------------
void vtkSMProperty::ResetToDefault()
{
if (!this->ResetToDomainDefaults(false))
{
this->ResetToXMLDefaults();
}
}
//---------------------------------------------------------------------------
void vtkSMProperty::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Proxy: " << this->Proxy << endl;
os << indent << "Command: " << (this->Command ? this->Command : "(null)") << endl;
os << indent << "ImmediateUpdate:" << this->ImmediateUpdate << endl;
os << indent << "InformationOnly:" << this->InformationOnly << endl;
os << indent << "XMLName:" << (this->XMLName ? this->XMLName : "(null)") << endl;
os << indent << "XMLLabel: " << (this->XMLLabel ? this->XMLLabel : "(null)") << endl;
os << indent << "InformationProperty: " << this->InformationProperty << endl;
os << indent << "Animateable: " << this->Animateable << endl;
os << indent << "Internal: " << this->IsInternal << endl;
os << indent << "Repeatable: " << this->Repeatable << endl;
os << indent << "Documentation: " << this->Documentation << endl;
os << indent << "Hints: ";
if (this->Hints)
{
this->Hints->PrintSelf(os, indent);
}
else
{
os << "(none)" << endl;
}
if (this->Links)
{
os << indent << "Links: " << endl;
this->Links->PrintSelf(os, indent.GetNextIndent());
}
else
{
os << indent << "Links: none" << endl;
}
}
//---------------------------------------------------------------------------
void vtkSMProperty::SaveState(
vtkPVXMLElement* parent, const char* property_name, const char* uid, int saveDomains /*=1*/)
{
vtkPVXMLElement* propertyElement = vtkPVXMLElement::New();
propertyElement->SetName("Property");
propertyElement->AddAttribute("name", property_name);
propertyElement->AddAttribute("id", uid);
this->SaveStateValues(propertyElement);
if (saveDomains)
{
this->SaveDomainState(propertyElement, uid);
}
parent->AddNestedElement(propertyElement);
propertyElement->Delete();
}
//---------------------------------------------------------------------------
void vtkSMProperty::SaveStateValues(vtkPVXMLElement* /*propertyElement*/)
{
// Concreate class should override it !!!
}
//---------------------------------------------------------------------------
void vtkSMProperty::SaveDomainState(vtkPVXMLElement* propertyElement, const char* uid)
{
this->DomainIterator->Begin();
while (!this->DomainIterator->IsAtEnd())
{
std::ostringstream dname;
dname << uid << "." << this->DomainIterator->GetKey() << ends;
this->DomainIterator->GetDomain()->SaveState(propertyElement, dname.str().c_str());
this->DomainIterator->Next();
}
}
//---------------------------------------------------------------------------
int vtkSMProperty::LoadState(vtkPVXMLElement* propertyElement, vtkSMProxyLocator* loader)
{
// Process the domains.
unsigned int numElems = propertyElement->GetNumberOfNestedElements();
for (unsigned int cc = 0; cc < numElems; cc++)
{
vtkPVXMLElement* child = propertyElement->GetNestedElement(cc);
if (!child->GetName())
{
continue;
}
if (strcmp(child->GetName(), "Domain") == 0)
{
const char* name = child->GetAttribute("name");
vtkSMDomain* domain = name ? this->GetDomain(name) : 0;
if (domain)
{
domain->LoadState(child, loader);
}
}
}
return 1;
}
//---------------------------------------------------------------------------
void vtkSMProperty::SetParent(vtkSMProxy* proxy)
{
this->Proxy = proxy;
}
//---------------------------------------------------------------------------
vtkSMProxy* vtkSMProperty::GetParent()
{
return this->Proxy.GetPointer();
}
//---------------------------------------------------------------------------
bool vtkSMProperty::HasDomainsWithRequiredProperties()
{
for (vtkSMPropertyInternals::DomainMap::iterator iter = this->PInternals->Domains.begin();
iter != this->PInternals->Domains.end(); ++iter)
{
if (iter->second->GetNumberOfRequiredProperties() > 0)
{
return true;
}
}
return false;
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The Pivx developers
// Copyright (c) 2018 The Myce developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactiondesc.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "paymentserver.h"
#include "transactionrecord.h"
#include "base58.h"
#include "db.h"
#include "main.h"
#include "script/script.h"
#include "timedata.h"
#include "ui_interface.h"
#include "util.h"
#include "wallet.h"
#include <stdint.h>
#include <string>
using namespace std;
QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
if (!IsFinalTx(wtx, chainActive.Height() + 1)) {
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
return tr("Open for %n more block(s)", "", wtx.nLockTime - chainActive.Height());
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
} else {
int signatures = wtx.GetTransactionLockSignatures();
QString strUsingIX = "";
if (signatures >= 0) {
if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) {
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline (verified via SwiftX)").arg(nDepth);
else if (nDepth < 6)
return tr("%1/confirmed (verified via SwiftX)").arg(nDepth);
else
return tr("%1 confirmations (verified via SwiftX)").arg(nDepth);
} else {
if (!wtx.IsTransactionLockTimedOut()) {
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline (SwiftX verification in progress - %2 of %3 signatures)").arg(nDepth).arg(signatures).arg(SWIFTTX_SIGNATURES_TOTAL);
else if (nDepth < 6)
return tr("%1/confirmed (SwiftX verification in progress - %2 of %3 signatures )").arg(nDepth).arg(signatures).arg(SWIFTTX_SIGNATURES_TOTAL);
else
return tr("%1 confirmations (SwiftX verification in progress - %2 of %3 signatures)").arg(nDepth).arg(signatures).arg(SWIFTTX_SIGNATURES_TOTAL);
} else {
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline (SwiftX verification failed)").arg(nDepth);
else if (nDepth < 6)
return tr("%1/confirmed (SwiftX verification failed)").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
} else {
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted");
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth < 6)
return tr("%1/unconfirmed").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
}
QString TransactionDesc::toHTML(CWallet* wallet, CWalletTx& wtx, TransactionRecord* rec, int unit)
{
QString strHTML;
LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
CAmount nNet = rec->credit + rec->debit;
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1) {
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (rec->time ? GUIUtil::dateTimeStr(rec->time) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase()) {
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
} else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty()) {
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
} else {
// Offline transaction
if (nNet > 0) {
// Credit
if (CBitcoinAddress(rec->address).IsValid()) {
CTxDestination address = CBitcoinAddress(rec->address).Get();
if (wallet->mapAddressBook.count(address)) {
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only");
if (!wallet->mapAddressBook[address].name.empty())
strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")";
else
strHTML += " (" + addressOwned + ")";
strHTML += "<br>";
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty()) {
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = CBitcoinAddress(strAddress).Get();
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && rec->credit == 0) {
//
// Coinbase
//
CAmount nUnmatured = 0;
for (const CTxOut& txout : wtx.vout)
nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured) + " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
} else if (nNet > 0) {
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + "<br>";
} else {
isminetype fAllFromMe = ISMINE_SPENDABLE;
for (const CTxIn& txin : wtx.vin) {
isminetype mine = wallet->IsMine(txin);
if (fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
for (const CTxOut& txout : wtx.vout) {
isminetype mine = wallet->IsMine(txout);
if (fAllToMe > mine) fAllToMe = mine;
}
if (fAllFromMe) {
if (fAllFromMe == ISMINE_WATCH_ONLY)
strHTML += "<b>" + tr("From") + ":</b> " + tr("watch-only") + "<br>";
//
// Debit
//
for (const CTxOut& txout : wtx.vout) {
// Ignore change
isminetype toSelf = wallet->IsMine(txout);
if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))
continue;
if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty()) {
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address)) {
strHTML += "<b>" + tr("To") + ":</b> ";
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
if (toSelf == ISMINE_SPENDABLE)
strHTML += " (own address)";
else if (toSelf == ISMINE_WATCH_ONLY)
strHTML += " (watch-only)";
strHTML += "<br>";
}
}
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + "<br>";
if (toSelf)
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + "<br>";
}
if (fAllToMe) {
// Payment to self
CAmount nChange = wtx.GetChange();
CAmount nValue = rec->credit - nChange;
strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>";
strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>";
}
CAmount nTxFee = rec->debit - wtx.GetValueOut();
if (nTxFee > 0)
strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + "<br>";
} else {
//
// Mixed debit transaction
//
for (const CTxIn& txin : wtx.vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
for (const CTxOut& txout : wtx.vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
}
}
strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxID() + "<br>";
strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>";
// Message from normal myce:URI (myce:XyZ...?message=example)
foreach (const PAIRTYPE(string, string) & r, wtx.vOrderForm)
if (r.first == "Message")
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>";
//
// PaymentRequest info:
//
foreach (const PAIRTYPE(string, string) & r, wtx.vOrderForm) {
if (r.first == "PaymentRequest") {
PaymentRequestPlus req;
req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));
QString merchant;
if (req.getMerchant(PaymentServer::getCertStore(), merchant))
strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>";
}
}
if (wtx.IsCoinBase()) {
quint32 numBlocksToMaturity = Params().COINBASE_MATURITY() + 1;
strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>";
}
//
// Debug view
//
if (fDebug) {
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
for (const CTxIn& txin : wtx.vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
for (const CTxOut& txout : wtx.vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
for (const CTxIn& txin : wtx.vin) {
COutPoint prevout = txin.prevout;
CCoins prev;
if (pcoinsTip->GetCoins(prevout.hash, prev)) {
if (prevout.n < prev.vout.size()) {
strHTML += "<li>";
const CTxOut& vout = prev.vout[prevout.n];
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address)) {
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += QString::fromStdString(CBitcoinAddress(address).ToString());
}
strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue);
strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false"));
strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>";
}
}
}
strHTML += "</ul>";
}
strHTML += "</font></html>";
return strHTML;
}
|
#include <stdexcept>
#include "LoadSaveVehicleType.h"
#include "SaveLoadGame.h"
#include "Soldier_Find.h"
#include "Vehicles.h"
#include "Strategic_Pathing.h"
#include "Assignments.h"
#include "Strategic_Movement.h"
#include "Squads.h"
#include "Map_Screen_Helicopter.h"
#include "Game_Clock.h"
#include "Overhead.h"
#include "Soldier_Profile.h"
#include "Sound_Control.h"
#include "SoundMan.h"
#include "Soldier_Add.h"
#include "Strategic.h"
#include "WorldDef.h"
#include "Tile_Animation.h"
#include "Isometric_Utils.h"
#include "Interface.h"
#include "Random.h"
#include "Text.h"
#include "Explosion_Control.h"
#include "Soldier_Create.h"
#include "StrategicMap.h"
#include "Campaign_Types.h"
#include "Sys_Globals.h"
#include "Map_Screen_Interface.h"
#include "JAScreens.h"
#include "Quests.h"
#include "Tactical_Save.h"
#include "Soldier_Macros.h"
#include "OppList.h"
#include "Soldier_Ani.h"
#include "MemMan.h"
#include "Debug.h"
#include "ScreenIDs.h"
#include "FileMan.h"
#include "ContentManager.h"
#include "GameInstance.h"
INT8 gubVehicleMovementGroups[ MAX_VEHICLES ];
// the list of vehicles
VEHICLETYPE *pVehicleList = NULL;
// number of vehicle slots on the list
UINT8 ubNumberOfVehicles = 0;
//ATE: These arrays below should all be in a large LUT which contains
// static info for each vehicle....
struct VehicleTypeInfo
{
SoundID enter_sound;
SoundID move_sound;
ProfileID profile;
UINT8 movement_type;
UINT16 armour_type;
UINT8 seats;
};
static const VehicleTypeInfo g_vehicle_type_info[] =
{
{ S_VECH1_INTO, S_VECH1_MOVE, PROF_ELDERODO, CAR, KEVLAR_VEST, 6 }, // Eldorado
{ S_VECH1_INTO, S_VECH1_MOVE, PROF_HUMMER, CAR, SPECTRA_VEST, 6 }, // Hummer
{ S_VECH1_INTO, S_VECH1_MOVE, PROF_ICECREAM, CAR, KEVLAR_VEST, 6 }, // Ice cream truck
{ S_VECH1_INTO, S_VECH1_MOVE, NPC164, CAR, KEVLAR_VEST, 6 }, // Jeep
{ S_VECH1_INTO, S_VECH1_MOVE, NPC164, CAR, SPECTRA_VEST, 6 }, // Tank
{ S_VECH1_INTO, S_VECH1_MOVE, PROF_HELICOPTER, AIR, KEVLAR_VEST, 6 } // Helicopter
};
// Loop through and create a few soldier squad ID's for vehicles ( max # 3 )
void InitVehicles(void)
{
INT32 cnt;
for( cnt = 0; cnt < MAX_VEHICLES; cnt++ )
{
// create mvt groups
GROUP* const g = CreateNewVehicleGroupDepartingFromSector(1, 1);
g->fPersistant = TRUE;
gubVehicleMovementGroups[cnt] = g->ubGroupID;
}
}
void SetVehicleValuesIntoSoldierType(SOLDIERTYPE* const vs)
{
const VEHICLETYPE* const v = &pVehicleList[vs->bVehicleID];
wcscpy(vs->name, zVehicleName[v->ubVehicleType]);
vs->ubProfile = g_vehicle_type_info[v->ubVehicleType].profile;
vs->sBreathRed = 10000; // Init fuel
vs->bBreath = 100;
vs->ubWhatKindOfMercAmI = MERC_TYPE__VEHICLE;
}
INT32 AddVehicleToList(const INT16 sMapX, const INT16 sMapY, const INT16 sGridNo, const UINT8 ubType)
{
INT32 vid;
for (vid = 0;; ++vid)
{
if (vid == ubNumberOfVehicles)
{
pVehicleList = REALLOC(pVehicleList, VEHICLETYPE, ++ubNumberOfVehicles);
break;
}
if (!pVehicleList[vid].fValid) break;
}
VEHICLETYPE* const v = &pVehicleList[vid];
// found a slot
*v = VEHICLETYPE{};
v->ubMovementGroup = 0;
v->sSectorX = sMapX;
v->sSectorY = sMapY;
v->sSectorZ = 0;
v->sGridNo = sGridNo;
v->fValid = TRUE;
v->ubVehicleType = ubType;
v->pMercPath = NULL;
v->fDestroyed = FALSE;
v->ubMovementGroup = gubVehicleMovementGroups[vid];
// ATE: Add movement mask to group...
GROUP* const g = GetGroup(v->ubMovementGroup);
// This is okay, no groups exist, so simply return.
if (!g && gfEditMode) return vid;
Assert(g);
// ARM: setup group movement defaults
g->ubTransportationMask = g_vehicle_type_info[ubType].movement_type;
g->ubSectorX = sMapX;
g->ubNextX = sMapX;
g->ubSectorY = sMapY;
g->ubNextY = sMapY;
g->uiTraverseTime = 0;
g->uiArrivalTime = 0;
return vid;
}
void RemoveVehicleFromList(VEHICLETYPE& v)
{
v.pMercPath = ClearStrategicPathList(v.pMercPath, 0);
v = VEHICLETYPE{};
}
void ClearOutVehicleList(void)
{
if (pVehicleList == NULL) return;
FOR_EACH_VEHICLE(v)
{
v->pMercPath = ClearStrategicPathList(v->pMercPath, 0);
}
MemFree(pVehicleList);
pVehicleList = NULL;
ubNumberOfVehicles = 0;
}
bool IsThisVehicleAccessibleToSoldier(SOLDIERTYPE const& s, VEHICLETYPE const& v)
{
return !s.fBetweenSectors &&
!v.fBetweenSectors &&
s.sSectorX == v.sSectorX &&
s.sSectorY == v.sSectorY &&
s.bSectorZ == v.sSectorZ &&
OKUseVehicle(g_vehicle_type_info[v.ubVehicleType].profile);
}
static bool AddSoldierToVehicle(SOLDIERTYPE& s, VEHICLETYPE& v)
{
// ok now check if any free slots in the vehicle
SOLDIERTYPE* vs = 0;
if (!IsHelicopter(v))
{
vs = &GetSoldierStructureForVehicle(v);
if (vs->bTeam != OUR_TEAM)
{
// Change sides
vs = ChangeSoldierTeam(vs, OUR_TEAM);
// add it to mapscreen list
fReBuildCharacterList = TRUE;
}
// If vehicle is empty, add to unique squad now that it has somebody in it!
if (GetNumberInVehicle(v) == 0)
{
// 2 ) Add to unique squad...
AddCharacterToUniqueSquad(vs);
// ATE: OK funcky stuff here!
// We have now a guy on a squad group, remove him!
RemovePlayerFromGroup(*vs);
// I really have vehicles.
// ONLY add to vehicle group once!
GROUP& g = *GetGroup(v.ubMovementGroup);
if (!DoesPlayerExistInPGroup(g, *vs))
{
//NOW.. add guy to vehicle group....
AddPlayerToGroup(g, *vs);
}
else
{
vs->ubGroupID = v.ubMovementGroup;
}
}
}
// check if the grunt is already here
CFOR_EACH_PASSENGER(v, i)
{
if (*i == &s) return true; // guy found, no need to add
}
if (vs)
{
// can't call SelectSoldier in mapscreen, that will initialize interface panels!!!
if (guiCurrentScreen == GAME_SCREEN)
{
SelectSoldier(vs, SELSOLDIER_FORCE_RESELECT);
}
PlayLocationJA2Sample(vs->sGridNo, g_vehicle_type_info[v.ubVehicleType].enter_sound, HIGHVOLUME, 1);
}
INT32 const seats = GetVehicleSeats(v);
for (INT32 i = 0; i < seats; ++i)
{
if (v.pPassengers[i]) continue;
v.pPassengers[i] = &s;
if (s.bAssignment == VEHICLE)
{
TakeSoldierOutOfVehicle(&s);
// NOTE: This will leave the soldier on a squad. Must be done PRIOR TO
// and in AS WELL AS the call to RemoveCharacterFromSquads() that's coming
// up, to permit direct vehicle->vehicle reassignment!
}
// if in a squad, remove from squad, if not, then check if in mvt group, if
// so, move and destroy group
if (s.bAssignment < ON_DUTY)
{
RemoveCharacterFromSquads(&s);
}
else if (s.ubGroupID != 0)
{
// destroy group and set to zero
RemoveGroup(*GetGroup(s.ubGroupID));
s.ubGroupID = 0;
}
if (s.bAssignment != VEHICLE || s.iVehicleId != VEHICLE2ID(v))
{
SetTimeOfAssignmentChangeForMerc(&s);
}
ChangeSoldiersAssignment(&s, VEHICLE);
s.iVehicleId = VEHICLE2ID(v);
// if vehicle is part of mvt group, then add character to mvt group
if (v.ubMovementGroup != 0)
{
AddPlayerToGroup(*GetGroup(v.ubMovementGroup), s);
}
// Are we the first?
s.uiStatusFlags |= GetNumberInVehicle(v) == 1 ?
SOLDIER_DRIVER : SOLDIER_PASSENGER;
RemoveSoldierFromGridNo(s);
if (vs)
{
// Set gridno for vehicle.....
EVENT_SetSoldierPositionXY(&s, vs->dXPos, vs->dYPos, SSP_NONE);
// Stop from any movement.....
EVENT_StopMerc(&s);
// can't call SetCurrentSquad OR SelectSoldier in mapscreen,
// that will initialize interface panels!!!
if (guiCurrentScreen == GAME_SCREEN)
{
SetCurrentSquad(vs->bAssignment, TRUE);
}
}
return true;
}
// no slots, leave
return false;
}
void SetSoldierExitHelicopterInsertionData(SOLDIERTYPE* const s)
{
if (s->bInSector) return;
if (s->sSectorX == BOBBYR_SHIPPING_DEST_SECTOR_X &&
s->sSectorY == BOBBYR_SHIPPING_DEST_SECTOR_Y &&
s->bSectorZ == BOBBYR_SHIPPING_DEST_SECTOR_Z)
{
// This is Drassen, make insertion gridno specific
s->ubStrategicInsertionCode = INSERTION_CODE_GRIDNO;
s->usStrategicInsertionData = 10125;
}
else
{
// Not anything different here - just use center gridno
s->ubStrategicInsertionCode = INSERTION_CODE_CENTER;
}
}
static void TeleportVehicleToItsClosestSector(UINT8 ubGroupID);
// remove soldier from vehicle
static bool RemoveSoldierFromVehicle(SOLDIERTYPE& s)
{
VEHICLETYPE& v = GetVehicle(s.iVehicleId);
// now look for the grunt
INT32 const seats = GetVehicleSeats(v);
for (INT32 i = 0;; ++i)
{
if (i == seats) return false;
if (v.pPassengers[i] != &s) continue;
v.pPassengers[i] = 0;
break;
}
RemovePlayerFromGroup(s);
s.ubGroupID = 0;
s.sSectorY = v.sSectorY;
s.sSectorX = v.sSectorX;
s.bSectorZ = v.sSectorZ;
s.uiStatusFlags &= ~(SOLDIER_DRIVER | SOLDIER_PASSENGER);
if (IsHelicopter(v))
{
// The vehicle the helicopter? It can continue moving when no soldiers
// aboard (Skyrider remains)
if (s.bLife >= OKLIFE)
{
// Mark the sector as visited (flying around in the chopper doesn't, so
// this does it as soon as we get off it)
SetSectorFlag(s.sSectorX, s.sSectorY, s.bSectorZ, SF_ALREADY_VISITED);
}
SetSoldierExitHelicopterInsertionData(&s);
// Update in sector if this is the current sector
if (s.sSectorX == gWorldSectorX &&
s.sSectorY == gWorldSectorY &&
s.bSectorZ == gbWorldSectorZ)
{
UpdateMercInSector(s, gWorldSectorX, gWorldSectorY, gbWorldSectorZ);
}
}
else
{
// check if anyone left in vehicle
CFOR_EACH_PASSENGER(v, i) return true;
SOLDIERTYPE& vs = GetSoldierStructureForVehicle(v);
// and he has a route set
if (GetLengthOfMercPath(&vs) > 0)
{
// cancel the entire path (also handles reversing directions)
CancelPathForVehicle(v, FALSE);
}
if (v.fBetweenSectors)
{
// The vehicle was abandoned between sectors. Teleport it to the closer of
// its current and next sectors (it beats having it arrive empty later)
TeleportVehicleToItsClosestSector(vs.ubGroupID);
}
// Remove vehicle from squad
RemoveCharacterFromSquads(&vs);
// ATE: Add him back to vehicle group!
GROUP& g = *GetGroup(v.ubMovementGroup);
if (!DoesPlayerExistInPGroup(g, vs)) AddPlayerToGroup(g, vs);
ChangeSoldiersAssignment(&vs, ASSIGNMENT_EMPTY);
}
return true;
}
BOOLEAN MoveCharactersPathToVehicle(SOLDIERTYPE* const s)
{
if (!s) return FALSE;
// check if character is in fact in a vehicle
INT32 vid;
if (s->uiStatusFlags & SOLDIER_VEHICLE)
{
vid = s->bVehicleID;
}
else if (s->bAssignment == VEHICLE)
{
vid = s->iVehicleId;
}
else
{
s->pMercPath = ClearStrategicPathList(s->pMercPath, 0);
return FALSE;
}
VEHICLETYPE& v = GetVehicle(vid);
ClearStrategicPathList(v.pMercPath, v.ubMovementGroup);
v.pMercPath = CopyPaths(s->pMercPath);
s->pMercPath = ClearStrategicPathList(s->pMercPath, 0);
return TRUE;
}
void SetUpMvtGroupForVehicle(SOLDIERTYPE* const s)
{
INT32 vid;
// Check if character is in fact in a vehicle
if (s->uiStatusFlags & SOLDIER_VEHICLE) vid = s->bVehicleID;
else if (s->bAssignment == VEHICLE) vid = s->iVehicleId;
else return;
VEHICLETYPE& v = GetVehicle(vid);
ClearStrategicPathList(s->pMercPath, s->ubGroupID);
s->pMercPath = CopyPaths(v.pMercPath);
s->ubGroupID = v.ubMovementGroup;
}
VEHICLETYPE& GetVehicle(INT32 const vehicle_id)
{
if (0 <= vehicle_id && vehicle_id < ubNumberOfVehicles)
{
VEHICLETYPE& v = pVehicleList[vehicle_id];
if (v.fValid) return v;
}
throw std::logic_error("Invalid vehicle ID");
}
VEHICLETYPE& GetVehicleFromMvtGroup(GROUP const& g)
{
// given the id of a mvt group, find a vehicle in this group
FOR_EACH_VEHICLE(i)
{
VEHICLETYPE& v = *i;
if (v.ubMovementGroup == g.ubGroupID) return v;
}
throw std::logic_error("Group does not contain a vehicle");
}
// Kill this person in the vehicle
static bool KillPersonInVehicle(SOLDIERTYPE& s)
{
if (s.bLife == 0) return false; // Guy is dead, leave
// Otherwise hurt him
SoldierTakeDamage(&s, 100, 100, TAKE_DAMAGE_BLOODLOSS, 0);
return true;
}
BOOLEAN KillAllInVehicle(VEHICLETYPE const& v)
{
// go through list of occupants and kill them
CFOR_EACH_PASSENGER(v, i)
{
if (!KillPersonInVehicle(**i)) return FALSE;
}
return TRUE;
}
INT32 GetNumberInVehicle(VEHICLETYPE const& v)
{
// go through list of occupants in vehicles and count them
INT32 count = 0;
CFOR_EACH_PASSENGER(v, i) ++count;
return count;
}
INT32 GetNumberOfNonEPCsInVehicle( INT32 iId )
{
// go through list of occupants in vehicles and count them
VEHICLETYPE const& v = GetVehicle(iId);
INT32 count = 0;
CFOR_EACH_PASSENGER(v, i)
{
const SOLDIERTYPE* const s = *i;
if (!AM_AN_EPC(s)) ++count;
}
return count;
}
BOOLEAN IsRobotControllerInVehicle( INT32 iId )
{
VEHICLETYPE const& v = GetVehicle(iId);
CFOR_EACH_PASSENGER(v, i)
{
if (ControllingRobot(*i)) return TRUE;
}
return FALSE;
}
bool AnyAccessibleVehiclesInSoldiersSector(SOLDIERTYPE const& s)
{
CFOR_EACH_VEHICLE(v)
{
if (IsThisVehicleAccessibleToSoldier(s, *v)) return true;
}
return false;
}
bool IsEnoughSpaceInVehicle(VEHICLETYPE const& v)
{
return GetNumberInVehicle(v) != GetVehicleSeats(v);
}
BOOLEAN TakeSoldierOutOfVehicle(SOLDIERTYPE* const s)
{
// if not in vehicle, don't take out, not much point, now is there?
if (s->bAssignment != VEHICLE) return FALSE;
if (s->sSectorX == gWorldSectorX &&
s->sSectorY == gWorldSectorY &&
s->bSectorZ == 0 &&
s->bInSector &&
!InHelicopter(*s)) // helicopter isn't a soldiertype instance
{
return ExitVehicle(s);
}
else
{
return RemoveSoldierFromVehicle(*s);
}
}
bool PutSoldierInVehicle(SOLDIERTYPE& s, VEHICLETYPE& v)
{
if (!AddSoldierToVehicle(s, v)) return false;
if (s.sSectorX == gWorldSectorX &&
s.sSectorY == gWorldSectorY &&
s.bSectorZ == 0 &&
!IsHelicopter(v) &&
guiCurrentScreen == GAME_SCREEN)
{
SetCurrentInterfacePanel(TEAM_PANEL);
}
return true;
}
BOOLEAN ExitVehicle(SOLDIERTYPE* const s)
{
SOLDIERTYPE& vs = GetSoldierStructureForVehicle(GetVehicle(s->iVehicleId));
INT16 sGridNo = FindGridNoFromSweetSpotWithStructDataFromSoldier(s, s->usUIMovementMode, 5, 3, &vs);
if (sGridNo == NOWHERE)
{
// ATE: BUT we need a place, widen the search
sGridNo = FindGridNoFromSweetSpotWithStructDataFromSoldier(s, s->usUIMovementMode, 20, 3, &vs);
}
RemoveSoldierFromVehicle(*s);
s->sInsertionGridNo = sGridNo;
s->ubStrategicInsertionCode = INSERTION_CODE_GRIDNO;
s->usStrategicInsertionData = s->sInsertionGridNo;
s->iVehicleId = -1;
//AllTeamsLookForAll( FALSE );
s->bOppList[vs.ubID] = 1;
// Add to sector....
EVENT_SetSoldierPosition(s, sGridNo, SSP_NONE);
// Update visiblity.....
HandleSight(*s, SIGHT_LOOK | SIGHT_RADIO);
AddCharacterToUniqueSquad(s);
// can't call SetCurrentSquad OR SelectSoldier in mapscreen, that will initialize interface panels!!!
if (guiCurrentScreen == GAME_SCREEN)
{
SetCurrentSquad(s->bAssignment, TRUE);
SelectSoldier(s, SELSOLDIER_FORCE_RESELECT);
}
PlayLocationJA2Sample(vs.sGridNo, g_vehicle_type_info[pVehicleList[vs.bVehicleID].ubVehicleType].enter_sound, HIGHVOLUME, 1);
return TRUE;
}
static void HandleCriticalHitForVehicleInLocation(UINT8 ubID, INT16 sDmg, INT16 sGridNo, SOLDIERTYPE* att);
void VehicleTakeDamage(const UINT8 ubID, const UINT8 ubReason, const INT16 sDamage, const INT16 sGridNo, SOLDIERTYPE* const att)
{
if ( ubReason != TAKE_DAMAGE_GAS )
{
PlayLocationJA2Sample(sGridNo, S_METAL_IMPACT3, MIDVOLUME, 1);
}
// check if there was in fact damage done to the vehicle
if( ( ubReason == TAKE_DAMAGE_HANDTOHAND ) || ( ubReason == TAKE_DAMAGE_GAS ) )
{
// nope
return;
}
if (!pVehicleList[ubID].fDestroyed)
{
switch( ubReason )
{
case( TAKE_DAMAGE_GUNFIRE ):
case( TAKE_DAMAGE_EXPLOSION):
case( TAKE_DAMAGE_STRUCTURE_EXPLOSION):
HandleCriticalHitForVehicleInLocation(ubID, sDamage, sGridNo, att);
break;
}
}
}
// handle crit hit to vehicle in this location
static void HandleCriticalHitForVehicleInLocation(const UINT8 ubID, const INT16 sDmg, const INT16 sGridNo, SOLDIERTYPE* const att)
{
// check state the armor was s'posed to be in vs. the current state..the difference / orig state is % chance
// that a critical hit will occur
BOOLEAN fMadeCorpse = FALSE;
VEHICLETYPE& v = pVehicleList[ubID];
SOLDIERTYPE& vs = GetSoldierStructureForVehicle(v);
if (sDmg > vs.bLife)
{
vs.bLife = 0;
}
else
{
// Decrease Health
vs.bLife -= sDmg;
}
if (vs.bLife < OKLIFE) vs.bLife = 0;
//Show damage
vs.sDamage += sDmg;
if (vs.bInSector && vs.bVisible != -1)
{
// If we are already dead, don't show damage!
if ( sDmg != 0 )
{
// Display damage
// Set Damage display counter
vs.fDisplayDamage = TRUE;
vs.bDisplayDamageCount = 0;
vs.sDamageX = vs.sBoundingBoxOffsetX;
vs.sDamageY = vs.sBoundingBoxOffsetY;
}
}
if (vs.bLife == 0 && !v.fDestroyed)
{
v.fDestroyed = TRUE;
// Explode vehicle...
IgniteExplosion(att, 0, sGridNo, GREAT_BIG_EXPLOSION, 0);
CheckForAndHandleSoldierDeath(&vs, &fMadeCorpse);
KillAllInVehicle(v);
}
}
bool DoesVehicleNeedAnyRepairs(VEHICLETYPE const& v)
{
// Skyrider isn't damagable/repairable
if (IsHelicopter(v)) return false;
// get the vehicle soldiertype
SOLDIERTYPE const& vs = GetSoldierStructureForVehicle(v);
return vs.bLife != vs.bLifeMax;
}
INT8 RepairVehicle(VEHICLETYPE const& v, INT8 const bRepairPtsLeft, BOOLEAN* const pfNothingToRepair)
{
INT8 bRepairPtsUsed = 0;
INT8 bOldLife;
if (!DoesVehicleNeedAnyRepairs(v)) return bRepairPtsUsed;
// get the vehicle soldiertype
SOLDIERTYPE& vs = GetSoldierStructureForVehicle(v);
bOldLife = vs.bLife;
// Repair
vs.bLife += bRepairPtsLeft / VEHICLE_REPAIR_POINTS_DIVISOR;
// Check
if (vs.bLife > vs.bLifeMax) vs.bLife = vs.bLifeMax;
// Calculate pts used;
bRepairPtsUsed = (vs.bLife - bOldLife) * VEHICLE_REPAIR_POINTS_DIVISOR;
// ARM: personally, I'd love to know where in Arulco the mechanic gets the PARTS to do this stuff, but hey, it's a game!
*pfNothingToRepair = !DoesVehicleNeedAnyRepairs(v);
return( bRepairPtsUsed );
}
SOLDIERTYPE& GetSoldierStructureForVehicle(VEHICLETYPE const& v)
{
FOR_EACH_SOLDIER(s)
{
if (!(s->uiStatusFlags & SOLDIER_VEHICLE)) continue;
if (s->bVehicleID != VEHICLE2ID(v)) continue;
return *s;
}
throw std::logic_error("Vehicle has no corresponding soldier");
}
void SaveVehicleInformationToSaveGameFile(HWFILE const f)
{
//Save the number of elements
FileWrite(f, &ubNumberOfVehicles, sizeof(UINT8));
//loop through all the vehicles and save each one
for (UINT8 i = 0; i < ubNumberOfVehicles; ++i)
{
const VEHICLETYPE* const v = &pVehicleList[i];
//save if the vehicle spot is valid
FileWrite(f, &v->fValid, sizeof(BOOLEAN));
if (!v->fValid) continue;
InjectVehicleTypeIntoFile(f, v);
SaveMercPath(f, v->pMercPath);
}
}
void LoadVehicleInformationFromSavedGameFile(HWFILE const hFile, UINT32 const uiSavedGameVersion)
{
ClearOutVehicleList();
//Load the number of elements
FileRead(hFile, &ubNumberOfVehicles, sizeof(UINT8));
if (ubNumberOfVehicles == 0) return;
//allocate memory to hold the vehicle list
VEHICLETYPE* const vl = MALLOCNZ(VEHICLETYPE, ubNumberOfVehicles);
pVehicleList = vl;
//loop through all the vehicles and load each one
for (UINT8 cnt = 0; cnt < ubNumberOfVehicles; ++cnt)
{
VEHICLETYPE* const v = &vl[cnt];
//Load if the vehicle spot is valid
FileRead(hFile, &v->fValid, sizeof(BOOLEAN));
if (!v->fValid) continue;
ExtractVehicleTypeFromFile(hFile, v, uiSavedGameVersion);
LoadMercPath(hFile, &v->pMercPath);
}
}
void SetVehicleSectorValues(VEHICLETYPE& v, UINT8 const x, UINT8 const y)
{
v.sSectorX = x;
v.sSectorY = y;
MERCPROFILESTRUCT& p = GetProfile(g_vehicle_type_info[v.ubVehicleType].profile);
p.sSectorX = x;
p.sSectorY = y;
// Go through list of mercs in vehicle and set all their states as arrived
CFOR_EACH_PASSENGER(v, i)
{
SOLDIERTYPE& s = **i;
s.sSectorX = x;
s.sSectorY = y;
s.fBetweenSectors = FALSE;
}
}
void UpdateAllVehiclePassengersGridNo(SOLDIERTYPE* const vs)
{
// If not a vehicle, ignore!
if (!(vs->uiStatusFlags & SOLDIER_VEHICLE)) return;
VEHICLETYPE const& v = pVehicleList[vs->bVehicleID];
// Loop through passengers and update each guy's position
CFOR_EACH_PASSENGER(v, i)
{
EVENT_SetSoldierPositionXY(*i, vs->dXPos, vs->dYPos, SSP_NONE);
}
}
void LoadVehicleMovementInfoFromSavedGameFile(HWFILE const hFile)
{
INT32 cnt;
//Load in the Squad movement id's
FileRead(hFile, gubVehicleMovementGroups, sizeof(INT8) * 5);
for( cnt = 5; cnt < MAX_VEHICLES; cnt++ )
{
// create mvt groups
GROUP* const g = CreateNewVehicleGroupDepartingFromSector(1, 1);
g->fPersistant = TRUE;
gubVehicleMovementGroups[cnt] = g->ubGroupID;
}
}
void NewSaveVehicleMovementInfoToSavedGameFile(HWFILE const hFile)
{
//Save all the vehicle movement id's
FileWrite(hFile, gubVehicleMovementGroups, sizeof(INT8) * MAX_VEHICLES);
}
void NewLoadVehicleMovementInfoFromSavedGameFile(HWFILE const hFile)
{
//Load in the Squad movement id's
FileRead(hFile, gubVehicleMovementGroups, sizeof(INT8) * MAX_VEHICLES);
}
BOOLEAN OKUseVehicle( UINT8 ubProfile )
{
if ( ubProfile == PROF_HUMMER )
{
return( CheckFact( FACT_OK_USE_HUMMER, NO_PROFILE ) );
}
else if ( ubProfile == PROF_ICECREAM )
{
return( CheckFact( FACT_OK_USE_ICECREAM, NO_PROFILE ) );
}
else if ( ubProfile == PROF_HELICOPTER )
{
// don't allow mercs to get inside vehicle if it's grounded (enemy controlled, Skyrider owed money, etc.)
return( CanHelicopterFly() );
}
else
{
return( TRUE );
}
}
static void TeleportVehicleToItsClosestSector(const UINT8 ubGroupID)
{
GROUP *pGroup = NULL;
UINT32 uiTimeToNextSector;
UINT32 uiTimeToLastSector;
INT16 sPrevX, sPrevY, sNextX, sNextY;
pGroup = GetGroup( ubGroupID );
Assert( pGroup );
Assert( pGroup->uiTraverseTime != -1 );
Assert(pGroup->uiTraverseTime > 0 && pGroup->uiTraverseTime != TRAVERSE_TIME_IMPOSSIBLE);
Assert( pGroup->uiArrivalTime >= GetWorldTotalMin() );
uiTimeToNextSector = pGroup->uiArrivalTime - GetWorldTotalMin();
Assert( pGroup->uiTraverseTime >= uiTimeToNextSector );
uiTimeToLastSector = pGroup->uiTraverseTime - uiTimeToNextSector;
if ( uiTimeToNextSector >= uiTimeToLastSector )
{
// go to the last sector
sPrevX = pGroup->ubNextX;
sPrevY = pGroup->ubNextY;
sNextX = pGroup->ubSectorX;
sNextY = pGroup->ubSectorY;
}
else
{
// go to the next sector
sPrevX = pGroup->ubSectorX;
sPrevY = pGroup->ubSectorY;
sNextX = pGroup->ubNextX;
sNextY = pGroup->ubNextY;
}
// make it arrive immediately, not eventually (it's driverless)
SetGroupArrivalTime(*pGroup, GetWorldTotalMin());
// change where it is and where it's going, then make it arrive there. Don't check for battle
PlaceGroupInSector(*pGroup, sPrevX, sPrevY, sNextX, sNextY, 0, false);
}
void AddVehicleFuelToSave( )
{
CFOR_EACH_VEHICLE(i)
{
VEHICLETYPE const& v = *i;
if (IsHelicopter(v)) continue;
SOLDIERTYPE& vs = GetSoldierStructureForVehicle(v);
// Init fuel!
vs.sBreathRed = 10000;
vs.bBreath = 100;
}
}
static bool CanSoldierDriveVehicle(SOLDIERTYPE const& s, INT32 const vehicle_id, bool const ignore_asleep)
{
return s.bAssignment == VEHICLE && // In a vehicle?
vehicle_id == s.iVehicleId && // In this vehicle?
vehicle_id != iHelicopterVehicleId && // Only Skyrider can pilot the helicopter
(ignore_asleep || !s.fMercAsleep) &&
!IsMechanical(s) && // Vehicles, robot, and EPCs can't drive
!AM_AN_EPC(&s) &&
s.bLife >= OKLIFE && // Too wounded to drive?
s.bBreathMax > BREATHMAX_ABSOLUTE_MINIMUM; // Too tired to drive?
}
static bool OnlyThisSoldierCanDriveVehicle(SOLDIERTYPE const& s, INT32 const vehicle_id)
{
CFOR_EACH_IN_TEAM(i, OUR_TEAM)
{
SOLDIERTYPE const& other = *i;
// Skip checking this soldier, we want to know about everyone else
if (&other == &s) continue;
// Don't count mercs who are asleep here
if (!CanSoldierDriveVehicle(other, vehicle_id, false)) continue;
// This guy can drive it, too
return false;
}
return true;
}
bool SoldierMustDriveVehicle(SOLDIERTYPE const& s, bool const trying_to_travel)
{
INT32 const vehicle_id = s.iVehicleId;
VEHICLETYPE const& v = GetVehicle(vehicle_id);
// If vehicle is not going anywhere, then nobody has to be driving it. Need
// the path length check in case we're doing a test while actually in a sector
// even though we're moving.
if (!trying_to_travel && !v.fBetweenSectors && GetLengthOfPath(v.pMercPath) == 0) return false;
// Can he drive it (don't care if he is currently asleep) and is he the only
// one aboard who can do so? If there are multiple possible drivers, than the
// assumption is that this guy isn't driving, so he can sleep.
if (!CanSoldierDriveVehicle(s, vehicle_id, true)) return false;
if (!OnlyThisSoldierCanDriveVehicle(s, vehicle_id)) return false;
return true;
}
BOOLEAN IsSoldierInThisVehicleSquad(const SOLDIERTYPE* const pSoldier, const INT8 bSquadNumber)
{
Assert( pSoldier );
Assert( ( bSquadNumber >= 0 ) && ( bSquadNumber < NUMBER_OF_SQUADS ) );
// not in a vehicle?
if( pSoldier->bAssignment != VEHICLE )
{
return( FALSE );
}
if (InHelicopter(*pSoldier)) return FALSE; // they don't get a squad #
SOLDIERTYPE const& vs = GetSoldierStructureForVehicle(GetVehicle(pSoldier->iVehicleId));
// check squad vehicle is on
if (vs.bAssignment != bSquadNumber)
{
return( FALSE );
}
// yes, he's in a vehicle assigned to this squad
return( TRUE );
}
SOLDIERTYPE* PickRandomPassengerFromVehicle(SOLDIERTYPE* const pSoldier)
{
// If not a vehicle, ignore!
if (!(pSoldier->uiStatusFlags & SOLDIER_VEHICLE)) return NULL;
VEHICLETYPE const& v = pVehicleList[pSoldier->bVehicleID];
INT32 n_mercs = 0;
SOLDIERTYPE* mercs_in_vehicle[20];
CFOR_EACH_PASSENGER(v, i) mercs_in_vehicle[n_mercs++] = *i;
return n_mercs == 0 ? NULL : mercs_in_vehicle[Random(n_mercs)];
}
bool DoesVehicleGroupHaveAnyPassengers(GROUP const& g)
{
return GetNumberInVehicle(GetVehicleFromMvtGroup(g)) != 0;
}
void HandleVehicleMovementSound(const SOLDIERTYPE* const s, const BOOLEAN fOn)
{
VEHICLETYPE* const v = &pVehicleList[s->bVehicleID];
if (fOn)
{
if (v->iMovementSoundID == NO_SAMPLE)
{
v->iMovementSoundID = PlayLocationJA2Sample(s->sGridNo, g_vehicle_type_info[v->ubVehicleType].move_sound, HIGHVOLUME, 1);
}
}
else
{
if (v->iMovementSoundID != NO_SAMPLE)
{
SoundStop(v->iMovementSoundID);
v->iMovementSoundID = NO_SAMPLE;
}
}
}
UINT8 GetVehicleArmourType(const UINT8 vehicle_id)
{
return GCM->getItem(g_vehicle_type_info[pVehicleList[vehicle_id].ubVehicleType].armour_type)->getClassIndex();
}
UINT8 GetVehicleSeats(VEHICLETYPE const& v)
{
return g_vehicle_type_info[v.ubVehicleType].seats;
}
|
/*
Copyright (C) 2004-2008 Renรฉ Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
Renรฉ Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#ifndef CEREAL_EXTERNAL_BASE64_HPP_
#define CEREAL_EXTERNAL_BASE64_HPP_
#ifdef __GNUC__
#endif
#include <string>
namespace cereal
{
namespace base64
{
static const std::string chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
inline std::string encode(unsigned char const* bytes_to_encode, size_t in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = static_cast<unsigned char>((char_array_3[0] & 0xfc) >> 2);
char_array_4[1] = static_cast<unsigned char>( ( ( char_array_3[0] & 0x03 ) << 4 ) + ( ( char_array_3[1] & 0xf0 ) >> 4 ) );
char_array_4[2] = static_cast<unsigned char>( ( ( char_array_3[1] & 0x0f ) << 2 ) + ( ( char_array_3[2] & 0xc0 ) >> 6 ) );
char_array_4[3] = static_cast<unsigned char>( char_array_3[2] & 0x3f );
for(i = 0; (i <4) ; i++)
ret += chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
inline std::string decode(std::string const& encoded_string) {
size_t in_len = encoded_string.size();
size_t i = 0;
size_t j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = static_cast<unsigned char>(chars.find( char_array_4[i] ));
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = static_cast<unsigned char>(chars.find( char_array_4[j] ));
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
} // namespace base64
} // namespace cereal
#ifdef __GNUC__
#endif
#endif // CEREAL_EXTERNAL_BASE64_HPP_
|
/**
* Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors
* All rights reserved.
*
* This source code is licensed under the FreeBSD license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifdef GLib_WIN
/////////////////////////////////////////////////
// System-Processes
void TSysProc::Sleep(const uint& MSecs){
SleepEx(MSecs, false);
}
TStr TSysProc::GetExeFNm(){
DWORD MxFNmLen=1024;
LPTSTR FNmCStr=new char[MxFNmLen];
DWORD FNmLen=GetModuleFileName(NULL, FNmCStr, MxFNmLen);
TStr FNm;
if (FNmLen!=0){
FNm=FNmCStr;}
delete[] FNmCStr;
return FNm;
}
void TSysProc::SetLowPriority(){
SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);
}
bool TSysProc::ExeProc(const TStr& ExeFNm, TStr& ParamStr){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb=sizeof(si);
ZeroMemory(&pi, sizeof(pi));
char * ParamStrCopy = ParamStr.CloneCStr();
// Start the child process.
BOOL Ok=CreateProcess(
ExeFNm.CStr(), // module name
ParamStrCopy, // patameters
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // No creation flags.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi); // Pointer to PROCESS_INFORMATION structure.
delete[] ParamStrCopy;
if (Ok){
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return true;
} else {
return false;
}
}
/////////////////////////////////////////////////
// Memory-Status
TStr TSysMemStat::GetLoadStr(){
static TStr MemUsageStr="Mem Load: ";
TChA ChA;
ChA+=MemUsageStr;
ChA+=TUInt64::GetStr(GetLoad());
ChA+="%";
return ChA;
}
TStr TSysMemStat::GetUsageStr(){
static TStr MemUsageStr="Mem Usage: ";
uint64 GlobalUsage=GetTotalPageFile()-GetAvailPageFile();
TChA ChA;
ChA+=MemUsageStr;
ChA+=TUInt64::GetStr(GlobalUsage/1024);
ChA+="K / ";
ChA+=TUInt64::GetStr(GetTotalPageFile()/1024);
ChA+="K";
return ChA;
}
TStr TSysMemStat::GetInfoStr(){
TChA ChA;
ChA+="Memory Load:";
ChA+=TUInt64::GetMegaStr(GetLoad()); ChA+="\r\n";
ChA+="Total Physical:";
ChA+=TUInt64::GetMegaStr(GetTotalPhys()); ChA+="\r\n";
ChA+="Available Physical:";
ChA+=TUInt64::GetMegaStr(GetAvailPhys()); ChA+="\r\n";
ChA+="Total Page File:";
ChA+=TUInt64::GetMegaStr(GetTotalPageFile()); ChA+="\r\n";
ChA+="Available Page File:";
ChA+=TUInt64::GetMegaStr(GetAvailPageFile()); ChA+="\r\n";
ChA+="Total Virtual:";
ChA+=TUInt64::GetMegaStr(GetTotalVirtual()); ChA+="\r\n";
ChA+="Available Virtual:";
ChA+=TUInt64::GetMegaStr(GetAvailVirtual()); ChA+="\r\n";
return ChA;
}
TStr TSysMemStat::GetStr(){
TChA ChA;
ChA+=TUInt64::GetStr(GetLoad()); ChA+=' ';
ChA+=TUInt64::GetStr(GetTotalPhys()); ChA+=' ';
ChA+=TUInt64::GetStr(GetAvailPhys()); ChA+=' ';
ChA+=TUInt64::GetStr(GetTotalPageFile()); ChA+=' ';
ChA+=TUInt64::GetStr(GetAvailPageFile()); ChA+=' ';
ChA+=TUInt64::GetStr(GetTotalVirtual()); ChA+=' ';
ChA+=TUInt64::GetStr(GetAvailVirtual());
return ChA;
}
/////////////////////////////////////////////////
// System-Console
TSysConsole::TSysConsole(){
Ok=(AllocConsole()!=0);
IAssert(Ok);
hStdOut=GetStdHandle(STD_OUTPUT_HANDLE);
IAssert(hStdOut!=INVALID_HANDLE_VALUE);
}
TSysConsole::~TSysConsole(){
if (Ok){
IAssert(FreeConsole());}
}
void TSysConsole::Put(const TStr& Str){
DWORD ChsWritten;
WriteConsole(hStdOut, Str.CStr(), Str.Len(), &ChsWritten, NULL);
IAssert(ChsWritten==DWORD(Str.Len()));
}
/////////////////////////////////////////////////
// System-Console-Notifier
void TSysConsoleNotify::OnNotify(const TNotifyType& Type, const TStr& MsgStr){
if (Type==ntInfo){
SysConsole->PutLn(TStr::Fmt("%s", MsgStr.CStr()));
} else {
TStr TypeStr=TNotify::GetTypeStr(Type, false);
SysConsole->PutLn(TStr::Fmt("%s: %s", TypeStr.CStr(), MsgStr.CStr()));
}
}
void TSysConsoleNotify::OnStatus(const TStr& MsgStr){
SysConsole->Put(MsgStr.CStr());
// print '\n' if message not overlayed
if ((!MsgStr.Empty())&&(MsgStr.LastCh()!='\r')){
SysConsole->PutLn(""); }
}
/////////////////////////////////////////////////
// System-Time
TTm TSysTm::GetCurUniTm(){
SYSTEMTIME SysTm;
GetSystemTime(&SysTm);
return TTm(SysTm.wYear, SysTm.wMonth, SysTm.wDay, SysTm.wDayOfWeek,
SysTm.wHour, SysTm.wMinute, SysTm.wSecond, SysTm.wMilliseconds);
}
TTm TSysTm::GetCurLocTm(){
SYSTEMTIME SysTm;
GetLocalTime(&SysTm);
return TTm(SysTm.wYear, SysTm.wMonth, SysTm.wDay, SysTm.wDayOfWeek,
SysTm.wHour, SysTm.wMinute, SysTm.wSecond, SysTm.wMilliseconds);
}
uint64 TSysTm::GetCurUniMSecs(){
SYSTEMTIME SysTm; FILETIME FileTm;
GetSystemTime(&SysTm);
IAssert(SystemTimeToFileTime(&SysTm, &FileTm));
TUInt64 UInt64(uint(FileTm.dwHighDateTime), uint(FileTm.dwLowDateTime));
return UInt64.Val/uint64(10000);
}
uint64 TSysTm::GetCurLocMSecs(){
SYSTEMTIME SysTm; FILETIME FileTm;
GetLocalTime(&SysTm);
IAssert(SystemTimeToFileTime(&SysTm, &FileTm));
TUInt64 UInt64(uint(FileTm.dwHighDateTime), uint(FileTm.dwLowDateTime));
return UInt64.Val/uint64(10000);
}
uint64 TSysTm::GetMSecsFromTm(const TTm& Tm){
SYSTEMTIME SysTm; FILETIME FileTm;
SysTm.wYear=WORD(Tm.GetYear());
SysTm.wMonth=WORD(Tm.GetMonth());
SysTm.wDayOfWeek=WORD(Tm.GetDayOfWeek());
SysTm.wDay=WORD(Tm.GetDay());
SysTm.wHour=WORD(Tm.GetHour());
SysTm.wMinute=WORD(Tm.GetMin());
SysTm.wSecond=WORD(Tm.GetSec());
SysTm.wMilliseconds=WORD(Tm.GetMSec());
ESAssert(SystemTimeToFileTime(&SysTm, &FileTm));
TUInt64 UInt64(uint(FileTm.dwHighDateTime), uint(FileTm.dwLowDateTime));
return UInt64.Val/uint64(10000);
}
TTm TSysTm::GetTmFromMSecs(const uint64& MSecs){
TUInt64 FileTmUnits(MSecs*uint64(10000));
SYSTEMTIME SysTm; FILETIME FileTm;
FileTm.dwHighDateTime=FileTmUnits.GetMsVal();
FileTm.dwLowDateTime=FileTmUnits.GetLsVal();
SAssert(FileTimeToSystemTime(&FileTm, &SysTm));
return TTm(SysTm.wYear, SysTm.wMonth, SysTm.wDay, SysTm.wDayOfWeek,
SysTm.wHour, SysTm.wMinute, SysTm.wSecond, SysTm.wMilliseconds);
}
uint TSysTm::GetMSecsFromOsStart(){
return uint(GetTickCount());
}
bool TSysTm::IsValidDate(const TTm& Tm) {
SYSTEMTIME SysTm; FILETIME FileTm;
SysTm.wYear = WORD(Tm.GetYear());
SysTm.wMonth = WORD(Tm.GetMonth());
SysTm.wDayOfWeek = WORD(Tm.GetDayOfWeek());
SysTm.wDay = WORD(Tm.GetDay());
SysTm.wHour = WORD(Tm.GetHour());
SysTm.wMinute = WORD(Tm.GetMin());
SysTm.wSecond = WORD(Tm.GetSec());
SysTm.wMilliseconds = WORD(Tm.GetMSec());
return (bool) SystemTimeToFileTime(&SysTm, &FileTm);
}
TTm TSysTm::GetLocTmFromUniTm(const TTm& Tm){
// get time-zone information
TIME_ZONE_INFORMATION TzInf;
GetTimeZoneInformation(&TzInf);
// get system time
SYSTEMTIME UniSysTm;
UniSysTm.wYear=WORD(Tm.GetYear());
UniSysTm.wMonth=WORD(Tm.GetMonth());
UniSysTm.wDayOfWeek=WORD(Tm.GetDayOfWeek());
UniSysTm.wDay=WORD(Tm.GetDay());
UniSysTm.wHour=WORD(Tm.GetHour());
UniSysTm.wMinute=WORD(Tm.GetMin());
UniSysTm.wSecond=WORD(Tm.GetSec());
UniSysTm.wMilliseconds=WORD(Tm.GetMSec());
// convert system-time
SYSTEMTIME LocSysTm;
SystemTimeToTzSpecificLocalTime(&TzInf, &UniSysTm, &LocSysTm);
// return local-time
return TTm(LocSysTm.wYear, LocSysTm.wMonth, LocSysTm.wDay, LocSysTm.wDayOfWeek,
LocSysTm.wHour, LocSysTm.wMinute, LocSysTm.wSecond, LocSysTm.wMilliseconds);
}
TTm TSysTm::GetUniTmFromLocTm(const TTm& Tm){
// get time-zone information
TIME_ZONE_INFORMATION TzInf;
GetTimeZoneInformation(&TzInf);
// get system time
SYSTEMTIME LocSysTm;
LocSysTm.wYear=WORD(Tm.GetYear());
LocSysTm.wMonth=WORD(Tm.GetMonth());
LocSysTm.wDayOfWeek=WORD(Tm.GetDayOfWeek());
LocSysTm.wDay=WORD(Tm.GetDay());
LocSysTm.wHour=WORD(Tm.GetHour());
LocSysTm.wMinute=WORD(Tm.GetMin());
LocSysTm.wSecond=WORD(Tm.GetSec());
LocSysTm.wMilliseconds=WORD(Tm.GetMSec());
// convert system-time
SYSTEMTIME UniSysTm=LocSysTm;
Fail; // BCB5.0 doesn't find TzSpecificLocalTimeToSystemTime
//TzSpecificLocalTimeToSystemTime(&TzInf, &LocSysTm, &UniSysTm);
// return system-time
return TTm(UniSysTm.wYear, UniSysTm.wMonth, UniSysTm.wDay, UniSysTm.wDayOfWeek,
UniSysTm.wHour, UniSysTm.wMinute, UniSysTm.wSecond, UniSysTm.wMilliseconds);
}
uint64 TSysTm::GetProcessMSecs(){
FILETIME CreationTime, ExitTime, KernelTime, UserTime;
IAssert(GetProcessTimes(GetCurrentProcess(),
&CreationTime, &ExitTime, &KernelTime, &UserTime));
TUInt64 KernelMSecs(uint(KernelTime.dwHighDateTime), uint(KernelTime.dwLowDateTime));
TUInt64 UserMSecs(uint(UserTime.dwHighDateTime), uint(UserTime.dwLowDateTime));
uint64 ProcessMSecs=KernelMSecs+UserMSecs;
return ProcessMSecs;
}
uint64 TSysTm::GetThreadMSecs(){
FILETIME CreationTime, ExitTime, KernelTime, UserTime;
IAssert(GetProcessTimes(GetCurrentProcess(),
&CreationTime, &ExitTime, &KernelTime, &UserTime));
TUInt64 KernelMSecs(uint(KernelTime.dwHighDateTime), uint(KernelTime.dwLowDateTime));
TUInt64 UserMSecs(uint(UserTime.dwHighDateTime), uint(UserTime.dwLowDateTime));
uint64 ThreadMSecs=KernelMSecs+UserMSecs;
return ThreadMSecs;
}
uint64 TSysTm::GetPerfTimerFq(){
uint MsFq; uint LsFq;
LARGE_INTEGER LargeInt;
if (QueryPerformanceFrequency(&LargeInt)){
MsFq=LargeInt.u.HighPart;
LsFq=LargeInt.u.LowPart;
} else {
MsFq=0;
LsFq=1;
}
TUInt64 UInt64(MsFq, LsFq);
return UInt64.Val;
}
uint64 TSysTm::GetPerfTimerTicks(){
uint MsVal; uint LsVal;
LARGE_INTEGER LargeInt;
if (QueryPerformanceCounter(&LargeInt)){
MsVal=LargeInt.u.HighPart;
LsVal=LargeInt.u.LowPart;
} else {
MsVal=0;
LsVal=int(time(NULL));
}
TUInt64 UInt64(MsVal, LsVal);
return UInt64.Val;
}
/////////////////////////////////////////////////
// System-Strings
TStr TSysStr::GetCmLn(){
return TStr((char*)GetCommandLine());
}
TStr TSysStr::GetMsgStr(const DWORD& MsgCd){
// retrieve message string
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
MsgCd,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL);
// save string
TStr MsgStr((char*)lpMsgBuf);
// free the buffer.
LocalFree(lpMsgBuf);
return MsgStr;
}
char* TSysStr::GetLastMsgCStr(){
TStr MsgStr=GetLastMsgStr();
static char* MsgCStr=NULL;
if (MsgCStr==NULL){MsgCStr=new char[1000];}
strcpy(MsgCStr, MsgStr.CStr());
return MsgCStr;
}
/////////////////////////////////////////////////
// Registry-Key
PRegKey TRegKey::GetKey(const PRegKey& BaseKey, const TStr& SubKeyNm){
HKEY hKey;
DWORD RetCd=RegOpenKeyEx(
BaseKey->GetHandle(), SubKeyNm.CStr(), 0, KEY_ALL_ACCESS, &hKey);
bool Ok=RetCd==ERROR_SUCCESS;
return new TRegKey(Ok, hKey);
}
TStr TRegKey::GetVal(const PRegKey& Key, const TStr& SubKeyNm, const TStr& ValNm){
PRegKey RegKey=TRegKey::GetKey(Key, SubKeyNm);
if (RegKey->IsOk()){
TStrKdV ValNmStrKdV; RegKey->GetValV(ValNmStrKdV);
int ValN;
if (ValNmStrKdV.IsIn(TStrKd(ValNm), ValN)){
return ValNmStrKdV[ValN].Dat;
} else {
return "";
}
} else {
return "";
}
}
void TRegKey::GetKeyNmV(TStrV& KeyNmV) const {
KeyNmV.Clr();
if (!Ok){return;}
// get subkey count
DWORD SubKeys; // number of subkeys
DWORD MxSubKeyNmLen; // longest subkey size
DWORD RetCd=RegQueryInfoKey(
hKey, // key handle
NULL, // buffer for class name
NULL, // length of class string
NULL, // reserved
&SubKeys, // number of subkeys
&MxSubKeyNmLen, // longest subkey size
NULL, // longest class string
NULL, // number of values for this key
NULL, // longest value name
NULL, // longest value data
NULL, // security descriptor
NULL); // last write time
if (RetCd!=ERROR_SUCCESS){return;}
// retrieve subkey-names
if (SubKeys>0){
KeyNmV.Gen(SubKeys, 0);
char* SubKeyNmCStr=new char[MxSubKeyNmLen+1];
DWORD SubKeyN=0;
forever{
DWORD SubKeyNmCStrLen=MxSubKeyNmLen+1;
DWORD RetCd=RegEnumKeyEx(
hKey, // handle of key to enumerate
SubKeyN, // index of subkey to enumerate
SubKeyNmCStr, // address of buffer for subkey name
&SubKeyNmCStrLen, // address for size of subkey buffer
NULL, // reserved
NULL, // address of buffer for class string
NULL, // address for size of class buffer
NULL); // address for time key last written to
if (RetCd==ERROR_SUCCESS){
TStr KeyNm(SubKeyNmCStr);
KeyNmV.Add(KeyNm);
} else {
break;
}
SubKeyN++;
}
delete[] SubKeyNmCStr;
}
}
void TRegKey::GetValV(TStrKdV& ValNmStrKdV) const {
ValNmStrKdV.Clr();
if (!Ok){return;}
// get subkey count
DWORD Vals; // number of values
DWORD MxValNmLen; // longest value name
DWORD MxValStrLen; // longest value data
DWORD RetCd=RegQueryInfoKey(
hKey, // key handle
NULL, // buffer for class name
NULL, // length of class string
NULL, // reserved
NULL, // number of subkeys
NULL, // longest subkey size
NULL, // longest class string
&Vals, // number of values for this key
&MxValNmLen, // longest value name
&MxValStrLen, // longest value data
NULL, // security descriptor
NULL); // last write time
if (RetCd!=ERROR_SUCCESS){return;}
// retrieve subkey-names
if (Vals>0){
ValNmStrKdV.Gen(Vals, 0);
char* ValNmCStr=new char[MxValNmLen+1];
char* ValCStr=new char[MxValStrLen+1];
DWORD ValN=0;
forever{
DWORD ValNmCStrLen=MxValNmLen+1;
DWORD ValCStrLen=MxValStrLen+1;
DWORD ValType;
DWORD RetCd=RegEnumValue(
hKey, // handle of key to query
ValN, // index of value to query
ValNmCStr, // address of buffer for value string
&ValNmCStrLen, // address for size of value buffer
NULL, // reserved
&ValType, // address of buffer for type code
(unsigned char*) ValCStr, // address of buffer for value data
&ValCStrLen); // address for size of data buffer
if (RetCd==ERROR_SUCCESS){
if (ValType==REG_SZ){
TStr ValNm(ValNmCStr);
TStr ValStr(ValCStr);
ValNmStrKdV.Add(TStrKd(ValNm, ValStr));
}
} else {
break;
}
ValN++;
}
delete[] ValNmCStr;
delete[] ValCStr;
}
}
/////////////////////////////////////////////////
// Program StdIn and StdOut redirection using pipes
void TStdIOPipe::CreateProc(const TStr& Cmd) {
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdInput = ChildStdinRd;
siStartInfo.hStdOutput = ChildStdoutWr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// Create the child process.
const BOOL FuncRetn = CreateProcess(NULL,
(LPSTR) Cmd.CStr(), // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
EAssertR(FuncRetn!=0, TStr::Fmt("Can not execute '%s'", Cmd.CStr()).CStr());
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
}
TStdIOPipe::TStdIOPipe(const TStr& CmdToExe) : ChildStdinRd(NULL), ChildStdinWrDup(NULL),
ChildStdoutWr(NULL), ChildStdoutRdDup(NULL) {
HANDLE ChildStdinWr, ChildStdoutRd;
SECURITY_ATTRIBUTES saAttr;
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
EAssert(CreatePipe(&ChildStdoutRd, &ChildStdoutWr, &saAttr, 0));
// Create noninheritable read handle and close the inheritable read handle.
EAssert(DuplicateHandle(GetCurrentProcess(), ChildStdoutRd,
GetCurrentProcess(), &ChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS));
CloseHandle(ChildStdoutRd);
// Create a pipe for the child process's STDIN.
EAssert(CreatePipe(&ChildStdinRd, &ChildStdinWr, &saAttr, 0));
// Duplicate the write handle to the pipe so it is not inherited.
EAssert(DuplicateHandle(GetCurrentProcess(), ChildStdinWr,
GetCurrentProcess(), &ChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS));
CloseHandle(ChildStdinWr);
// Now create the child process.
CreateProc(CmdToExe);
}
TStdIOPipe::~TStdIOPipe() {
if (ChildStdinRd != NULL) CloseHandle(ChildStdinRd);
if (ChildStdinWrDup != NULL) CloseHandle(ChildStdinWrDup);
if (ChildStdoutWr != NULL) CloseHandle(ChildStdoutWr);
if (ChildStdoutRdDup != NULL) CloseHandle(ChildStdoutRdDup);
}
int TStdIOPipe::Write(const char* Bf, const int& BfLen) {
DWORD Written;
EAssert(WriteFile(ChildStdinWrDup, Bf, BfLen, &Written, NULL));
return int(Written);
}
int TStdIOPipe::Read(char *Bf, const int& BfMxLen) {
DWORD Read;
EAssert(ReadFile(ChildStdoutRdDup, Bf, BfMxLen, &Read, NULL));
return int(Read);
}
#elif defined(GLib_UNIX)
/////////////////////////////////////////////////
// Compatibility functions
int GetModuleFileName(void *hModule, char *Bf, int MxBfL) {
int retlen = (int) readlink("/proc/self/exe", Bf, MxBfL);
if (retlen == -1) {
if (MxBfL > 0) Bf[0] = '\0';
return 0;
}
if (retlen == MxBfL) --retlen;
Bf[retlen] = '\0';
return retlen;
}
int GetCurrentDirectory(const int MxBfL, char *Bf) {
EAssert(getcwd(Bf, MxBfL) != NULL);
return (int) strlen(Bf);
}
int CreateDirectory(const char *FNm, void *useless) {
return mkdir(FNm, 0777)==0;
}
int RemoveDirectory(const char *FNm) {
return rmdir(FNm)==0;
}
#define TICKS_PER_SECOND 10000000
#define EPOCH_DIFFERENCE 11644473600LL
/// Converts Unix epoch time to Windows FILETIME.
uint64 Epoch2Ft(time_t Epoch){
uint64 Ft;
Ft = Epoch + EPOCH_DIFFERENCE; // Adds seconds between epochs
Ft *= TICKS_PER_SECOND; // Converts from seconds to 100ns intervals
return Ft;
}
/// Converts Windows FILETIME to Unix epoch time.
time_t Ft2Epoch(uint64 Ft){
uint64 Epoch;
Epoch = Ft / TICKS_PER_SECOND; // Converts from 100ns intervals to seconds
Epoch -= EPOCH_DIFFERENCE; // Subtracts seconds between epochs
return (time_t) Epoch;
}
/////////////////////////////////////////////////
// System-Time
TTm TSysTm::GetCurUniTm(){
time_t t;
struct tm tms;
struct timeval tv;
time(&t);
int ErrCd = gettimeofday(&tv, NULL);
if (ErrCd != 0) { EAssert(t!=-1); }
gmtime_r(&t, &tms);
return TTm(1900+tms.tm_year, tms.tm_mon + 1, tms.tm_mday, tms.tm_wday,
tms.tm_hour, tms.tm_min, tms.tm_sec, tv.tv_usec/1000);
}
TTm TSysTm::GetCurLocTm(){
time_t t;
struct tm tms;
struct timeval tv;
time(&t);
int ErrCd = gettimeofday(&tv, NULL);
if (ErrCd != 0) { EAssert(t!=-1); }
localtime_r(&t, &tms);
return TTm(1900+tms.tm_year, tms.tm_mon + 1, tms.tm_mday, tms.tm_wday,
tms.tm_hour, tms.tm_min, tms.tm_sec, tv.tv_usec/1000);
}
uint64 TSysTm::GetCurUniMSecs(){
return TSysTm::GetMSecsFromTm(GetCurLocTm());
}
uint64 TSysTm::GetCurLocMSecs(){
return TSysTm::GetMSecsFromTm(GetCurUniTm());
}
uint64 TSysTm::GetMSecsFromTm(const TTm& Tm){
time_t t;
struct tm tms;
tms.tm_year = Tm.GetYear() - 1900;
tms.tm_mon = Tm.GetMonth() - 1;
tms.tm_mday = Tm.GetDay();
tms.tm_hour = Tm.GetHour();
tms.tm_min = Tm.GetMin();
tms.tm_sec = Tm.GetSec();
t = timegm(&tms);
return Epoch2Ft(t)/10000 + (uint64)Tm.GetMSec();
}
TTm TSysTm::GetTmFromMSecs(const uint64& TmNum){
const int MSec = int(TmNum % 1000);
time_t Sec = Ft2Epoch(TmNum*10000);
struct tm tms;
gmtime_r(&Sec, &tms);
return TTm(1900+tms.tm_year, tms.tm_mon + 1, tms.tm_mday, tms.tm_wday,
tms.tm_hour, tms.tm_min, tms.tm_sec, MSec);
}
bool TSysTm::IsValidDate(const TTm& Tm) {
FailR("Feature not implemented");
return true;
}
TTm TSysTm::GetLocTmFromUniTm(const TTm& Tm) {
struct tm tms, tmr;
tms.tm_year = Tm.GetYear() - 1900;
tms.tm_mon = Tm.GetMonth() - 1;
tms.tm_mday = Tm.GetDay();
tms.tm_hour = Tm.GetHour();
tms.tm_min = Tm.GetMin();
tms.tm_sec = Tm.GetSec();
int MSec = Tm.GetMSec();
time_t Sec = timegm(&tms);
localtime_r(&Sec, &tmr);
return TTm(1900+tmr.tm_year, tmr.tm_mon + 1, tmr.tm_mday, tmr.tm_wday,
tmr.tm_hour, tmr.tm_min, tmr.tm_sec, MSec);
}
TTm TSysTm::GetUniTmFromLocTm(const TTm& Tm) {
struct tm tms, tmr;
tms.tm_year = Tm.GetYear() - 1900;
tms.tm_mon = Tm.GetMonth() - 1;
tms.tm_mday = Tm.GetDay();
tms.tm_hour = Tm.GetHour();
tms.tm_min = Tm.GetMin();
tms.tm_sec = Tm.GetSec();
tms.tm_isdst = -1; // ask the system to figure out DST
int MSec = Tm.GetMSec();
time_t Sec = mktime(&tms);
gmtime_r(&Sec, &tmr);
return TTm(1900+tmr.tm_year, tmr.tm_mon + 1, tmr.tm_mday, tmr.tm_wday,
tmr.tm_hour, tmr.tm_min, tmr.tm_sec, MSec);
}
uint TSysTm::GetMSecsFromOsStart(){
#if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_MONOTONIC, &ts);
if (ErrCd != 0) { Assert(ErrCd==0); }
return (ts.tv_sec*1000) + (ts.tv_nsec/1000000);
#else
FILE *f;
uint sec, csec;
f = fopen("/proc/uptime", "r");
if (!f) return 0xffffffff; // !bn: assert
fscanf(f, "%u.%u", &sec, &csec);
fclose(f);
return (uint) (sec * 1000) + (csec * 10);
#endif
}
uint64 TSysTm::GetProcessMSecs() {
#if defined(_POSIX_CPUTIME) && (_POSIX_CPUTIME != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
if (ErrCd != 0) { Assert(ErrCd==0); }
return (ts.tv_sec*1000) + (ts.tv_nsec / 1000000);
#else
//#warning "CLOCK_PROCESS_CPUTIME not available; using getrusage"
struct rusage ru;
int ErrCd = getrusage(RUSAGE_SELF, &ru);
if (ErrCd != 0) { EAssert(ErrCd == 0); }
return ((ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) / 1000) +
((ru.ru_utime.tv_sec + ru.ru_stime.tv_sec) * 1000);
#endif
}
uint64 TSysTm::GetThreadMSecs() {
#if defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
if (ErrCd != 0) { Assert(ErrCd==0); }
return (ts.tv_sec*1000) + (ts.tv_nsec / 1000000);
#else
//#warning "CLOCK_THREAD_CPUTIME not available; using GetProcessMSecs()"
return GetProcessMSecs();
#endif
}
uint64 TSysTm::GetPerfTimerFq(){
#if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK != -1)
return 1000000000;
#else
return 1000000;
#endif
}
uint64 TSysTm::GetPerfTimerTicks(){
#if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK != -1)
struct timespec ts;
int ErrCd=clock_gettime(CLOCK_MONOTONIC, &ts);
//Assert(ErrCd==0); //J: vcasih se prevede in ne dela
if (ErrCd != 0) {
return (uint64)ts.tv_sec*1000000000ll + (uint64)ts.tv_nsec; }
else {
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64)tv.tv_usec + ((uint64)tv.tv_sec)*1000000;
}
#else
//#warning "CLOCK_MONOTONIC not available; using gettimeofday()"
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64)tv.tv_usec + ((uint64)tv.tv_sec)*1000000;
#endif
}
/////////////////////////////////////////////////
// System-Processes
int TSysProc::Sleep(const uint& MSecs) {
int ret;
struct timespec tsp, trem;
tsp.tv_sec = MSecs / 1000;
tsp.tv_nsec = (MSecs % 1000) * 1000000;
while (true) {
ret = nanosleep(&tsp, &trem);
if ((ret != -1) || (errno != EINTR)) {
break;
}
tsp = trem;
}
return ret;
}
TStr TSysProc::GetExeFNm() {
char Bf[1024];
GetModuleFileName(NULL, Bf, 1023);
return TStr(Bf);
}
void TSysProc::SetLowPriority() {
EAssert(nice(19) != -1);
}
bool TSysProc::ExeProc(const TStr& ExeFNm, TStr& ParamStr) {
TStrV SArgV;
ParamStr.SplitOnWs(SArgV);
int pid = fork();
if (pid == -1) return false;
if (pid > 0) return true;
char **argv;
argv = new char*[SArgV.Len()+2];
argv[0] = strdup(ExeFNm.CStr());
for (int i=0;i<SArgV.Len();i++) argv[i+1] = strdup(SArgV[i].CStr());
argv[SArgV.Len()+1] = NULL;
execvp(argv[0], argv);
//BF: moved role of TSysMsg to TLoop and TSockSys in net.h, hence removed the following inline
//TSysMsg::Quit();
kill(getpid(), SIGINT);
return false;
}
/////////////////////////////////////////////////
// System-Memory-Status
TSysMemStat::TSysMemStat() {
struct {
unsigned long size,resident,share,text,lib,data,dt;
} result;
// read process information
FILE *f = fopen("/proc/self/statm", "r");
EAssertR(f != NULL, "Error reading /proc/self/statm");
EAssertR(7 == fscanf(f, "%ld %ld %ld %ld %ld %ld %ld", &result.size,
&result.resident, &result.share, &result.text, &result.lib,
&result.data, &result.dt), "Error parsing /proc/self/statm");
// close file
fclose(f);
// transform from Kb to bytes
Size = (uint64)(result.size) * 1024LL;
Resident = (uint64)(result.resident) * 1024LL;
Share = (uint64)(result.share) * 1024LL;
Text = (uint64)(result.text) * 1024LL;
Lib = (uint64)(result.lib) * 1024LL;
Data = (uint64)(result.data) * 1024LL;
Dt = (uint64)(result.dt) * 1024LL;
}
/////////////////////////////////////////////////
// Program StdIn and StdOut redirection using pipes
// J: not yet ported to Linux
TStdIOPipe::TStdIOPipe(const TStr& CmdToExe) {
FailR("Not intended for use under Linux!");
}
TStdIOPipe::~TStdIOPipe() {
FailR("Not intended for use under Linux!");
}
int TStdIOPipe::Write(const char* Bf, const int& BfLen) {
FailR("Not intended for use under Linux!");
return -1;
}
int TStdIOPipe::Read(char *Bf, const int& BfMxLen) {
FailR("Not intended for use under Linux!");
return -1;
}
#endif
|
// | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main author: Miguel Angel Celigueta
//
#if !defined(KRATOS_APPLY_KINEMATIC_CONSTRAINTS_PROCESS )
#define KRATOS_APPLY_KINEMATIC_CONSTRAINTS_PROCESS
// System includes
#include <string>
#include <iostream>
// External includes
// Project includes
#include "includes/table.h"
#include "includes/kratos_flags.h"
#include "includes/kratos_parameters.h"
#include "processes/process.h"
#include "utilities/interval_utility.h"
#include "utilities/python_function_callback_utility.h"
#include "DEM_application_variables.h"
namespace Kratos
{
///@addtogroup DEMApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Auxiliary process to apply forces and moments to particles.
/** This process sets the EXTERNAL_APPLIED_FORCE and EXTERNAL_APPLIED_MOMENT variables
over particles.
*/
class KRATOS_API(DEM_APPLICATION) ApplyKinematicConstraintsProcess: public Process
{
public:
///@name Type Definitions
///@{
/// Pointer definition of ApplyKinematicConstraintsProcess
KRATOS_CLASS_POINTER_DEFINITION(ApplyKinematicConstraintsProcess);
/// Defining a table with double argument and result type as table type.
typedef Table<double,double> TableType;
///@}
///@name Life Cycle
///@{
/// Constructor
ApplyKinematicConstraintsProcess(ModelPart& rModelPart, Parameters rParameters);
/// Destructor.
~ApplyKinematicConstraintsProcess() override;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
void Execute() override;
void ExecuteInitializeSolutionStep() override;
void ExecuteFinalizeSolutionStep() override;
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override;
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override;
/// Print object's data.
void PrintData(std::ostream& rOStream) const override;
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
ModelPart& mrModelPart;
Parameters mParameters;
IntervalUtility mInterval;
array_1d<bool, 3> mVelocityIsConstrained;
array_1d<bool, 3> mAngularVelocityIsConstrained;
array_1d<bool, 3> mVelocityValueIsNumeric;
array_1d<bool, 3> mAngularVelocityValueIsNumeric;
array_1d<double, 3> mVelocityValues;
array_1d<double, 3> mAngularVelocityValues;
std::vector<GenericFunctionUtility> mVelocityFunctions;
std::vector<GenericFunctionUtility> mAngularVelocityFunctions;
array_1d<int, 3> mVelocityTableId;
array_1d<int, 3> mAngularVelocityTableId;
std::vector<TableType::Pointer> mpVelocityTable;
std::vector<TableType::Pointer> mpAngularVelocityTable;
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
/// Assignment operator.
ApplyKinematicConstraintsProcess& operator=(ApplyKinematicConstraintsProcess const& rOther);
/// Copy constructor.
ApplyKinematicConstraintsProcess(ApplyKinematicConstraintsProcess const& rOther);
///@}
}; // Class ApplyKinematicConstraintsProcess
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
/// output stream function
inline std::ostream& operator << (
std::ostream& rOStream,
const ApplyKinematicConstraintsProcess& rThis);
///@}
///@} addtogroup block
} // namespace Kratos.
#endif // KRATOS_APPLY_KINEMATIC_CONSTRAINTS_PROCESS defined
|
/* =====================================================================================
* Utilitiy functions, macros and templates for binding C++ code to Lua easily
*
* Copyright (C) 2018 Jonas Mรธller (no) <jonas.moeller2@protonmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* =====================================================================================
*/
#include <memory>
extern "C" {
#include <unistd.h>
}
#include "LuaUtils.hpp"
#include "utils.hpp"
using namespace std;
using namespace std::chrono;
namespace Lua {
/**
* Print the stack contents to a stringstream.
*/
void printStack(lua_State *L, stringstream *stream) {
(*stream) << "Lua stack trace:" << std::endl;
for (int i = lua_gettop(L); i > 0; i--) {
switch (lua_type(L, i)) {
case LUA_TBOOLEAN:
(*stream) << " " << i << ": " << lua_toboolean(L, i) << std::endl;
break;
case LUA_TSTRING:
(*stream) << " " << i << ": " << lua_tostring(L, i) << std::endl;
break;
case LUA_TNUMBER:
(*stream) << " " << i << ": " << lua_tonumber(L, i) << std::endl;
break;
case LUA_TUSERDATA:
(*stream) << " " << i << ": " << lua_getuservalue(L, i) << std::endl;
break;
default:
(*stream) << " " << i << ": " << luaL_typename(L, i) << std::endl;
break;
}
}
}
/**
* Implementation of isCallable
*/
static bool isCallableHelper(lua_State *L, int idx, int depth) {
static const int soft_max_depth = 32;
if (!lua_checkstack(L, 2))
luaL_error(L, "Maximum recursion depth exceeded (%s)", __func__);
else if (depth > soft_max_depth)
luaL_error(L,
"Unable to determine if function is callable," \
"__call metamethods nested beyond %d layers (%s)",
soft_max_depth, __func__);
if (lua_isfunction(L, idx))
return true;
lua_getmetatable(L, idx);
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
return false;
}
lua_getfield(L, -1, "__call");
// Nested __call metamethods are possible
bool is_callable = isCallableHelper(L, -1, depth+1);
lua_pop(L, 2);
return is_callable;
}
/** Figure out if a Lua value is callable, will detect tables
* with __call metamethods as callable with a maximum nesting
* depth of 32.
*
* @param L Lua state.
* @param idx Index on Lua stack.
*/
bool isCallable(lua_State *L, int idx) {
return isCallableHelper(L, idx, 0);
}
Script::Script(string path) : src(path) {
if (src.size() == 0)
throw Lua::LuaError("No path given");
auto L = unique_ptr<lua_State, decltype(&lua_close)>(luaL_newstate(),
&lua_close);
this->L = L.get();
luaL_openlibs(L.get());
from(path);
L.release();
}
Script::Script() {
L = luaL_newstate();
luaL_openlibs(L);
}
void Script::from(const std::string& path) {
if (luaL_loadfile(L, path.c_str()) != LUA_OK) {
string err(lua_tostring(L, -1));
throw Lua::LuaError(err);
}
if (lua_pcall(L, 0, 0, 0) != LUA_OK) {
string err(lua_tostring(L, -1));
throw Lua::LuaError(err);
}
}
void Script::reset() {
lua_close(L);
auto L = unique_ptr<lua_State, decltype(&lua_close)>(luaL_newstate(), &lua_close);
this->L = L.get();
luaL_openlibs(L.get());
L.release();
}
Script::~Script() noexcept {
lua_close(L);
}
lua_State *Script::getL() noexcept {
return L;
}
void Script::exec(const std::string &src, const std::string &str) {
auto reformat = [&](const std::string &err) -> auto {
regex rx("^\\[string \".+\"\\]:([0-9]+): (.*)$");
smatch cm;
regex_search(err, cm, rx);
if (cm.size() < 3)
return err;
return src + ":" + cm[1].str() + ": " + cm[2].str();
};
if (luaL_loadstring(L, str.c_str()) != LUA_OK) {
string err(lua_tostring(L, -1));
throw Lua::LuaError(reformat(err));
}
if (lua_pcall(L, 0, 0, 0) != LUA_OK) {
string err(lua_tostring(L, -1));
throw Lua::LuaError(reformat(err));
}
}
std::mutex TimeoutHook::script_end_times_mtx;
std::unordered_map<uintptr_t, milliseconds> TimeoutHook::script_end_times;
TimeoutHook::TimeoutHook(lua_State *L, milliseconds time)
: Hook(L, lua_timeout_hook, TimeoutHook::NUM_INST)
{
lock_guard<mutex> lock(script_end_times_mtx);
milliseconds ms = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
);
script_end_times[reinterpret_cast<uintptr_t>(L)] = ms + time;
}
TimeoutHook::~TimeoutHook() {
lock_guard<mutex> lock(script_end_times_mtx);
script_end_times.erase(reinterpret_cast<uintptr_t>(L));
}
#define MK_LUA_ERROR_HOOK(_name, _msg) \
static void lua_##_name##_error_hook(lua_State *L, lua_Debug *ar) { \
(void) ar; \
luaL_error(L, _msg); \
}
extern "C" {
MK_LUA_ERROR_HOOK(timeout, "Timeout Error")
}
#undef MK_LUA_ERROR_HOOK
extern "C" void lua_timeout_hook(lua_State *L, lua_Debug *ar) noexcept
{
(void) ar;
lock_guard<mutex> lock(TimeoutHook::script_end_times_mtx);
milliseconds end_time = TimeoutHook::script_end_times[reinterpret_cast<uintptr_t>(L)];
milliseconds now = duration_cast<milliseconds>(
system_clock::now().time_since_epoch()
);
if (now > end_time) {
lua_sethook(L, NULL, 0, 0);
lua_sethook(L, lua_timeout_error_hook, LUA_MASKCOUNT, 1);
}
}
extern "C" int hwk_lua_error_handler_callback(lua_State *L) noexcept
{
lua_Debug ar;
size_t errmsg_sz = 0;
const char *errmsg_c = lua_tolstring(L, -1, &errmsg_sz);
string errmsg(errmsg_c, errmsg_sz);
vector<lua_Debug> traceback;
for (int lv = 0; lua_getstack(L, lv, &ar); lv++) {
lua_getinfo(L, "Sunl", &ar);
traceback.push_back(ar);
}
lua_pushlightuserdata(L, new LuaError(errmsg, traceback));
return 1;
}
/**
* This __gc metamethod is used by LuaObject.
* It is given two upvalues:
* 1. The reference counter.
* 2. The destructor function to use.
*/
extern "C" int hwk_lua_object_destructor_cb(lua_State *L) noexcept
{
void *obj_ref = * (void **) lua_touserdata(L, -1);
atomic<int> *rc = * (atomic<int> **) lua_touserdata(L, lua_upvalueindex(1));
if (--*rc <= 0) {
typedef void (*Destructor)(void*);
void (*destructor)(void*) = * (Destructor *) lua_touserdata(L, lua_upvalueindex(2));
destructor(obj_ref);
delete rc;
}
return 0;
}
std::atomic<uint64_t> id_incr;
}
|
#include "lib.h"
#include <stdio.h>
void sayHi()
{
printf("Hello from dynamic library\n");
}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The LINC Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "txmempool.h"
#include "walletmodel.h"
#include "coincontrol.h"
#include "init.h"
#include "main.h" // For minRelayTxFee
#include "wallet/wallet.h"
#include "darksend.h"
#include "instantx.h"
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <QApplication>
#include <QCheckBox>
#include <QCursor>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QSettings>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
QList<CAmount> CoinControlDialog::payAmounts;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
bool CoinControlDialog::fSubtractFeeFromAmount = false;
CoinControlDialog::CoinControlDialog(const PlatformStyle *platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0),
platformStyle(platformStyle)
{
ui->setupUi(this);
/* Open CSS when configured */
this->setStyleSheet(GUIUtil::loadStyleSheet());
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
contextMenu->addSeparator();
contextMenu->addAction(lockAction);
contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));
// click on header
#if QT_VERSION < 0x050000
ui->treeWidget->header()->setClickable(true);
#else
ui->treeWidget->header()->setSectionsClickable(true);
#endif
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
// Toggle lock state
connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked()));
// change coin control first column label due Qt4 bug.
// see https://github.com/bitcoin/bitcoin/issues/5716
ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString());
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190);
ui->treeWidget->setColumnWidth(COLUMN_PRIVATESEND_ROUNDS, 88);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 80);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100);
ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but don't show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it
ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but don't show it
ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but don't show it
ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but don't show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder);
// restore list mode and sortorder as a convenience feature
QSettings settings;
if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
ui->radioTreeMode->click();
if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
}
CoinControlDialog::~CoinControlDialog()
{
QSettings settings;
settings.setValue("nCoinControlMode", ui->radioListMode->isChecked());
settings.setValue("nCoinControlSortColumn", sortColumn);
settings.setValue("nCoinControlSortOrder", (int)sortOrder);
delete ui;
}
void CoinControlDialog::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel() && model->getAddressTableModel())
{
updateView();
updateLabelLocked();
CoinControlDialog::updateLabels(model, this);
}
}
// helper function str_pad
QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding)
{
while (s.length() < nPadLength)
s = sPadding + s;
return s;
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
{
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked)
{
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
if (state == Qt::Unchecked)
coinControl->UnSelectAll(); // just to be sure
CoinControlDialog::updateLabels(model, this);
}
// Toggle lock state
void CoinControlDialog::buttonToggleLockClicked()
{
QTreeWidgetItem *item;
QString theme = GUIUtil::getThemeName();
// Works in list-mode only
if(ui->radioListMode->isChecked()){
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++){
item = ui->treeWidget->topLevelItem(i);
COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())){
model->unlockCoin(outpt);
item->setDisabled(false);
item->setIcon(COLUMN_CHECKBOX, QIcon());
}
else{
model->lockCoin(outpt);
item->setDisabled(true);
item->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed"));
}
updateLabelLocked();
}
ui->treeWidget->setEnabled(true);
CoinControlDialog::updateLabels(model, this);
}
else{
QMessageBox msgBox;
msgBox.setObjectName("lockMessageBox");
msgBox.setStyleSheet(GUIUtil::loadStyleSheet());
msgBox.setText(tr("Please switch to \"List mode\" to use this function."));
msgBox.exec();
}
}
// context menu
void CoinControlDialog::showMenu(const QPoint &point)
{
QTreeWidgetItem *item = ui->treeWidget->itemAt(point);
if(item)
{
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
{
lockAction->setEnabled(false);
unlockAction->setEnabled(true);
}
else
{
lockAction->setEnabled(true);
unlockAction->setEnabled(false);
}
}
else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
lockAction->setEnabled(false);
unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT)));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
void CoinControlDialog::lockCoin()
{
QString theme = GUIUtil::getThemeName();
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed"));
updateLabelLocked();
}
// context menu action: unlock coin
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, ""));
}
// copy label "Priority" to clipboard
void CoinControlDialog::clipboardPriority()
{
GUIUtil::setClipboard(ui->labelCoinControlPriority->text());
}
// copy label "Dust" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder);
}
else
{
logicalIndex = getMappedColumn(logicalIndex, false);
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else
{
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else {
coinControl->Select(outpt);
CTxIn txin = CTxIn(outpt);
int nRounds = pwalletMain->GetInputPrivateSendRounds(txin);
if (coinControl->fUsePrivateSend && nRounds < nPrivateSendRounds) {
QMessageBox::warning(this, windowTitle(),
tr("Non-anonymized input selected. <b>PrivateSend will be disabled.</b><br><br>If you still want to use PrivateSend, please deselect all non-nonymized inputs first and then check PrivateSend checkbox again."),
QMessageBox::Ok, QMessageBox::Ok);
coinControl->fUsePrivateSend = false;
}
}
// selection changed -> update labels
if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
}
// todo: this is a temporary qt5 fix: when clicking a parent node in tree mode, the parent node
// including all children are partially selected. But the parent node should be fully selected
// as well as the children. Children should never be partially selected in the first place.
// Please remove this ugly fix, once the bug is solved upstream.
#if QT_VERSION >= 0x050000
else if (column == COLUMN_CHECKBOX && item->childCount() > 0)
{
if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
item->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
#endif
}
// return human readable label for priority number
QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEstimatePriority)
{
double dPriorityMedium = mempoolEstimatePriority;
if (dPriorityMedium <= 0)
dPriorityMedium = AllowFreeThreshold(); // not enough data, back to hard-coded
if (dPriority / 1000000 > dPriorityMedium) return tr("highest");
else if (dPriority / 100000 > dPriorityMedium) return tr("higher");
else if (dPriority / 10000 > dPriorityMedium) return tr("high");
else if (dPriority / 1000 > dPriorityMedium) return tr("medium-high");
else if (dPriority > dPriorityMedium) return tr("medium");
else if (dPriority * 10 > dPriorityMedium) return tr("low-medium");
else if (dPriority * 100 > dPriorityMedium) return tr("low");
else if (dPriority * 1000 > dPriorityMedium) return tr("lower");
else return tr("lowest");
}
// shows count of locked unspent outputs
void CoinControlDialog::updateLabelLocked()
{
std::vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0)
{
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
}
else ui->labelLocked->setVisible(false);
}
void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
if (!model)
return;
// nPayAmount
CAmount nPayAmount = 0;
bool fDust = false;
CMutableTransaction txDummy;
Q_FOREACH(const CAmount &amount, CoinControlDialog::payAmounts)
{
nPayAmount += amount;
if (amount > 0)
{
CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
if (txout.IsDust(::minRelayTxFee))
fDust = true;
}
}
QString sPriorityLabel = tr("none");
CAmount nAmount = 0;
CAmount nPayFee = 0;
CAmount nAfterFee = 0;
CAmount nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
double dPriority = 0;
double dPriorityInputs = 0;
unsigned int nQuantity = 0;
int nQuantityUncompressed = 0;
bool fAllowFree = false;
std::vector<COutPoint> vCoinControl;
std::vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
BOOST_FOREACH(const COutput& out, vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
if (model->isSpent(outpt))
{
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->vout[out.i].nValue;
// Priority
dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
// Bytes
CTxDestination address;
if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&address);
if (keyid && model->getPubKey(*keyid, pubkey))
{
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
if (!pubkey.IsCompressed())
nQuantityUncompressed++;
}
else
nBytesInputs += 148; // in all error cases, simply assume 148 here
}
else nBytesInputs += 148;
// Add inputs to calculate InstantSend Fee later
if(coinControl->fUseInstantSend)
txDummy.vin.push_back(CTxIn());
}
// calculation
if (nQuantity > 0)
{
// Bytes
nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here
// Priority
double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget);
dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority)
sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority);
// in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate
if (CoinControlDialog::fSubtractFeeFromAmount)
if (nAmount - nPayAmount == 0)
nBytes -= 34;
// Fee
nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
if (nPayFee > 0 && coinControl->nMinimumTotalFee > nPayFee)
nPayFee = coinControl->nMinimumTotalFee;
// InstantSend Fee
if (coinControl->fUseInstantSend) nPayFee = std::max(nPayFee, CTxLockRequest(txDummy).GetMinFee());
// Allow free? (require at least hard-coded threshold and default to that if no estimate)
double dPriorityNeeded = std::max(mempoolEstimatePriority, AllowFreeThreshold());
fAllowFree = (dPriority >= dPriorityNeeded);
if (fSendFreeTransactions)
if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
nPayFee = 0;
if (nPayAmount > 0)
{
nChange = nAmount - nPayAmount;
if (!CoinControlDialog::fSubtractFeeFromAmount)
nChange -= nPayFee;
// PrivateSend Fee = overpay
if(coinControl->fUsePrivateSend && nChange > 0)
{
nPayFee += nChange;
nChange = 0;
}
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < MIN_CHANGE)
{
CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0));
if (txout.IsDust(::minRelayTxFee))
{
if (CoinControlDialog::fSubtractFeeFromAmount) // dust-change will be raised until no dust
nChange = txout.GetDustThreshold(::minRelayTxFee);
else
{
nPayFee += nChange;
nChange = 0;
}
}
}
if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount)
nBytes -= 34;
}
// after fee
nAfterFee = nAmount - nPayFee;
if (nAfterFee < 0)
nAfterFee = 0;
}
// actually update labels
int nDisplayUnit = BitcoinUnits::LINC;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity");
QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount");
QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee");
QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee");
QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes");
QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority");
QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
// enable/disable "dust" and "change"
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes
l6->setText(sPriorityLabel); // Priority
l7->setText(fDust ? tr("yes") : tr("no")); // Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
if (nPayFee > 0 && (coinControl->nMinimumTotalFee < nPayFee))
{
l3->setText(ASYMP_UTF8 + l3->text());
l4->setText(ASYMP_UTF8 + l4->text());
if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount)
l8->setText(ASYMP_UTF8 + l8->text());
}
// turn labels "red"
l5->setStyleSheet((nBytes >= MAX_FREE_TRANSACTION_CREATE_SIZE) ? "color:red;" : "");// Bytes >= 1000
l6->setStyleSheet((dPriority > 0 && !fAllowFree) ? "color:red;" : ""); // Priority < "medium"
l7->setStyleSheet((fDust) ? "color:red;" : ""); // Dust = "yes"
// tool tips
QString toolTip1 = tr("This label turns red if the transaction size is greater than 1000 bytes.") + "<br /><br />";
toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000))) + "<br /><br />";
toolTip1 += tr("Can vary +/- 1 byte per input.");
QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />";
toolTip2 += tr("This label turns red if the priority is smaller than \"medium\".") + "<br /><br />";
toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000)));
QString toolTip3 = tr("This label turns red if any recipient receives an amount smaller than %1.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, ::minRelayTxFee.GetFee(546)));
// how many satoshis the estimated fee can vary per byte we guess wrong
double dFeeVary;
if (payTxFee.GetFeePerK() > 0)
dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), payTxFee.GetFeePerK()) / 1000;
else {
dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), mempool.estimateSmartFee(nTxConfirmTarget).GetFeePerK()) / 1000;
}
QString toolTip4 = tr("Can vary +/- %1 duff(s) per input.").arg(dFeeVary);
l3->setToolTip(toolTip4);
l4->setToolTip(toolTip4);
l5->setToolTip(toolTip1);
l6->setToolTip(toolTip2);
l7->setToolTip(toolTip3);
l8->setToolTip(toolTip4);
dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip());
dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip());
dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip());
dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip());
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip());
// Insufficient funds
QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel())
return;
bool treeMode = ui->radioTreeMode->isChecked();
QString theme = GUIUtil::getThemeName();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget);
std::map<QString, std::vector<COutput> > mapCoins;
model->listCoins(mapCoins);
BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) {
QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
if (treeMode)
{
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
itemWalletAddress->setToolTip(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
itemWalletAddress->setToolTip(COLUMN_ADDRESS, sWalletAddress);
}
CAmount nSum = 0;
double dPrioritySum = 0;
int nChildren = 0;
int nInputSum = 0;
BOOST_FOREACH(const COutput& out, coins.second) {
int nInputSize = 0;
nSum += out.tx->vout[out.i].nValue;
nChildren++;
QTreeWidgetItem *itemOutput;
if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress);
else itemOutput = new QTreeWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress))
{
sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString());
// if listMode or change => show linc address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
itemOutput->setToolTip(COLUMN_ADDRESS, sAddress);
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&outputAddress);
if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed())
nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes)
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
}
else if (!treeMode)
{
QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.isEmpty())
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue));
itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setToolTip(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setText(COLUMN_DATE_INT64, strPad(QString::number(out.tx->GetTxTime()), 20, " "));
// PrivateSend rounds
CTxIn txin = CTxIn(out.tx->GetHash(), out.i);
int nRounds = pwalletMain->GetInputPrivateSendRounds(txin);
if (nRounds >= 0 || fDebug) itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, strPad(QString::number(nRounds), 11, " "));
else itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, strPad(QString(tr("n/a")), 11, " "));
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " "));
// priority
double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10
itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority));
itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPriority), 20, " "));
dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1);
nInputSum += nInputSize;
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex()));
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
if (model->isLockedCoin(txhash, out.i))
{
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed"));
}
// set checkbox
if (coinControl->IsSelected(txhash, out.i))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode)
{
dPrioritySum = dPrioritySum / (nInputSum + 78);
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " "));
itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum, mempoolEstimatePriority));
itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPrioritySum), 20, " "));
}
}
// expand all partially selected
if (treeMode)
{
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
}
|
#ifndef CALCULATOR_HPP_
#define CALCULATOR_HPP_
#include "bookkeeper.hpp"
#include "parser.hpp"
class Calculator {
public:
void StartCalculation(const std::string incoming_expression);
private:
Bookkeeper bookkeeper_;
Parser parser_;
};
#endif // CALCULATOR_HPP_
|
#include "sparta/utils/LockedValue.hpp"
#include "sparta/utils/ValidValue.hpp"
#include "sparta/utils/SpartaTester.hpp"
#include <iostream>
TEST_INIT;
#define PRINT_ENTER_TEST \
std::cout << std::endl; \
std::cout << "*************************************************************" \
<< "*** Beginning '" << __FUNCTION__ << "'" \
<< "*************************************************************" \
<< std::endl;
namespace {
template <typename T>
bool lockedValueCompare(
sparta::utils::LockedValue<sparta::utils::ValidValue<T>> & lhs,
sparta::utils::ValidValue<T> & rhs)
{
return (lhs.getValue() == rhs);
}
}
void testLockedValue(){
PRINT_ENTER_TEST;
namespace ru = sparta::utils;
uint16_t data_1 = uint16_t();
uint32_t data_2 = 32;
uint64_t data_3 = 64;
uint64_t data_4 = 128;
double data_5 = 3.14;
uint32_t data_6 = 512;
ru::LockedValue<uint16_t> lv_1;
ru::LockedValue<uint32_t> lv_2(data_2);
ru::LockedValue<uint64_t> lv_3(data_3, false);
ru::LockedValue<uint64_t> lv_4(data_4, true);
ru::LockedValue<double> lv_5;
ru::LockedValue<uint32_t> lv_6 = {data_6, false};
EXPECT_NOTHROW(lv_5.lock());
EXPECT_NOTHROW(lv_5.lock());
EXPECT_TRUE(lv_5.isLocked());
EXPECT_NOTHROW(lv_5.getValue());
EXPECT_THROW(lv_5 = data_5);
EXPECT_FALSE(lv_1.isLocked());
EXPECT_FALSE(lv_2.isLocked());
EXPECT_FALSE(lv_3.isLocked());
EXPECT_TRUE(lv_4.isLocked());
EXPECT_FALSE(lv_6.isLocked());
EXPECT_NOTHROW(lv_1.getValue());
EXPECT_NOTHROW(lv_2.getValue());
EXPECT_NOTHROW(lv_3.getValue());
EXPECT_NOTHROW(lv_4.getValue());
EXPECT_NOTHROW(lv_6.getValue());
EXPECT_EQUAL(lv_1.getValue(), data_1);
EXPECT_EQUAL(lv_2.getValue(), data_2);
EXPECT_EQUAL(lv_3.getValue(), data_3);
EXPECT_EQUAL(lv_4.getValue(), data_4);
EXPECT_EQUAL(lv_6.getValue(), data_6);
EXPECT_EQUAL(lv_1, data_1);
EXPECT_EQUAL(lv_2, data_2);
EXPECT_EQUAL(lv_3, data_3);
EXPECT_EQUAL(lv_4, data_4);
EXPECT_EQUAL(lv_6, data_6);
data_1 = 4;
data_2 = 8;
data_3 = 16;
data_6 = 256;
EXPECT_NOTHROW(lv_1 = data_1);
EXPECT_NOTHROW(lv_2 = data_2);
EXPECT_NOTHROW(lv_3 = data_3);
EXPECT_THROW(lv_4 = data_4);
EXPECT_NOTHROW(lv_6 = data_6);
EXPECT_EQUAL(lv_1.getValue(), data_1);
EXPECT_EQUAL(lv_2.getValue(), data_2);
EXPECT_EQUAL(lv_3.getValue(), data_3);
EXPECT_EQUAL(lv_4.getValue(), data_4);
EXPECT_EQUAL(lv_6.getValue(), data_6);
EXPECT_NOTHROW(lv_3.lock());
EXPECT_NOTHROW(lv_6.lock());
EXPECT_TRUE(lv_6.isLocked());
EXPECT_THROW(lv_6 = data_6);
EXPECT_FALSE(lv_1.isLocked());
EXPECT_TRUE(lv_3.isLocked());
EXPECT_TRUE(lv_3.isLocked());
EXPECT_TRUE(lv_4.isLocked());
EXPECT_THROW(lv_3 = data_3);
EXPECT_NOTHROW(lv_3.lock());
data_2 = 12;
EXPECT_NOTHROW(lv_2.setAndLock(data_2));
EXPECT_EQUAL(lv_2, data_2);
EXPECT_EQUAL(lv_2.getValue(), data_2);
EXPECT_TRUE(lv_2.isLocked());
EXPECT_THROW(lv_2 = data_2);
EXPECT_THROW(lv_2.setAndLock(data_2));
data_1 = 512;
EXPECT_NOTHROW(lv_1 = data_1);
EXPECT_FALSE(lv_1.isLocked());
EXPECT_TRUE(lv_1 == data_1);
data_1 = 256;
EXPECT_NOTHROW(lv_1.setAndLock(data_1));
EXPECT_TRUE(lv_1 == data_1);
EXPECT_TRUE(lv_1.isLocked());
EXPECT_THROW(lv_1.setAndLock(data_1));
EXPECT_THROW(lv_1 = data_1);
EXPECT_EQUAL(lv_1, data_1);
EXPECT_EQUAL(lv_1.getValue(), data_1);
}
void testLockedValidValue(){
PRINT_ENTER_TEST;
namespace ru = sparta::utils;
ru::ValidValue<uint16_t> data_1;
ru::ValidValue<uint32_t> data_2 = 32;
ru::ValidValue<uint64_t> data_3 = 64;
ru::ValidValue<uint64_t> data_4 = 128;
ru::ValidValue<double> data_5 = 3.14;
ru::LockedValue<ru::ValidValue<uint16_t>> lv_1;
ru::LockedValue<ru::ValidValue<uint32_t>> lv_2(data_2);
ru::LockedValue<ru::ValidValue<uint64_t>> lv_3(data_3, false);
ru::LockedValue<ru::ValidValue<uint64_t>> lv_4(data_4, true);
ru::LockedValue<ru::ValidValue<double>> lv_5;
EXPECT_NOTHROW(lv_5.lock());
EXPECT_NOTHROW(lv_5.lock());
EXPECT_TRUE(lv_5.isLocked());
EXPECT_NOTHROW(lv_5.getValue());
EXPECT_THROW(lv_5 = data_5);
EXPECT_FALSE(lv_1.isLocked());
EXPECT_FALSE(lv_2.isLocked());
EXPECT_FALSE(lv_3.isLocked());
EXPECT_TRUE(lv_4.isLocked());
EXPECT_NOTHROW(lv_1.getValue());
EXPECT_THROW(lv_1.getValue().getValue());
EXPECT_NOTHROW(lv_2.getValue());
EXPECT_NOTHROW(lv_3.getValue());
EXPECT_NOTHROW(lv_4.getValue());
EXPECT_THROW(lockedValueCompare(lv_1, data_1));
EXPECT_EQUAL(lv_2.getValue(), data_2);
EXPECT_EQUAL(lv_3.getValue(), data_3);
EXPECT_EQUAL(lv_4.getValue(), data_4);
EXPECT_THROW(lockedValueCompare(lv_1, data_1));
EXPECT_EQUAL(lv_2, data_2);
EXPECT_EQUAL(lv_3, data_3);
EXPECT_EQUAL(lv_4, data_4);
data_1 = 4;
data_2 = 8;
data_3 = 16;
EXPECT_NOTHROW(lv_1 = data_1);
EXPECT_NOTHROW(lv_2 = data_2);
EXPECT_NOTHROW(lv_3 = data_3);
EXPECT_THROW(lv_4 = data_4);
EXPECT_EQUAL(lv_1.getValue(), data_1);
EXPECT_EQUAL(lv_2.getValue(), data_2);
EXPECT_EQUAL(lv_3.getValue(), data_3);
EXPECT_EQUAL(lv_4.getValue(), data_4);
EXPECT_NOTHROW(lv_3.lock());
EXPECT_FALSE(lv_1.isLocked());
EXPECT_TRUE(lv_3.isLocked());
EXPECT_TRUE(lv_3.isLocked());
EXPECT_TRUE(lv_4.isLocked());
EXPECT_THROW(lv_3 = data_3);
EXPECT_NOTHROW(lv_3.lock());
data_2 = 12;
EXPECT_NOTHROW(lv_2.setAndLock(data_2));
EXPECT_EQUAL(lv_2, data_2);
EXPECT_EQUAL(lv_2.getValue(), data_2);
EXPECT_TRUE(lv_2.isLocked());
EXPECT_THROW(lv_2 = data_2);
EXPECT_THROW(lv_2.setAndLock(data_2));
data_1 = 512;
EXPECT_NOTHROW(lv_1 = data_1);
EXPECT_FALSE(lv_1.isLocked());
EXPECT_TRUE(lv_1 == data_1);
data_1 = 256;
EXPECT_NOTHROW(lv_1.setAndLock(data_1));
EXPECT_TRUE(lv_1 == data_1);
EXPECT_TRUE(lv_1.isLocked());
EXPECT_THROW(lv_1.setAndLock(data_1));
EXPECT_THROW(lv_1 = data_1);
EXPECT_EQUAL(lv_1, data_1);
EXPECT_EQUAL(lv_1.getValue(), data_1);
}
int main(){
testLockedValue();
testLockedValidValue();
REPORT_ERROR;
return ERROR_CODE;
}
|
/* replace a given class value with NAN */
#include"misc.h"
int main(int argc, char ** argv){
if(argc < 2) err("class_replace_nan [input binary (classification) file name]");
int start_0 = argc > 2;
str fn(argv[1]); // input file name
str ofn(fn + str("_recode.bin"));
str ohfn(fn +str("_recode.hdr"));
str hfn(hdr_fn(fn)); // auto-detect header file name
size_t nrow, ncol, nband, np, i, j;
hread(hfn, nrow, ncol, nband); // read header
np = nrow * ncol;
if(nband != 1) err("this program defines results for 1-band images");
// read data into float array
float * dat = bread(fn, nrow, ncol, nband);
for0(i, np){
if(dat[i] == 0.)
dat[i] = NAN;
}
hwrite(ohfn, nrow, ncol, 1); // write header
FILE * f = fopen(ofn.c_str(), "wb");
fwrite(dat, sizeof(float), np, f);
fclose(f);
free(dat);
return 0;
}
|
//===-- BackgroundIndexLoader.cpp - ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "index/BackgroundIndexLoader.h"
#include "GlobalCompilationDatabase.h"
#include "Logger.h"
#include "Path.h"
#include "index/Background.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/Path.h"
#include <string>
#include <utility>
#include <vector>
namespace clang {
namespace clangd {
namespace {
/// A helper class to cache BackgroundIndexStorage operations and keep the
/// inverse dependency mapping.
class BackgroundIndexLoader {
public:
BackgroundIndexLoader(BackgroundIndexStorage::Factory &IndexStorageFactory)
: IndexStorageFactory(IndexStorageFactory) {}
/// Load the shards for \p MainFile and all of its dependencies.
void load(PathRef MainFile);
/// Consumes the loader and returns all shards.
std::vector<LoadedShard> takeResult() &&;
private:
/// Returns the Shard for \p StartSourceFile from cache or loads it from \p
/// Storage. Also returns paths for dependencies of \p StartSourceFile if it
/// wasn't cached yet.
std::pair<const LoadedShard &, std::vector<Path>>
loadShard(PathRef StartSourceFile, PathRef DependentTU);
/// Cache for Storage lookups.
llvm::StringMap<LoadedShard> LoadedShards;
BackgroundIndexStorage::Factory &IndexStorageFactory;
};
std::pair<const LoadedShard &, std::vector<Path>>
BackgroundIndexLoader::loadShard(PathRef StartSourceFile, PathRef DependentTU) {
auto It = LoadedShards.try_emplace(StartSourceFile);
LoadedShard &LS = It.first->getValue();
std::vector<Path> Edges = {};
// Return the cached shard.
if (!It.second)
return {LS, Edges};
LS.AbsolutePath = StartSourceFile.str();
LS.DependentTU = DependentTU;
BackgroundIndexStorage *Storage = IndexStorageFactory(LS.AbsolutePath);
auto Shard = Storage->loadShard(StartSourceFile);
if (!Shard || !Shard->Sources) {
vlog("Failed to load shard: {0}", StartSourceFile);
return {LS, Edges};
}
LS.Shard = std::move(Shard);
for (const auto &It : *LS.Shard->Sources) {
auto AbsPath = URI::resolve(It.getKey(), StartSourceFile);
if (!AbsPath) {
elog("Failed to resolve URI: {0}", AbsPath.takeError());
continue;
}
// A shard contains only edges for non main-file sources.
if (*AbsPath != StartSourceFile) {
Edges.push_back(*AbsPath);
continue;
}
// Fill in shard metadata.
const IncludeGraphNode &IGN = It.getValue();
LS.Digest = IGN.Digest;
LS.CountReferences = IGN.Flags & IncludeGraphNode::SourceFlag::IsTU;
LS.HadErrors = IGN.Flags & IncludeGraphNode::SourceFlag::HadErrors;
}
assert(LS.Digest != FileDigest{{0}} && "Digest is empty?");
return {LS, Edges};
}
void BackgroundIndexLoader::load(PathRef MainFile) {
llvm::StringSet<> InQueue;
// Following containers points to strings inside InQueue.
std::queue<PathRef> ToVisit;
InQueue.insert(MainFile);
ToVisit.push(MainFile);
while (!ToVisit.empty()) {
PathRef SourceFile = ToVisit.front();
ToVisit.pop();
auto ShardAndEdges = loadShard(SourceFile, MainFile);
for (PathRef Edge : ShardAndEdges.second) {
auto It = InQueue.insert(Edge);
if (It.second)
ToVisit.push(It.first->getKey());
}
}
}
std::vector<LoadedShard> BackgroundIndexLoader::takeResult() && {
std::vector<LoadedShard> Result;
Result.reserve(LoadedShards.size());
for (auto &It : LoadedShards)
Result.push_back(std::move(It.getValue()));
return Result;
}
} // namespace
std::vector<LoadedShard>
loadIndexShards(llvm::ArrayRef<Path> MainFiles,
BackgroundIndexStorage::Factory &IndexStorageFactory,
const GlobalCompilationDatabase &CDB) {
BackgroundIndexLoader Loader(IndexStorageFactory);
for (llvm::StringRef MainFile : MainFiles) {
assert(llvm::sys::path::is_absolute(MainFile));
Loader.load(MainFile);
}
return std::move(Loader).takeResult();
}
} // namespace clangd
} // namespace clang
|
/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <vector>
#include <memory>
#include <cmath>
#include "GLTFLoader.hpp"
#include "MapHelper.hpp"
#include "CommonlyUsedStates.h"
#include "DataBlobImpl.hpp"
#include "Image.h"
#include "FileSystem.hpp"
#include "FileWrapper.hpp"
#include "GraphicsAccessories.hpp"
#define TINYGLTF_IMPLEMENTATION
#define TINYGLTF_NO_STB_IMAGE
#define TINYGLTF_NO_STB_IMAGE_WRITE
#include "../../ThirdParty/tinygltf/tiny_gltf.h"
namespace Diligent
{
namespace GLTF
{
RefCntAutoPtr<ITexture> TextureFromGLTFImage(IRenderDevice* pDevice,
IDeviceContext* pCtx,
const tinygltf::Image& gltfimage,
ISampler* pSampler,
float AlphaCutoff)
{
if (gltfimage.image.empty())
{
LOG_ERROR_AND_THROW("Failed to create texture for image ", gltfimage.uri, ": no data available.");
}
if (gltfimage.width <= 0 || gltfimage.height <= 0 || gltfimage.component <= 0)
{
LOG_ERROR_AND_THROW("Failed to create texture for image ", gltfimage.uri, ": invalid parameters.");
}
std::vector<Uint8> RGBA;
const Uint8* pTextureData = nullptr;
if (gltfimage.component == 3)
{
RGBA.resize(gltfimage.width * gltfimage.height * 4);
// Due to depressing performance of iterators in debug MSVC we have to use raw pointers here
const auto* rgb = gltfimage.image.data();
auto* rgba = RGBA.data();
for (int i = 0; i < gltfimage.width * gltfimage.height; ++i)
{
rgba[0] = rgb[0];
rgba[1] = rgb[1];
rgba[2] = rgb[2];
rgba[3] = 255;
rgba += 4;
rgb += 3;
}
VERIFY_EXPR(rgb == gltfimage.image.data() + gltfimage.image.size());
VERIFY_EXPR(rgba == RGBA.data() + RGBA.size());
pTextureData = RGBA.data();
}
else if (gltfimage.component == 4)
{
pTextureData = gltfimage.image.data();
if (AlphaCutoff > 0)
{
// Remap alpha channel using the following formula to improve mip maps:
//
// A_new = max(A_old; 1/3 * A_old + 2/3 * CutoffThreshold)
//
// https://asawicki.info/articles/alpha_test.php5
VERIFY_EXPR(AlphaCutoff > 0 && AlphaCutoff <= 1);
AlphaCutoff *= 255.f;
RGBA.resize(gltfimage.width * gltfimage.height * 4);
// Due to depressing performance of iterators in debug MSVC we have to use raw pointers here
const auto* src = gltfimage.image.data();
auto* dst = RGBA.data();
for (int i = 0; i < gltfimage.width * gltfimage.height; ++i)
{
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = std::max(src[3], static_cast<Uint8>(std::min(1.f / 3.f * src[3] + 2.f / 3.f * AlphaCutoff, 255.f)));
src += 4;
dst += 4;
}
VERIFY_EXPR(src == gltfimage.image.data() + gltfimage.image.size());
VERIFY_EXPR(dst == RGBA.data() + RGBA.size());
pTextureData = RGBA.data();
}
}
else
{
UNEXPECTED("Unexpected number of color components in gltf image: ", gltfimage.component);
}
TextureDesc TexDesc;
TexDesc.Name = "GLTF Texture";
TexDesc.Type = RESOURCE_DIM_TEX_2D;
TexDesc.Usage = USAGE_DEFAULT;
TexDesc.BindFlags = BIND_SHADER_RESOURCE;
TexDesc.Width = gltfimage.width;
TexDesc.Height = gltfimage.height;
TexDesc.Format = TEX_FORMAT_RGBA8_UNORM;
TexDesc.MipLevels = 0;
TexDesc.MiscFlags = MISC_TEXTURE_FLAG_GENERATE_MIPS;
RefCntAutoPtr<ITexture> pTexture;
pDevice->CreateTexture(TexDesc, nullptr, &pTexture);
Box UpdateBox;
UpdateBox.MaxX = TexDesc.Width;
UpdateBox.MaxY = TexDesc.Height;
TextureSubResData Level0Data(pTextureData, gltfimage.width * 4);
pCtx->UpdateTexture(pTexture, 0, 0, UpdateBox, Level0Data, RESOURCE_STATE_TRANSITION_MODE_NONE, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
pTexture->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE)->SetSampler(pSampler);
return pTexture;
}
Mesh::Mesh(IRenderDevice* pDevice, const float4x4& matrix)
{
Transforms.matrix = matrix;
}
void Mesh::SetBoundingBox(const float3& min, const float3& max)
{
BB.Min = min;
BB.Max = max;
IsValidBB = true;
}
float4x4 Node::LocalMatrix() const
{
return Matrix * float4x4::Scale(Scale) * Rotation.ToMatrix() * float4x4::Translation(Translation);
}
float4x4 Node::GetMatrix() const
{
auto mat = LocalMatrix();
for (auto* p = Parent; p != nullptr; p = p->Parent)
{
mat = mat * p->LocalMatrix();
}
return mat;
}
void Node::Update()
{
if (_Mesh)
{
_Mesh->Transforms.matrix = GetMatrix();
if (_Skin != nullptr)
{
// Update join matrices
auto InverseTransform = _Mesh->Transforms.matrix.Inverse(); // TODO: do not use inverse tranform here
size_t numJoints = std::min((uint32_t)_Skin->Joints.size(), Uint32{Mesh::TransformData::MaxNumJoints});
for (size_t i = 0; i < numJoints; i++)
{
auto* JointNode = _Skin->Joints[i];
auto JointMat = _Skin->InverseBindMatrices[i] * JointNode->GetMatrix() * InverseTransform;
_Mesh->Transforms.jointMatrix[i] = JointMat;
}
_Mesh->Transforms.jointcount = static_cast<int>(numJoints);
}
}
for (auto& child : Children)
{
child->Update();
}
}
Model::Model(IRenderDevice* pDevice,
IDeviceContext* pContext,
const std::string& filename,
TextureCacheType* pTextureCache)
{
LoadFromFile(pDevice, pContext, filename, pTextureCache);
}
void Model::LoadNode(IRenderDevice* pDevice,
Node* parent,
const tinygltf::Node& gltf_node,
uint32_t nodeIndex,
const tinygltf::Model& gltf_model,
std::vector<uint32_t>& indexBuffer,
std::vector<VertexAttribs0>& vertexData0,
std::vector<VertexAttribs1>& vertexData1)
{
std::unique_ptr<Node> NewNode(new Node{});
NewNode->Index = nodeIndex;
NewNode->Parent = parent;
NewNode->Name = gltf_node.name;
NewNode->SkinIndex = gltf_node.skin;
NewNode->Matrix = float4x4::Identity();
// Generate local node matrix
//float3 Translation;
if (gltf_node.translation.size() == 3)
{
NewNode->Translation = float3::MakeVector(gltf_node.translation.data());
}
if (gltf_node.rotation.size() == 4)
{
NewNode->Rotation.q = float4::MakeVector(gltf_node.rotation.data());
//NewNode->rotation = glm::mat4(q);
}
if (gltf_node.scale.size() == 3)
{
NewNode->Scale = float3::MakeVector(gltf_node.scale.data());
}
if (gltf_node.matrix.size() == 16)
{
NewNode->Matrix = float4x4::MakeMatrix(gltf_node.matrix.data());
}
// Node with children
if (gltf_node.children.size() > 0)
{
for (size_t i = 0; i < gltf_node.children.size(); i++)
{
LoadNode(pDevice, NewNode.get(), gltf_model.nodes[gltf_node.children[i]], gltf_node.children[i], gltf_model, indexBuffer, vertexData0, vertexData1);
}
}
// Node contains mesh data
if (gltf_node.mesh > -1)
{
const tinygltf::Mesh& gltf_mesh = gltf_model.meshes[gltf_node.mesh];
std::unique_ptr<Mesh> NewMesh(new Mesh(pDevice, NewNode->Matrix));
for (size_t j = 0; j < gltf_mesh.primitives.size(); j++)
{
const tinygltf::Primitive& primitive = gltf_mesh.primitives[j];
uint32_t indexStart = static_cast<uint32_t>(indexBuffer.size());
uint32_t vertexStart = static_cast<uint32_t>(vertexData0.size());
VERIFY_EXPR(vertexData1.empty() || vertexData0.size() == vertexData1.size());
uint32_t indexCount = 0;
uint32_t vertexCount = 0;
float3 PosMin;
float3 PosMax;
bool hasSkin = false;
bool hasIndices = primitive.indices > -1;
// Vertices
{
const float* bufferPos = nullptr;
const float* bufferNormals = nullptr;
const float* bufferTexCoordSet0 = nullptr;
const float* bufferTexCoordSet1 = nullptr;
const uint16_t* bufferJoints = nullptr;
const float* bufferWeights = nullptr;
auto position_it = primitive.attributes.find("POSITION");
VERIFY(position_it != primitive.attributes.end(), "Position attribute is required");
const tinygltf::Accessor& posAccessor = gltf_model.accessors[position_it->second];
const tinygltf::BufferView& posView = gltf_model.bufferViews[posAccessor.bufferView];
bufferPos = reinterpret_cast<const float*>(&(gltf_model.buffers[posView.buffer].data[posAccessor.byteOffset + posView.byteOffset]));
PosMin =
float3 //
{
static_cast<float>(posAccessor.minValues[0]),
static_cast<float>(posAccessor.minValues[1]),
static_cast<float>(posAccessor.minValues[2]) //
};
PosMax =
float3 //
{
static_cast<float>(posAccessor.maxValues[0]),
static_cast<float>(posAccessor.maxValues[1]),
static_cast<float>(posAccessor.maxValues[2]) //
};
vertexCount = static_cast<uint32_t>(posAccessor.count);
if (primitive.attributes.find("NORMAL") != primitive.attributes.end())
{
const tinygltf::Accessor& normAccessor = gltf_model.accessors[primitive.attributes.find("NORMAL")->second];
const tinygltf::BufferView& normView = gltf_model.bufferViews[normAccessor.bufferView];
bufferNormals = reinterpret_cast<const float*>(&(gltf_model.buffers[normView.buffer].data[normAccessor.byteOffset + normView.byteOffset]));
}
if (primitive.attributes.find("TEXCOORD_0") != primitive.attributes.end())
{
const tinygltf::Accessor& uvAccessor = gltf_model.accessors[primitive.attributes.find("TEXCOORD_0")->second];
const tinygltf::BufferView& uvView = gltf_model.bufferViews[uvAccessor.bufferView];
bufferTexCoordSet0 = reinterpret_cast<const float*>(&(gltf_model.buffers[uvView.buffer].data[uvAccessor.byteOffset + uvView.byteOffset]));
}
if (primitive.attributes.find("TEXCOORD_1") != primitive.attributes.end())
{
const tinygltf::Accessor& uvAccessor = gltf_model.accessors[primitive.attributes.find("TEXCOORD_1")->second];
const tinygltf::BufferView& uvView = gltf_model.bufferViews[uvAccessor.bufferView];
bufferTexCoordSet1 = reinterpret_cast<const float*>(&(gltf_model.buffers[uvView.buffer].data[uvAccessor.byteOffset + uvView.byteOffset]));
}
// Skinning
// Joints
if (primitive.attributes.find("JOINTS_0") != primitive.attributes.end())
{
const tinygltf::Accessor& jointAccessor = gltf_model.accessors[primitive.attributes.find("JOINTS_0")->second];
const tinygltf::BufferView& jointView = gltf_model.bufferViews[jointAccessor.bufferView];
bufferJoints = reinterpret_cast<const uint16_t*>(&(gltf_model.buffers[jointView.buffer].data[jointAccessor.byteOffset + jointView.byteOffset]));
}
if (primitive.attributes.find("WEIGHTS_0") != primitive.attributes.end())
{
const tinygltf::Accessor& uvAccessor = gltf_model.accessors[primitive.attributes.find("WEIGHTS_0")->second];
const tinygltf::BufferView& uvView = gltf_model.bufferViews[uvAccessor.bufferView];
bufferWeights = reinterpret_cast<const float*>(&(gltf_model.buffers[uvView.buffer].data[uvAccessor.byteOffset + uvView.byteOffset]));
}
hasSkin = (bufferJoints != nullptr && bufferWeights != nullptr);
for (size_t v = 0; v < posAccessor.count; v++)
{
VertexAttribs0 vert0{};
vert0.pos = float4(float3::MakeVector(&bufferPos[v * 3]), 1.0f);
// clang-format off
vert0.normal = bufferNormals != nullptr ? normalize(float3::MakeVector(&bufferNormals[v * 3])) : float3{};
vert0.uv0 = bufferTexCoordSet0 != nullptr ? float2::MakeVector(&bufferTexCoordSet0[v * 2]) : float2{};
vert0.uv1 = bufferTexCoordSet1 != nullptr ? float2::MakeVector(&bufferTexCoordSet1[v * 2]) : float2{};
// clang-format on
vertexData0.push_back(vert0);
VertexAttribs1 vert1{};
if (hasSkin)
{
vert1.joint0 = float4::MakeVector(&bufferJoints[v * 4]);
vert1.weight0 = float4::MakeVector(&bufferWeights[v * 4]);
}
vertexData1.push_back(vert1);
}
}
// Indices
if (hasIndices)
{
const tinygltf::Accessor& accessor = gltf_model.accessors[primitive.indices > -1 ? primitive.indices : 0];
const tinygltf::BufferView& bufferView = gltf_model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltf_model.buffers[bufferView.buffer];
indexCount = static_cast<uint32_t>(accessor.count);
const void* dataPtr = &(buffer.data[accessor.byteOffset + bufferView.byteOffset]);
switch (accessor.componentType)
{
case TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT:
{
const uint32_t* buf = static_cast<const uint32_t*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
indexBuffer.push_back(buf[index] + vertexStart);
}
break;
}
case TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT:
{
const uint16_t* buf = static_cast<const uint16_t*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
indexBuffer.push_back(buf[index] + vertexStart);
}
break;
}
case TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE:
{
const uint8_t* buf = static_cast<const uint8_t*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
indexBuffer.push_back(buf[index] + vertexStart);
}
break;
}
default:
std::cerr << "Index component type " << accessor.componentType << " not supported!" << std::endl;
return;
}
}
std::unique_ptr<Primitive> newPrimitive(
new Primitive //
{
indexStart,
indexCount,
vertexCount,
primitive.material > -1 ? Materials[primitive.material] : Materials.back() //
} //
);
newPrimitive->SetBoundingBox(PosMin, PosMax);
NewMesh->Primitives.push_back(std::move(newPrimitive));
}
// Mesh BB from BBs of primitives
for (const auto& prim : NewMesh->Primitives)
{
if (prim->IsValidBB && !NewMesh->IsValidBB)
{
NewMesh->BB = prim->BB;
NewMesh->IsValidBB = true;
}
float3 bb_min = std::min(NewMesh->BB.Min, prim->BB.Min);
float3 bb_max = std::max(NewMesh->BB.Max, prim->BB.Max);
NewMesh->SetBoundingBox(bb_min, bb_max);
}
NewNode->_Mesh = std::move(NewMesh);
}
LinearNodes.push_back(NewNode.get());
if (parent)
{
parent->Children.push_back(std::move(NewNode));
}
else
{
Nodes.push_back(std::move(NewNode));
}
}
void Model::LoadSkins(const tinygltf::Model& gltf_model)
{
for (const auto& source : gltf_model.skins)
{
std::unique_ptr<Skin> NewSkin(new Skin{});
NewSkin->Name = source.name;
// Find skeleton root node
if (source.skeleton > -1)
{
NewSkin->pSkeletonRoot = NodeFromIndex(source.skeleton);
}
// Find joint nodes
for (int jointIndex : source.joints)
{
Node* node = NodeFromIndex(jointIndex);
if (node)
{
NewSkin->Joints.push_back(NodeFromIndex(jointIndex));
}
}
// Get inverse bind matrices from buffer
if (source.inverseBindMatrices > -1)
{
const tinygltf::Accessor& accessor = gltf_model.accessors[source.inverseBindMatrices];
const tinygltf::BufferView& bufferView = gltf_model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltf_model.buffers[bufferView.buffer];
NewSkin->InverseBindMatrices.resize(accessor.count);
memcpy(NewSkin->InverseBindMatrices.data(), &buffer.data[accessor.byteOffset + bufferView.byteOffset], accessor.count * sizeof(float4x4));
}
Skins.push_back(std::move(NewSkin));
}
}
static float GetTextureAlphaCutoffValue(const tinygltf::Model& gltf_model, int TextureIndex)
{
float AlphaCutoff = -1.f;
for (const auto& gltf_mat : gltf_model.materials)
{
auto base_color_tex_it = gltf_mat.values.find("baseColorTexture");
if (base_color_tex_it == gltf_mat.values.end())
{
// The material has no base texture
continue;
}
if (base_color_tex_it->second.TextureIndex() != TextureIndex)
{
// The material does not use this texture
continue;
}
auto alpha_mode_it = gltf_mat.additionalValues.find("alphaMode");
if (alpha_mode_it == gltf_mat.additionalValues.end())
{
// The material uses this texture, but it is not an alpha-blended or an alpha-cut material
AlphaCutoff = 0.f;
continue;
}
const tinygltf::Parameter& param = alpha_mode_it->second;
if (param.string_value == "MASK")
{
auto MaterialAlphaCutoff = 0.5f;
auto alpha_cutoff_it = gltf_mat.additionalValues.find("alphaCutoff");
if (alpha_cutoff_it != gltf_mat.additionalValues.end())
{
MaterialAlphaCutoff = static_cast<float>(alpha_cutoff_it->second.Factor());
}
if (AlphaCutoff < 0)
{
AlphaCutoff = MaterialAlphaCutoff;
}
else if (AlphaCutoff != MaterialAlphaCutoff)
{
if (AlphaCutoff == 0)
{
LOG_WARNING_MESSAGE("Texture ", TextureIndex,
" is used in an alpha-cut material with threshold ", MaterialAlphaCutoff,
" as well as in a non-alpha-cut material."
" Alpha remapping to improve mipmap generation will be disabled.");
}
else
{
LOG_WARNING_MESSAGE("Texture ", TextureIndex,
" is used in alpha-cut materials with different cutoff thresholds (", AlphaCutoff, ", ", MaterialAlphaCutoff,
"). Alpha remapping to improve mipmap generation will use ",
AlphaCutoff, '.');
}
}
}
else
{
// The material is not an alpha-cut material
if (AlphaCutoff > 0)
{
LOG_WARNING_MESSAGE("Texture ", TextureIndex,
" is used in an alpha-cut material as well as in a non-alpha-cut material."
" Alpha remapping to improve mipmap generation will be disabled.");
}
AlphaCutoff = 0.f;
}
}
return std::max(AlphaCutoff, 0.f);
}
void Model::LoadTextures(IRenderDevice* pDevice,
IDeviceContext* pCtx,
const tinygltf::Model& gltf_model,
const std::string& BaseDir,
TextureCacheType* pTextureCache)
{
std::vector<ITexture*> NewTextures;
for (const tinygltf::Texture& gltf_tex : gltf_model.textures)
{
const tinygltf::Image& gltf_image = gltf_model.images[gltf_tex.source];
RefCntAutoPtr<ITexture> pTexture;
if (pTextureCache != nullptr)
{
auto it = pTextureCache->find(BaseDir + gltf_image.uri);
if (it != pTextureCache->end())
{
pTexture = it->second.Lock();
if (!pTexture)
{
// Image width and height are initialized by LoadImageData() if the texture is found
// in the cache.
if (gltf_image.width > 0 && gltf_image.height > 0)
{
UNEXPECTED("Stale textures should not be found in the texture cache because we hold strong references. "
"This must be an unexpected effect of loading resources from multiple threads or a bug.");
}
else
{
pTextureCache->erase(it);
}
}
}
}
if (!pTexture)
{
RefCntAutoPtr<ISampler> pSampler;
if (gltf_tex.sampler == -1)
{
// No sampler specified, use a default one
pDevice->CreateSampler(Sam_LinearWrap, &pSampler);
}
else
{
pSampler = TextureSamplers[gltf_tex.sampler];
}
// Check if the texture is used in an alpha-cut material
float AlphaCutoff = GetTextureAlphaCutoffValue(gltf_model, static_cast<int>(Textures.size()));
pTexture = TextureFromGLTFImage(pDevice, pCtx, gltf_image, pSampler, AlphaCutoff);
NewTextures.push_back(pTexture);
if (pTextureCache != nullptr)
{
pTextureCache->emplace(BaseDir + gltf_image.uri, pTexture);
}
}
Textures.push_back(std::move(pTexture));
}
std::vector<StateTransitionDesc> Barriers;
for (auto& Tex : NewTextures)
{
pCtx->GenerateMips(Tex->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE));
StateTransitionDesc Barrier{Tex, RESOURCE_STATE_UNKNOWN, RESOURCE_STATE_SHADER_RESOURCE};
Barrier.UpdateResourceState = true;
Barriers.emplace_back(Barrier);
}
pCtx->TransitionResourceStates(static_cast<Uint32>(Barriers.size()), Barriers.data());
}
namespace
{
TEXTURE_ADDRESS_MODE GetWrapMode(int32_t wrapMode)
{
switch (wrapMode)
{
case 10497:
return TEXTURE_ADDRESS_WRAP;
case 33071:
return TEXTURE_ADDRESS_CLAMP;
case 33648:
return TEXTURE_ADDRESS_MIRROR;
default:
LOG_WARNING_MESSAGE("Unknown gltf address wrap mode: ", wrapMode, ". Defaulting to WRAP.");
return TEXTURE_ADDRESS_WRAP;
}
}
std::pair<FILTER_TYPE, FILTER_TYPE> GetFilterMode(int32_t filterMode)
{
switch (filterMode)
{
case 9728: // NEAREST
return {FILTER_TYPE_POINT, FILTER_TYPE_POINT};
case 9729: // LINEAR
return {FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR};
case 9984: // NEAREST_MIPMAP_NEAREST
return {FILTER_TYPE_POINT, FILTER_TYPE_POINT};
case 9985: // LINEAR_MIPMAP_NEAREST
return {FILTER_TYPE_LINEAR, FILTER_TYPE_POINT};
case 9986: // NEAREST_MIPMAP_LINEAR
return {FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR}; // use linear min filter instead as point makes no sesne
case 9987: // LINEAR_MIPMAP_LINEAR
return {FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR};
default:
LOG_WARNING_MESSAGE("Unknown gltf filter mode: ", filterMode, ". Defaulting to linear.");
return {FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR};
}
}
} // namespace
void Model::LoadTextureSamplers(IRenderDevice* pDevice, const tinygltf::Model& gltf_model)
{
for (const tinygltf::Sampler& smpl : gltf_model.samplers)
{
SamplerDesc SamDesc;
SamDesc.MagFilter = GetFilterMode(smpl.magFilter).first;
auto MinMipFilter = GetFilterMode(smpl.minFilter);
SamDesc.MinFilter = MinMipFilter.first;
SamDesc.MipFilter = MinMipFilter.second;
SamDesc.AddressU = GetWrapMode(smpl.wrapS);
SamDesc.AddressV = GetWrapMode(smpl.wrapT);
SamDesc.AddressW = SamDesc.AddressV;
RefCntAutoPtr<ISampler> pSampler;
pDevice->CreateSampler(SamDesc, &pSampler);
TextureSamplers.push_back(std::move(pSampler));
}
}
void Model::LoadMaterials(const tinygltf::Model& gltf_model)
{
for (const tinygltf::Material& gltf_mat : gltf_model.materials)
{
Material Mat;
{
auto base_color_tex_it = gltf_mat.values.find("baseColorTexture");
if (base_color_tex_it != gltf_mat.values.end())
{
Mat.pBaseColorTexture = Textures[base_color_tex_it->second.TextureIndex()];
Mat.TexCoordSets.BaseColor = static_cast<Uint8>(base_color_tex_it->second.TextureTexCoord());
}
}
{
auto metal_rough_tex_it = gltf_mat.values.find("metallicRoughnessTexture");
if (metal_rough_tex_it != gltf_mat.values.end())
{
Mat.pMetallicRoughnessTexture = Textures[metal_rough_tex_it->second.TextureIndex()];
Mat.TexCoordSets.MetallicRoughness = static_cast<Uint8>(metal_rough_tex_it->second.TextureTexCoord());
}
}
{
auto rough_factor_it = gltf_mat.values.find("roughnessFactor");
if (rough_factor_it != gltf_mat.values.end())
{
Mat.RoughnessFactor = static_cast<float>(rough_factor_it->second.Factor());
}
}
{
auto metal_factor_it = gltf_mat.values.find("metallicFactor");
if (metal_factor_it != gltf_mat.values.end())
{
Mat.MetallicFactor = static_cast<float>(metal_factor_it->second.Factor());
}
}
{
auto base_col_factor_it = gltf_mat.values.find("baseColorFactor");
if (base_col_factor_it != gltf_mat.values.end())
{
Mat.BaseColorFactor = float4::MakeVector(base_col_factor_it->second.ColorFactor().data());
}
}
{
auto normal_tex_it = gltf_mat.additionalValues.find("normalTexture");
if (normal_tex_it != gltf_mat.additionalValues.end())
{
Mat.pNormalTexture = Textures[normal_tex_it->second.TextureIndex()];
Mat.TexCoordSets.Normal = static_cast<Uint8>(normal_tex_it->second.TextureTexCoord());
}
}
{
auto emssive_tex_it = gltf_mat.additionalValues.find("emissiveTexture");
if (emssive_tex_it != gltf_mat.additionalValues.end())
{
Mat.pEmissiveTexture = Textures[emssive_tex_it->second.TextureIndex()];
Mat.TexCoordSets.Emissive = static_cast<Uint8>(emssive_tex_it->second.TextureTexCoord());
}
}
{
auto occlusion_tex_it = gltf_mat.additionalValues.find("occlusionTexture");
if (occlusion_tex_it != gltf_mat.additionalValues.end())
{
Mat.pOcclusionTexture = Textures[occlusion_tex_it->second.TextureIndex()];
Mat.TexCoordSets.Occlusion = static_cast<Uint8>(occlusion_tex_it->second.TextureTexCoord());
}
}
{
auto alpha_mode_it = gltf_mat.additionalValues.find("alphaMode");
if (alpha_mode_it != gltf_mat.additionalValues.end())
{
const tinygltf::Parameter& param = alpha_mode_it->second;
if (param.string_value == "BLEND")
{
Mat.AlphaMode = Material::ALPHAMODE_BLEND;
}
if (param.string_value == "MASK")
{
Mat.AlphaCutoff = 0.5f;
Mat.AlphaMode = Material::ALPHAMODE_MASK;
}
}
}
{
auto alpha_cutoff_it = gltf_mat.additionalValues.find("alphaCutoff");
if (alpha_cutoff_it != gltf_mat.additionalValues.end())
{
Mat.AlphaCutoff = static_cast<float>(alpha_cutoff_it->second.Factor());
}
}
{
auto emissive_fctr_it = gltf_mat.additionalValues.find("emissiveFactor");
if (emissive_fctr_it != gltf_mat.additionalValues.end())
{
Mat.EmissiveFactor = float4(float3::MakeVector(emissive_fctr_it->second.ColorFactor().data()), 1.0);
//Mat.EmissiveFactor = float4(0.0f);
}
}
{
auto double_sided_it = gltf_mat.additionalValues.find("doubleSided");
if (double_sided_it != gltf_mat.additionalValues.end())
{
Mat.DoubleSided = double_sided_it->second.bool_value;
}
}
// Extensions
// @TODO: Find out if there is a nicer way of reading these properties with recent tinygltf headers
{
auto ext_it = gltf_mat.extensions.find("KHR_materials_pbrSpecularGlossiness");
if (ext_it != gltf_mat.extensions.end())
{
if (ext_it->second.Has("specularGlossinessTexture"))
{
auto index = ext_it->second.Get("specularGlossinessTexture").Get("index");
Mat.extension.pSpecularGlossinessTexture = Textures[index.Get<int>()];
auto texCoordSet = ext_it->second.Get("specularGlossinessTexture").Get("texCoord");
Mat.TexCoordSets.SpecularGlossiness = static_cast<Uint8>(texCoordSet.Get<int>());
Mat.workflow = Material::PbrWorkflow::SpecularGlossiness;
}
if (ext_it->second.Has("diffuseTexture"))
{
auto index = ext_it->second.Get("diffuseTexture").Get("index");
Mat.extension.pDiffuseTexture = Textures[index.Get<int>()];
}
if (ext_it->second.Has("diffuseFactor"))
{
auto factor = ext_it->second.Get("diffuseFactor");
for (uint32_t i = 0; i < factor.ArrayLen(); i++)
{
auto val = factor.Get(i);
Mat.extension.DiffuseFactor[i] = val.IsNumber() ? (float)val.Get<double>() : (float)val.Get<int>();
}
}
if (ext_it->second.Has("specularFactor"))
{
auto factor = ext_it->second.Get("specularFactor");
for (uint32_t i = 0; i < factor.ArrayLen(); i++)
{
auto val = factor.Get(i);
Mat.extension.SpecularFactor[i] = val.IsNumber() ? (float)val.Get<double>() : (float)val.Get<int>();
}
}
}
}
Materials.push_back(Mat);
}
// Push a default material at the end of the list for meshes with no material assigned
Materials.push_back(Material{});
}
void Model::LoadAnimations(const tinygltf::Model& gltf_model)
{
for (const tinygltf::Animation& gltf_anim : gltf_model.animations)
{
Animation animation{};
animation.Name = gltf_anim.name;
if (gltf_anim.name.empty())
{
animation.Name = std::to_string(Animations.size());
}
// Samplers
for (auto& samp : gltf_anim.samplers)
{
AnimationSampler AnimSampler{};
if (samp.interpolation == "LINEAR")
{
AnimSampler.Interpolation = AnimationSampler::INTERPOLATION_TYPE::LINEAR;
}
else if (samp.interpolation == "STEP")
{
AnimSampler.Interpolation = AnimationSampler::INTERPOLATION_TYPE::STEP;
}
else if (samp.interpolation == "CUBICSPLINE")
{
AnimSampler.Interpolation = AnimationSampler::INTERPOLATION_TYPE::CUBICSPLINE;
}
// Read sampler input time values
{
const tinygltf::Accessor& accessor = gltf_model.accessors[samp.input];
const tinygltf::BufferView& bufferView = gltf_model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltf_model.buffers[bufferView.buffer];
VERIFY_EXPR(accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT);
const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset];
const float* buf = static_cast<const float*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
AnimSampler.Inputs.push_back(buf[index]);
}
for (auto input : AnimSampler.Inputs)
{
if (input < animation.Start)
{
animation.Start = input;
}
if (input > animation.End)
{
animation.End = input;
}
}
}
// Read sampler output T/R/S values
{
const tinygltf::Accessor& accessor = gltf_model.accessors[samp.output];
const tinygltf::BufferView& bufferView = gltf_model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer = gltf_model.buffers[bufferView.buffer];
VERIFY_EXPR(accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT);
const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset];
switch (accessor.type)
{
case TINYGLTF_TYPE_VEC3:
{
const float3* buf = static_cast<const float3*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
AnimSampler.OutputsVec4.push_back(float4(buf[index], 0.0f));
}
break;
}
case TINYGLTF_TYPE_VEC4:
{
const float4* buf = static_cast<const float4*>(dataPtr);
for (size_t index = 0; index < accessor.count; index++)
{
AnimSampler.OutputsVec4.push_back(buf[index]);
}
break;
}
default:
{
LOG_WARNING_MESSAGE("Unknown type", accessor.type);
break;
}
}
}
animation.Samplers.push_back(AnimSampler);
}
for (auto& source : gltf_anim.channels)
{
AnimationChannel channel{};
if (source.target_path == "rotation")
{
channel.PathType = AnimationChannel::PATH_TYPE::ROTATION;
}
else if (source.target_path == "translation")
{
channel.PathType = AnimationChannel::PATH_TYPE::TRANSLATION;
}
else if (source.target_path == "scale")
{
channel.PathType = AnimationChannel::PATH_TYPE::SCALE;
}
else if (source.target_path == "weights")
{
LOG_WARNING_MESSAGE("Weights not yet supported, skipping channel");
continue;
}
channel.SamplerIndex = source.sampler;
channel.node = NodeFromIndex(source.target_node);
if (!channel.node)
{
continue;
}
animation.Channels.push_back(channel);
}
Animations.push_back(animation);
}
}
namespace Callbacks
{
namespace
{
struct ImageLoaderData
{
Model::TextureCacheType* pTextureCache;
std::vector<RefCntAutoPtr<ITexture>>* pTextureHold;
std::string BaseDir;
};
bool LoadImageData(tinygltf::Image* gltf_image,
const int gltf_image_idx,
std::string* error,
std::string* warning,
int req_width,
int req_height,
const unsigned char* image_data,
int size,
void* user_data)
{
(void)warning;
auto* pLoaderData = reinterpret_cast<ImageLoaderData*>(user_data);
if (pLoaderData != nullptr && pLoaderData->pTextureCache != nullptr)
{
auto it = pLoaderData->pTextureCache->find(pLoaderData->BaseDir + gltf_image->uri);
if (it != pLoaderData->pTextureCache->end())
{
if (auto pTexture = it->second.Lock())
{
const auto& TexDesc = pTexture->GetDesc();
const auto& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format);
gltf_image->width = TexDesc.Width;
gltf_image->height = TexDesc.Height;
gltf_image->component = FmtAttribs.NumComponents;
gltf_image->bits = FmtAttribs.ComponentSize * 8;
gltf_image->pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
// Keep strong reference to ensure the texture is alive.
pLoaderData->pTextureHold->emplace_back(std::move(pTexture));
return true;
}
else
{
// Texture is stale - remove it from the cache
pLoaderData->pTextureCache->erase(it);
}
}
}
ImageLoadInfo LoadInfo;
LoadInfo.Format = Image::GetFileFormat(image_data, size);
if (LoadInfo.Format == IMAGE_FILE_FORMAT_UNKNOWN)
{
if (error != nullptr)
{
*error += FormatString("Unknown format for image[", gltf_image_idx, "] name = '", gltf_image->name, "'");
}
return false;
}
RefCntAutoPtr<DataBlobImpl> pImageData(MakeNewRCObj<DataBlobImpl>()(size));
memcpy(pImageData->GetDataPtr(), image_data, size);
RefCntAutoPtr<Image> pImage;
Image::CreateFromDataBlob(pImageData, LoadInfo, &pImage);
if (!pImage)
{
if (error != nullptr)
{
*error += FormatString("Failed to load image[", gltf_image_idx, "] name = '", gltf_image->name, "'");
}
return false;
}
const auto& ImgDesc = pImage->GetDesc();
if (req_width > 0)
{
if (static_cast<Uint32>(req_width) != ImgDesc.Width)
{
if (error != nullptr)
{
(*error) += FormatString("Image width mismatch for image[",
gltf_image_idx, "] name = '", gltf_image->name,
"': requested width: ",
req_width, ", actual width: ",
ImgDesc.Width);
}
return false;
}
}
if (req_height > 0)
{
if (static_cast<Uint32>(req_height) != ImgDesc.Height)
{
if (error != nullptr)
{
(*error) += FormatString("Image height mismatch for image[",
gltf_image_idx, "] name = '", gltf_image->name,
"': requested height: ",
req_height, ", actual height: ",
ImgDesc.Height);
}
return false;
}
}
gltf_image->width = ImgDesc.Width;
gltf_image->height = ImgDesc.Height;
gltf_image->component = 4;
gltf_image->bits = GetValueSize(ImgDesc.ComponentType) * 8;
gltf_image->pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
auto DstRowSize = gltf_image->width * gltf_image->component * (gltf_image->bits / 8);
gltf_image->image.resize(static_cast<size_t>(gltf_image->height * DstRowSize));
auto* pPixelsBlob = pImage->GetData();
const Uint8* pSrcPixels = reinterpret_cast<const Uint8*>(pPixelsBlob->GetDataPtr());
if (ImgDesc.NumComponents == 3)
{
for (Uint32 row = 0; row < ImgDesc.Height; ++row)
{
for (Uint32 col = 0; col < ImgDesc.Width; ++col)
{
Uint8* DstPixel = gltf_image->image.data() + DstRowSize * row + col * gltf_image->component;
const Uint8* SrcPixel = pSrcPixels + ImgDesc.RowStride * row + col * ImgDesc.NumComponents;
DstPixel[0] = SrcPixel[0];
DstPixel[1] = SrcPixel[1];
DstPixel[2] = SrcPixel[2];
DstPixel[3] = 1;
}
}
}
else if (gltf_image->component == 4)
{
for (Uint32 row = 0; row < ImgDesc.Height; ++row)
{
memcpy(gltf_image->image.data() + DstRowSize * row, pSrcPixels + ImgDesc.RowStride * row, DstRowSize);
}
}
else
{
*error += FormatString("Unexpected number of image comonents (", ImgDesc.NumComponents, ")");
return false;
}
return true;
}
bool FileExists(const std::string& abs_filename, void*)
{
return FileSystem::FileExists(abs_filename.c_str());
}
bool ReadWholeFile(std::vector<unsigned char>* out,
std::string* err,
const std::string& filepath,
void*)
{
FileWrapper pFile(filepath.c_str(), EFileAccessMode::Read);
if (!pFile)
{
if (err)
{
(*err) += FormatString("Unable to open file ", filepath, "\n");
}
return false;
}
auto size = pFile->GetSize();
if (size == 0)
{
if (err)
{
(*err) += FormatString("File is empty: ", filepath, "\n");
}
return false;
}
out->resize(size);
pFile->Read(out->data(), size);
return true;
}
} // namespace
} // namespace Callbacks
void Model::LoadFromFile(IRenderDevice* pDevice,
IDeviceContext* pContext,
const std::string& filename,
TextureCacheType* pTextureCache)
{
tinygltf::Model gltf_model;
tinygltf::TinyGLTF gltf_context;
std::vector<RefCntAutoPtr<ITexture>> TextureHold;
Callbacks::ImageLoaderData LoaderData //
{
pTextureCache,
&TextureHold //
};
if (filename.find_last_of("/\\") != std::string::npos)
LoaderData.BaseDir = filename.substr(0, filename.find_last_of("/\\"));
LoaderData.BaseDir += '/';
gltf_context.SetImageLoader(Callbacks::LoadImageData, &LoaderData);
tinygltf::FsCallbacks fsCallbacks = {};
fsCallbacks.ExpandFilePath = tinygltf::ExpandFilePath;
fsCallbacks.FileExists = Callbacks::FileExists;
fsCallbacks.ReadWholeFile = Callbacks::ReadWholeFile;
fsCallbacks.WriteWholeFile = tinygltf::WriteWholeFile;
fsCallbacks.user_data = this;
gltf_context.SetFsCallbacks(fsCallbacks);
bool binary = false;
size_t extpos = filename.rfind('.', filename.length());
if (extpos != std::string::npos)
{
binary = (filename.substr(extpos + 1, filename.length() - extpos) == "glb");
}
std::string error;
std::string warning;
bool fileLoaded;
if (binary)
fileLoaded = gltf_context.LoadBinaryFromFile(&gltf_model, &error, &warning, filename.c_str());
else
fileLoaded = gltf_context.LoadASCIIFromFile(&gltf_model, &error, &warning, filename.c_str());
if (!fileLoaded)
{
LOG_ERROR_AND_THROW("Failed to load gltf file ", filename, ": ", error);
}
if (!warning.empty())
{
LOG_WARNING_MESSAGE("Loaded gltf file ", filename, " with the following warning:", warning);
}
std::vector<Uint32> IndexBuffer;
std::vector<VertexAttribs0> VertexData0;
std::vector<VertexAttribs1> VertexData1;
LoadTextureSamplers(pDevice, gltf_model);
LoadTextures(pDevice, pContext, gltf_model, LoaderData.BaseDir, pTextureCache);
LoadMaterials(gltf_model);
// TODO: scene handling with no default scene
const tinygltf::Scene& scene = gltf_model.scenes[gltf_model.defaultScene > -1 ? gltf_model.defaultScene : 0];
for (size_t i = 0; i < scene.nodes.size(); i++)
{
const tinygltf::Node node = gltf_model.nodes[scene.nodes[i]];
LoadNode(pDevice, nullptr, node, scene.nodes[i], gltf_model, IndexBuffer, VertexData0, VertexData1);
}
if (gltf_model.animations.size() > 0)
{
LoadAnimations(gltf_model);
}
LoadSkins(gltf_model);
for (auto* node : LinearNodes)
{
// Assign skins
if (node->SkinIndex >= 0)
{
node->_Skin = Skins[node->SkinIndex].get();
}
// Initial pose
if (node->_Mesh)
{
node->Update();
}
}
Extensions = gltf_model.extensionsUsed;
{
VERIFY_EXPR(!VertexData0.empty());
BufferDesc VBDesc;
VBDesc.Name = "GLTF vertex attribs 0 buffer";
VBDesc.uiSizeInBytes = static_cast<Uint32>(VertexData0.size() * sizeof(VertexData0[0]));
VBDesc.BindFlags = BIND_VERTEX_BUFFER;
VBDesc.Usage = USAGE_STATIC;
BufferData BuffData(VertexData0.data(), VBDesc.uiSizeInBytes);
pDevice->CreateBuffer(VBDesc, &BuffData, &pVertexBuffer[0]);
}
{
VERIFY_EXPR(!VertexData1.empty());
BufferDesc VBDesc;
VBDesc.Name = "GLTF vertex attribs 1 buffer";
VBDesc.uiSizeInBytes = static_cast<Uint32>(VertexData1.size() * sizeof(VertexData1[0]));
VBDesc.BindFlags = BIND_VERTEX_BUFFER;
VBDesc.Usage = USAGE_STATIC;
BufferData BuffData(VertexData1.data(), VBDesc.uiSizeInBytes);
pDevice->CreateBuffer(VBDesc, &BuffData, &pVertexBuffer[1]);
}
if (!IndexBuffer.empty())
{
BufferDesc IBDesc;
IBDesc.Name = "GLTF inde buffer";
IBDesc.uiSizeInBytes = static_cast<Uint32>(IndexBuffer.size() * sizeof(IndexBuffer[0]));
IBDesc.BindFlags = BIND_INDEX_BUFFER;
IBDesc.Usage = USAGE_STATIC;
BufferData BuffData(IndexBuffer.data(), IBDesc.uiSizeInBytes);
pDevice->CreateBuffer(IBDesc, &BuffData, &pIndexBuffer);
}
GetSceneDimensions();
}
void Model::CalculateBoundingBox(Node* node, const Node* parent)
{
BoundBox parentBvh = parent ? parent->BVH : BoundBox{dimensions.min, dimensions.max};
if (node->_Mesh)
{
if (node->_Mesh->IsValidBB)
{
node->AABB = node->_Mesh->BB.Transform(node->GetMatrix());
if (node->Children.empty())
{
node->BVH.Min = node->AABB.Min;
node->BVH.Max = node->AABB.Max;
node->IsValidBVH = true;
}
}
}
parentBvh.Min = std::min(parentBvh.Min, node->BVH.Min);
parentBvh.Max = std::max(parentBvh.Max, node->BVH.Max);
for (auto& child : node->Children)
{
CalculateBoundingBox(child.get(), node);
}
}
void Model::GetSceneDimensions()
{
// Calculate binary volume hierarchy for all nodes in the scene
for (auto* node : LinearNodes)
{
CalculateBoundingBox(node, nullptr);
}
dimensions.min = float3{+FLT_MAX, +FLT_MAX, +FLT_MAX};
dimensions.max = float3{-FLT_MAX, -FLT_MAX, -FLT_MAX};
for (const auto* node : LinearNodes)
{
if (node->IsValidBVH)
{
dimensions.min = std::min(dimensions.min, node->BVH.Min);
dimensions.max = std::max(dimensions.max, node->BVH.Max);
}
}
// Calculate scene AABBTransform
AABBTransform = float4x4::Scale(dimensions.max[0] - dimensions.min[0], dimensions.max[1] - dimensions.min[1], dimensions.max[2] - dimensions.min[2]);
AABBTransform[3][0] = dimensions.min[0];
AABBTransform[3][1] = dimensions.min[1];
AABBTransform[3][2] = dimensions.min[2];
}
void Model::UpdateAnimation(Uint32 index, float time)
{
if (index > static_cast<Uint32>(Animations.size()) - 1)
{
LOG_WARNING_MESSAGE("No animation with index ", index);
return;
}
Animation& animation = Animations[index];
bool updated = false;
for (auto& channel : animation.Channels)
{
AnimationSampler& sampler = animation.Samplers[channel.SamplerIndex];
if (sampler.Inputs.size() > sampler.OutputsVec4.size())
{
continue;
}
for (size_t i = 0; i < sampler.Inputs.size() - 1; i++)
{
if ((time >= sampler.Inputs[i]) && (time <= sampler.Inputs[i + 1]))
{
float u = std::max(0.0f, time - sampler.Inputs[i]) / (sampler.Inputs[i + 1] - sampler.Inputs[i]);
if (u <= 1.0f)
{
switch (channel.PathType)
{
case AnimationChannel::PATH_TYPE::TRANSLATION:
{
float4 trans = lerp(sampler.OutputsVec4[i], sampler.OutputsVec4[i + 1], u);
channel.node->Translation = float3(trans);
break;
}
case AnimationChannel::PATH_TYPE::SCALE:
{
float4 scale = lerp(sampler.OutputsVec4[i], sampler.OutputsVec4[i + 1], u);
channel.node->Scale = float3(scale);
break;
}
case AnimationChannel::PATH_TYPE::ROTATION:
{
Quaternion q1;
q1.q.x = sampler.OutputsVec4[i].x;
q1.q.y = sampler.OutputsVec4[i].y;
q1.q.z = sampler.OutputsVec4[i].z;
q1.q.w = sampler.OutputsVec4[i].w;
Quaternion q2;
q2.q.x = sampler.OutputsVec4[i + 1].x;
q2.q.y = sampler.OutputsVec4[i + 1].y;
q2.q.z = sampler.OutputsVec4[i + 1].z;
q2.q.w = sampler.OutputsVec4[i + 1].w;
channel.node->Rotation = normalize(slerp(q1, q2, u));
break;
}
}
updated = true;
}
}
}
}
if (updated)
{
for (auto& node : Nodes)
{
node->Update();
}
}
}
Node* Model::FindNode(Node* parent, Uint32 index)
{
Node* nodeFound = nullptr;
if (parent->Index == index)
{
return parent;
}
for (auto& child : parent->Children)
{
nodeFound = FindNode(child.get(), index);
if (nodeFound)
{
break;
}
}
return nodeFound;
}
Node* Model::NodeFromIndex(uint32_t index)
{
Node* nodeFound = nullptr;
for (auto& node : Nodes)
{
nodeFound = FindNode(node.get(), index);
if (nodeFound)
{
break;
}
}
return nodeFound;
}
} // namespace GLTF
} // namespace Diligent
|
#include "../myoddweb.directorywatcher.win/utils/Threads/CallbackWorker.h"
#include "pch.h"
#include "../myoddweb.directorywatcher.win/utils/Threads/WorkerPool.h"
#include "../myoddweb.directorywatcher.win/utils/Threads/Worker.h"
#include "../myoddweb.directorywatcher.win/utils/Wait.h"
#include "MonitorsManagerTestHelper.h"
#include "WorkerHelper.h"
using myoddweb::directorywatcher::threads::WorkerPool;
using myoddweb::directorywatcher::Wait;
TEST(WorkPool, DefaultValues) {
{
const auto pool = ::WorkerPool( 10 );
EXPECT_FALSE( pool.Started());
}
{
const auto pool = ::WorkerPool(10);
EXPECT_FALSE(pool.Completed());
}
}
TEST(WorkPool, StartIsCalledExactlyOnceWithQuickWorkers) {
{
auto worker1 = TestWorker(1);
auto worker2 = TestWorker(1);
auto pool = ::WorkerPool(10);
pool.Add(worker1);
// give worker 1 a chance to complete
auto wr = worker1.WaitFor(100);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
// add another one
pool.Add(worker2);
// then wait a bit for everything
pool.WaitFor(100);
// surely start is called.
EXPECT_EQ(1, worker1._startCalled);
EXPECT_EQ(1, worker2._startCalled);
// clean up
wr = pool.StopAndWait(100 );
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
}
}
TEST(WorkPool, StartIsCalledExactlyOnceEvenForCompleteWorker) {
{
// create a worker and run it.
auto worker1 = TestWorker(1);
worker1.Execute();
EXPECT_TRUE(worker1.Completed());
auto worker2 = TestWorker(1);
auto pool = ::WorkerPool(10);
// add it to the pool
pool.Add(worker1);
// give worker 1 a chance to complete
auto wr = worker1.WaitFor(100);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
// add another one
pool.Add(worker2);
// then wait a bit for everything
pool.WaitFor(100);
// start should only be called once regaldess.
EXPECT_EQ(1, worker1._startCalled);
EXPECT_EQ(1, worker2._startCalled);
// clean up
wr = pool.StopAndWait(100);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
}
}
TEST(WorkPool, EndIsCalledExactlyOnce) {
{
auto worker1 = TestWorker(1);
auto worker2 = TestWorker(1);
auto pool = ::WorkerPool(10);
pool.Add(worker1);
pool.Add(worker2);
// wait for the pool to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// even if we wait a tiny bit, we still start
pool.WaitFor(100);
// surely start is called.
EXPECT_EQ(1, worker1._endCalled);
EXPECT_EQ(1, worker2._endCalled);
}
}
TEST(WorkPool, NumberOfTimesUpdatesIsCalled) {
{
for (auto i = 0; i < 10; ++i)
{
// we do not want this to be too quick
// otherwise those might finish before we even start
const auto numTimesWorker1 = 50;
const auto numTimesWorker2 = 60;
const auto pollTime = 10;
auto worker1 = TestWorker(numTimesWorker1);
auto worker2 = TestWorker(numTimesWorker2);
auto pool = ::WorkerPool(pollTime);
pool.Add(worker1);
pool.Add(worker2);
// wait for the pool to start
if (!Wait::SpinUntil([&pool]
{
return pool.Started();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// we are not going to stop it
// we just waiting for it to complete.
const auto status = pool.WaitFor( (numTimesWorker1 + numTimesWorker2) * TEST_TIMEOUT_WAIT );
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, status);
EXPECT_EQ(worker1._maxUpdate, worker1._updateCalled);
EXPECT_EQ(worker2._maxUpdate, worker2._updateCalled);
// santy check that our test class is saving the correct values
EXPECT_EQ(numTimesWorker1, worker1._updateCalled);
EXPECT_EQ(numTimesWorker2, worker2._updateCalled);
}
}
}
TEST(WorkPool, WaitingForAWorkerThatIsNotOurs)
{
auto worker1 = TestWorker(5);
auto worker2 = TestWorker(1);
auto pool = ::WorkerPool(10);
pool.Add(worker1);
// wait for the pool to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// we are not going to stop it
// we just waiting for it to complete.
const auto status = pool.WaitFor(worker2, 10000);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, status);
EXPECT_EQ(1, worker1._startCalled);
// but our start was never called.
EXPECT_EQ(0, worker2._startCalled);
}
TEST(WorkPool, WaitUntiWhenNoWorker ) {
{
auto pool = ::WorkerPool(10);
// we are not going to stop it
// we just waiting for it to complete.
const auto status = pool.WaitFor(10000);
// still complete.
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, status);
}
}
TEST(WorkPool, WaitForASingleItem) {
{
auto worker1 = TestWorker(3);
auto pool = ::WorkerPool(10);
pool.Add(worker1);
// we are not going to stop it
// we just waiting for it to complete.
const auto status = pool.WaitFor( worker1, 10000);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, status);
EXPECT_EQ(worker1._maxUpdate, worker1._updateCalled);
}
}
TEST(WorkPool, StopAndWait) {
{
for (auto i = 0; i < 10; ++i)
{
// make it very large number
auto worker1 = TestWorker(5000);
auto worker2 = TestWorker(6000);
auto pool = ::WorkerPool(10);
pool.Add(worker1);
pool.Add(worker2);
// wait for the pool to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// run a little
pool.WaitFor(100);
// we are not going to stop it
// we just waiting for it to complete.
const auto status = pool.StopAndWait(1000);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, status);
EXPECT_TRUE(worker1._updateCalled <= worker1._maxUpdate);
EXPECT_TRUE(worker2._updateCalled <= worker2._maxUpdate);
EXPECT_TRUE(worker1._updateCalled > 0);
EXPECT_TRUE(worker2._updateCalled > 0);
// but we must have started
EXPECT_EQ(1, worker1._startCalled);
EXPECT_EQ(1, worker2._startCalled);
EXPECT_EQ(1, worker1._endCalled);
EXPECT_EQ(1, worker2._endCalled);
}
}
}
TEST(WorkPool, CheckHasStartedWithShortRunningWorker)
{
for (auto i = 0; i < 10; ++i)
{
// create a worker that will run veru quick
auto worker = TestWorker(1);
// create a pool
auto pool = ::WorkerPool(10);
pool.Add(worker);
// the act of adding a worker could start it.
// so we cannot test "pool.Started()"
// make sure that start by itself.
if (!Wait::SpinUntil([&]
{
return pool.Started() || pool.Completed();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// then wait for it to end.
if (myoddweb::directorywatcher::threads::WaitResult::complete != pool.StopAndWait(2*TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to complete pool");
}
EXPECT_FALSE(pool.Started());
}
}
TEST(WorkPool, CheckHasStartedWithLongRunningWorker)
{
for (auto i = 0; i < 10; ++i)
{
// create a worker that will run for a while
auto worker = TestWorker(100);
// create a pool
auto pool = ::WorkerPool(10);
pool.Add(worker);
// the act of adding a worker could start it.
// so we cannot test "pool.Started()"
// make sure that start by itself.
if (!Wait::SpinUntil([&]
{
return pool.Started() || pool.Completed();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// wait a bit
pool.WaitFor(TEST_TIMEOUT_WAIT);
// then wait for it to end.
if (myoddweb::directorywatcher::threads::WaitResult::complete != pool.StopAndWait( TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to complete pool");
}
EXPECT_FALSE(pool.Started());
}
}
TEST(WorkPool, SingleCallbackWorkerEndsAsExpected)
{
auto pool = ::WorkerPool(10);
auto wasCalled = false;
// then create a somple CallbackWorker
auto cbWorker = myoddweb::directorywatcher::threads::CallbackWorker([&wasCalled]
{
wasCalled = true;
});
// then wait for our simple worker to complete.
pool.Add(cbWorker);
// wait a little
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// then wait a couple of milliseconds
// it should be really quick.
const auto wr = pool.WaitFor(cbWorker, TEST_TIMEOUT_WAIT);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
EXPECT_TRUE(wasCalled);
// but we must be complete as well
EXPECT_TRUE(cbWorker.Completed());
// just complete the test.
if (myoddweb::directorywatcher::threads::WaitResult::complete != pool.StopAndWait(TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("Unable to complete pool");
}
EXPECT_FALSE(pool.Started());
}
TEST(WorkPool, SingleCallbackWorkerWithOtherWorkerEndsAsExpected)
{
// wait a while
auto worker = TestWorker(5000);
auto pool = ::WorkerPool(10);
pool.Add(worker);
// wait a little
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
auto wasCalled = false;
// then create a somple CallbackWorker
auto cbWorker = myoddweb::directorywatcher::threads::CallbackWorker([&wasCalled]
{
wasCalled = true;
});
// then wait for our simple worker to complete.
pool.Add(cbWorker);
// then wait a couple of milliseconds
// it should be really quick.
const auto wr = pool.WaitFor(cbWorker, TEST_TIMEOUT_WAIT);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
EXPECT_TRUE(wasCalled);
// but we must be complete as well
EXPECT_TRUE(cbWorker.Completed());
// just complete the test.
if (myoddweb::directorywatcher::threads::WaitResult::complete != pool.StopAndWait(TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("Unable to complete pool");
}
EXPECT_FALSE(pool.Started());
}
TEST(WorkPool, BlockingMultipleCallbackWorkerEndsAsExpected)
{
// create a worker that has 200 events, (every 10ms = ~2000ms)
auto worker = TestWorker(200);
// add it to our work pool
auto pool = ::WorkerPool(10);
pool.Add(worker);
// wait for it to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// the flag to check that it was called
auto wasCalled = false;
// then create a somple CallbackWorker that return very fast
auto cbWorker = myoddweb::directorywatcher::threads::CallbackWorker([&wasCalled]
{
wasCalled = true;
});
// create another that is mostly blocking
myoddweb::directorywatcher::threads::CallbackWorker* cbWorkerLong = nullptr;
cbWorkerLong = new myoddweb::directorywatcher::threads::CallbackWorker([&cbWorkerLong]
{
for (;;)
{
if (cbWorkerLong->MustStop())
{
return;
}
std::this_thread::sleep_for(std::chrono::milliseconds(TEST_TIMEOUT/2));
}
});
// then wait for our simple worker to complete.
pool.Add(cbWorker);
pool.Add(*cbWorkerLong);
// then wait for the quick worker to complete it should finish quick
// if it blocks it means there is an error on our other, blocking function
// that is preventing _this_ function from even running.
const auto wr = pool.WaitFor(cbWorker, TEST_TIMEOUT_WAIT );
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
EXPECT_TRUE( wasCalled);
// but we must be complete as well
EXPECT_TRUE(cbWorker.Completed() );
// not call stop so the other one should also complete
if (myoddweb::directorywatcher::threads::WaitResult::complete != pool.StopAndWait(TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("Unable to complete pool");
}
EXPECT_FALSE(pool.Started());
delete cbWorkerLong;
}
TEST(WorkPool, StoppingWorkpoolWhenAFunctionNeverEnds)
{
// a worker that will work for 50*10 ms = ~500ms
auto worker = TestWorker(50);
auto pool = ::WorkerPool(10);
pool.Add(worker);
// wait for the pool to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// this is the kill switch for this function so we can actually stop it.
auto stop = false;
// create a worker that has a blocking function
auto cbWorkerLong = myoddweb::directorywatcher::threads::CallbackWorker([&stop]
{
// this will never end
for (;;)
{
if( stop)
{
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(TEST_TIMEOUT / 2));
}
});
// then wait for our simple worker to complete.
pool.Add(cbWorkerLong);
// for it ... it will never end
const auto wr = pool.WaitFor(cbWorkerLong, TEST_TIMEOUT);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::timeout, wr);
// try and complete the test, it will not happen as we have that one long running function
if (myoddweb::directorywatcher::threads::WaitResult::complete == pool.StopAndWait(TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("The pool should have timed out ... ");
}
// the pool cannot be complete as we have that one long running function.
EXPECT_FALSE(pool.Completed());
// kill the function now.
stop = true;
pool.WaitFor(cbWorkerLong, TEST_TIMEOUT_WAIT );
if (myoddweb::directorywatcher::threads::WaitResult::complete != pool.StopAndWait(TEST_TIMEOUT))
{
GTEST_FATAL_FAILURE_("The pool should have completed now ... ");
}
}
TEST(WorkPool, AddAWorkerWithinAWorkerOnUpdate) {
{
// our pool and workers
auto worker1 = TestWorker(5);
auto pool = ::WorkerPool(10);
// then create a simple CallbackWorker
auto wasCalled = false;
auto cbWorker = myoddweb::directorywatcher::threads::CallbackWorker([&]
{
wasCalled = true;
// durring the update, add the other worker
pool.Add(worker1);
});
// then get things started
// and add the callback worker.
pool.Add(cbWorker );
// wait for the pool to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// then wait for a couple of callback
// every 10ms * 5 callback = ~50ms so 500 should be more than enough,
const auto wr = pool.WaitFor(500);
// surely start is called.
EXPECT_TRUE(wasCalled);
EXPECT_EQ(1, worker1._endCalled);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
}
}
TEST(WorkPool, AddAWorkerWithinAWorkerOnStartDurringPoolStart) {
{
// our pool and workers
auto worker1 = TestWorker(5);
auto pool = ::WorkerPool(10);
// then create a simple CallbackWorker
auto cbWorker = TestWorkerOnStart(pool, worker1, 100 );
auto cbWorker1 = TestWorkerOnStart(pool, cbWorker, 100);
// then get things started
// and add the callback worker.
// because it is added now it will be called at the sametime as the pool "OnStart"
pool.Add(cbWorker1);
// wait for the pool to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// then wait for a couple of callback
// every 10ms * 100 callback = ~1000ms
const auto wr = pool.WaitFor(10000);
// surely start is called.
EXPECT_EQ(1, worker1._endCalled);
EXPECT_EQ(worker1._maxUpdate, worker1._updateCalled);
EXPECT_EQ(cbWorker._maxUpdate, cbWorker._updateCalled);
EXPECT_EQ(cbWorker1._maxUpdate, cbWorker1._updateCalled);
EXPECT_EQ(1, cbWorker._endCalled);
EXPECT_EQ(1, cbWorker1._endCalled);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
}
}
TEST(WorkPool, AddAWorkerWithinAWorkerOnStartDurringPoolUpdate) {
{
// have a long running worker
auto worker1 = TestWorker(500);
auto worker2 = TestWorker(500);
auto pool = ::WorkerPool(10);
// then create a simple CallbackWorker
auto cbWorker = TestWorkerOnStart(pool, worker2, 100);
// add the long running worker and make sure that everything started
pool.Add(worker1);
// wait for the pool to start
if (!Wait::SpinUntil([&]
{
return pool.Started();
}, TEST_TIMEOUT_WAIT))
{
GTEST_FATAL_FAILURE_("Unable to start pool");
}
// now that we started, add the worker that adds a worker
// because it is added now it will be called at the sametime as the pool "OnUpdate"
pool.Add(cbWorker);
// then wait for a couple of callback
// every 10ms * 10000 callback = ~100000ms
const auto wr = pool.WaitFor(10000 + TEST_TIMEOUT_WAIT);
// surely start is called.
EXPECT_EQ(1, worker1._endCalled);
EXPECT_EQ(worker1._maxUpdate, worker1._updateCalled);
EXPECT_EQ(worker2._maxUpdate, worker2._updateCalled);
EXPECT_EQ(cbWorker._maxUpdate, cbWorker._updateCalled);
EXPECT_EQ(1, cbWorker._endCalled);
EXPECT_EQ(1, worker1._endCalled);
EXPECT_EQ(1, worker2._endCalled);
EXPECT_EQ(myoddweb::directorywatcher::threads::WaitResult::complete, wr);
}
}
|
//
// Copyright 2018 gRPC authors.
//
// 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 <grpc/support/port_platform.h>
#include <inttypes.h>
#include <limits.h>
#include "absl/strings/str_cat.h"
#include <grpc/grpc.h>
#include "src/core/ext/filters/client_channel/lb_policy.h"
#include "src/core/ext/filters/client_channel/lb_policy/address_filtering.h"
#include "src/core/ext/filters/client_channel/lb_policy/child_policy_handler.h"
#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/timer.h"
namespace grpc_core {
TraceFlag grpc_lb_priority_trace(false, "priority_lb");
namespace {
constexpr char kPriority[] = "priority_experimental";
// How long we keep a child around for after it is no longer being used
// (either because it has been removed from the config or because we
// have switched to a higher-priority child).
constexpr int kChildRetentionIntervalMs = 15 * 60 * 1000;
// Default for how long we wait for a newly created child to get connected
// before starting to attempt the next priority. Overridable via channel arg.
constexpr int kDefaultChildFailoverTimeoutMs = 10000;
// Config for priority LB policy.
class PriorityLbConfig : public LoadBalancingPolicy::Config {
public:
PriorityLbConfig(
std::map<std::string, RefCountedPtr<LoadBalancingPolicy::Config>>
children,
std::vector<std::string> priorities)
: children_(std::move(children)), priorities_(std::move(priorities)) {}
const char* name() const override { return kPriority; }
const std::map<std::string, RefCountedPtr<LoadBalancingPolicy::Config>>&
children() const {
return children_;
}
const std::vector<std::string>& priorities() const { return priorities_; }
private:
const std::map<std::string, RefCountedPtr<LoadBalancingPolicy::Config>>
children_;
const std::vector<std::string> priorities_;
};
// priority LB policy.
class PriorityLb : public LoadBalancingPolicy {
public:
explicit PriorityLb(Args args);
const char* name() const override { return kPriority; }
void UpdateLocked(UpdateArgs args) override;
void ExitIdleLocked() override;
void ResetBackoffLocked() override;
private:
// Each ChildPriority holds a ref to the PriorityLb.
class ChildPriority : public InternallyRefCounted<ChildPriority> {
public:
ChildPriority(RefCountedPtr<PriorityLb> priority_policy, std::string name);
~ChildPriority() {
priority_policy_.reset(DEBUG_LOCATION, "ChildPriority");
}
const std::string& name() const { return name_; }
void UpdateLocked(RefCountedPtr<LoadBalancingPolicy::Config> config);
void ExitIdleLocked();
void ResetBackoffLocked();
void DeactivateLocked();
void MaybeReactivateLocked();
void MaybeCancelFailoverTimerLocked();
void Orphan() override;
std::unique_ptr<SubchannelPicker> GetPicker() {
return absl::make_unique<RefCountedPickerWrapper>(picker_wrapper_);
}
grpc_connectivity_state connectivity_state() const {
return connectivity_state_;
}
bool failover_timer_callback_pending() const {
return failover_timer_callback_pending_;
}
private:
// A simple wrapper for ref-counting a picker from the child policy.
class RefCountedPicker : public RefCounted<RefCountedPicker> {
public:
explicit RefCountedPicker(std::unique_ptr<SubchannelPicker> picker)
: picker_(std::move(picker)) {}
PickResult Pick(PickArgs args) { return picker_->Pick(args); }
private:
std::unique_ptr<SubchannelPicker> picker_;
};
// A non-ref-counted wrapper for RefCountedPicker.
class RefCountedPickerWrapper : public SubchannelPicker {
public:
explicit RefCountedPickerWrapper(RefCountedPtr<RefCountedPicker> picker)
: picker_(std::move(picker)) {}
PickResult Pick(PickArgs args) override { return picker_->Pick(args); }
private:
RefCountedPtr<RefCountedPicker> picker_;
};
class Helper : public ChannelControlHelper {
public:
explicit Helper(RefCountedPtr<ChildPriority> priority)
: priority_(std::move(priority)) {}
~Helper() { priority_.reset(DEBUG_LOCATION, "Helper"); }
RefCountedPtr<SubchannelInterface> CreateSubchannel(
const grpc_channel_args& args) override;
void UpdateState(grpc_connectivity_state state,
std::unique_ptr<SubchannelPicker> picker) override;
void RequestReresolution() override;
void AddTraceEvent(TraceSeverity severity, StringView message) override;
private:
RefCountedPtr<ChildPriority> priority_;
};
// Methods for dealing with the child policy.
OrphanablePtr<LoadBalancingPolicy> CreateChildPolicyLocked(
const grpc_channel_args* args);
void OnConnectivityStateUpdateLocked(
grpc_connectivity_state state,
std::unique_ptr<SubchannelPicker> picker);
void StartFailoverTimerLocked();
static void OnFailoverTimer(void* arg, grpc_error* error);
static void OnFailoverTimerLocked(void* arg, grpc_error* error);
static void OnDeactivationTimer(void* arg, grpc_error* error);
static void OnDeactivationTimerLocked(void* arg, grpc_error* error);
RefCountedPtr<PriorityLb> priority_policy_;
const std::string name_;
OrphanablePtr<LoadBalancingPolicy> child_policy_;
grpc_connectivity_state connectivity_state_ = GRPC_CHANNEL_CONNECTING;
RefCountedPtr<RefCountedPicker> picker_wrapper_;
// States for delayed removal.
grpc_timer deactivation_timer_;
grpc_closure on_deactivation_timer_;
bool deactivation_timer_callback_pending_ = false;
// States of failover.
grpc_timer failover_timer_;
grpc_closure on_failover_timer_;
grpc_closure on_failover_timer_locked_;
bool failover_timer_callback_pending_ = false;
};
~PriorityLb();
void ShutdownLocked() override;
// Returns UINT32_MAX if child is not in current priority list.
uint32_t GetChildPriorityLocked(const std::string& child_name) const;
void HandleChildConnectivityStateChangeLocked(ChildPriority* child);
void DeleteChild(ChildPriority* child);
void TryNextPriorityLocked(bool report_connecting);
void SelectPriorityLocked(uint32_t priority);
const int child_failover_timeout_ms_;
// Current channel args and config from the resolver.
const grpc_channel_args* args_ = nullptr;
RefCountedPtr<PriorityLbConfig> config_;
HierarchicalAddressMap addresses_;
// Internal state.
bool shutting_down_ = false;
std::map<std::string, OrphanablePtr<ChildPriority>> children_;
// The priority that is being used.
uint32_t current_priority_ = UINT32_MAX;
// Points to the current child from before the most recent update.
// We will continue to use this child until we decide which of the new
// children to use.
ChildPriority* current_child_from_before_update_ = nullptr;
};
//
// PriorityLb
//
PriorityLb::PriorityLb(Args args)
: LoadBalancingPolicy(std::move(args)),
child_failover_timeout_ms_(grpc_channel_args_find_integer(
args.args, GRPC_ARG_PRIORITY_FAILOVER_TIMEOUT_MS,
{kDefaultChildFailoverTimeoutMs, 0, INT_MAX})) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] created", this);
}
}
PriorityLb::~PriorityLb() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] destroying priority LB policy", this);
}
grpc_channel_args_destroy(args_);
}
void PriorityLb::ShutdownLocked() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] shutting down", this);
}
shutting_down_ = true;
children_.clear();
}
void PriorityLb::ExitIdleLocked() {
if (current_priority_ != UINT32_MAX) {
const std::string& child_name = config_->priorities()[current_priority_];
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] exiting IDLE for current priority %d child %s",
this, current_priority_, child_name.c_str());
}
children_[child_name]->ExitIdleLocked();
}
}
void PriorityLb::ResetBackoffLocked() {
for (const auto& p : children_) p.second->ResetBackoffLocked();
}
void PriorityLb::UpdateLocked(UpdateArgs args) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] received update", this);
}
// Save current child.
if (current_priority_ != UINT32_MAX) {
const std::string& child_name = config_->priorities()[current_priority_];
current_child_from_before_update_ = children_[child_name].get();
// Unset current_priority_, since it was an index into the old
// config's priority list and may no longer be valid. It will be
// reset later by TryNextPriorityLocked(), but we unset it here in
// case updating any of our children triggers a state update.
current_priority_ = UINT32_MAX;
}
// Update config.
config_ = std::move(args.config);
// Update args.
grpc_channel_args_destroy(args_);
args_ = args.args;
args.args = nullptr;
// Update addresses.
addresses_ = MakeHierarchicalAddressMap(args.addresses);
// Check all existing children against the new config.
for (const auto& p : children_) {
const std::string& child_name = p.first;
auto& child = p.second;
auto config_it = config_->children().find(child_name);
if (config_it == config_->children().end()) {
// Existing child not found in new config. Deactivate it.
child->DeactivateLocked();
} else {
// Existing child found in new config. Update it.
child->UpdateLocked(config_it->second);
}
}
// Try to get connected.
TryNextPriorityLocked(/*report_connecting=*/children_.empty());
}
uint32_t PriorityLb::GetChildPriorityLocked(
const std::string& child_name) const {
for (uint32_t priority = 0; priority < config_->priorities().size();
++priority) {
if (config_->priorities()[priority] == child_name) return priority;
}
return UINT32_MAX;
}
void PriorityLb::HandleChildConnectivityStateChangeLocked(
ChildPriority* child) {
// Special case for the child that was the current child before the
// most recent update.
if (child == current_child_from_before_update_) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] state update for current child from before "
"config update",
this);
}
if (child->connectivity_state() == GRPC_CHANNEL_READY ||
child->connectivity_state() == GRPC_CHANNEL_IDLE) {
// If it's still READY or IDLE, we stick with this child, so pass
// the new picker up to our parent.
channel_control_helper()->UpdateState(child->connectivity_state(),
child->GetPicker());
} else {
// If it's no longer READY or IDLE, we should stop using it.
// We already started trying other priorities as a result of the
// update, but calling TryNextPriorityLocked() ensures that we will
// properly select between CONNECTING and TRANSIENT_FAILURE as the
// new state to report to our parent.
current_child_from_before_update_ = nullptr;
TryNextPriorityLocked(/*report_connecting=*/true);
}
return;
}
// Otherwise, find the child's priority.
uint32_t child_priority = GetChildPriorityLocked(child->name());
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] state update for priority %d, child %s",
this, child_priority, child->name().c_str());
}
// Ignore priorities not in the current config.
if (child_priority == UINT32_MAX) return;
// Ignore lower-than-current priorities.
if (child_priority > current_priority_) return;
// If a child reports TRANSIENT_FAILURE, start trying the next priority.
// Note that even if this is for a higher-than-current priority, we
// may still need to create some children between this priority and
// the current one (e.g., if we got an update that inserted new
// priorities ahead of the current one).
if (child->connectivity_state() == GRPC_CHANNEL_TRANSIENT_FAILURE) {
TryNextPriorityLocked(
/*report_connecting=*/child_priority == current_priority_);
return;
}
// The update is for a higher-than-current priority (or for any
// priority if we don't have any current priority).
if (child_priority < current_priority_) {
// If the child reports READY or IDLE, switch to that priority.
// Otherwise, ignore the update.
if (child->connectivity_state() == GRPC_CHANNEL_READY ||
child->connectivity_state() == GRPC_CHANNEL_IDLE) {
SelectPriorityLocked(child_priority);
}
return;
}
// The current priority has returned a new picker, so pass it up to
// our parent.
channel_control_helper()->UpdateState(child->connectivity_state(),
child->GetPicker());
}
void PriorityLb::DeleteChild(ChildPriority* child) {
// If this was the current child from before the most recent update,
// stop using it. We already started trying other priorities as a
// result of the update, but calling TryNextPriorityLocked() ensures that
// we will properly select between CONNECTING and TRANSIENT_FAILURE as the
// new state to report to our parent.
if (current_child_from_before_update_ == child) {
current_child_from_before_update_ = nullptr;
TryNextPriorityLocked(/*report_connecting=*/true);
}
children_.erase(child->name());
}
void PriorityLb::TryNextPriorityLocked(bool report_connecting) {
for (uint32_t priority = 0; priority < config_->priorities().size();
++priority) {
// If the child for the priority does not exist yet, create it.
const std::string& child_name = config_->priorities()[priority];
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] trying priority %d, child %s", this,
priority, child_name.c_str());
}
auto& child = children_[child_name];
if (child == nullptr) {
if (report_connecting) {
channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING,
absl::make_unique<QueuePicker>(Ref(DEBUG_LOCATION, "QueuePicker")));
}
child = MakeOrphanable<ChildPriority>(
Ref(DEBUG_LOCATION, "ChildPriority"), child_name);
child->UpdateLocked(config_->children().find(child_name)->second);
return;
}
// The child already exists.
child->MaybeReactivateLocked();
// If the child is in state READY or IDLE, switch to it.
if (child->connectivity_state() == GRPC_CHANNEL_READY ||
child->connectivity_state() == GRPC_CHANNEL_IDLE) {
SelectPriorityLocked(priority);
return;
}
// Child is not READY or IDLE.
// If its failover timer is still pending, give it time to fire.
if (child->failover_timer_callback_pending()) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] priority %d, child %s: child still "
"attempting to connect, will wait",
this, priority, child_name.c_str());
}
if (report_connecting) {
channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING,
absl::make_unique<QueuePicker>(Ref(DEBUG_LOCATION, "QueuePicker")));
}
return;
}
// Child has been failing for a while. Move on to the next priority.
}
// If there are no more priorities to try, report TRANSIENT_FAILURE.
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] no priority reachable, putting channel in "
"TRANSIENT_FAILURE",
this);
}
current_priority_ = UINT32_MAX;
current_child_from_before_update_ = nullptr;
grpc_error* error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("no ready priority"),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
absl::make_unique<TransientFailurePicker>(error));
}
void PriorityLb::SelectPriorityLocked(uint32_t priority) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] selected priority %d, child %s", this,
priority, config_->priorities()[priority].c_str());
}
current_priority_ = priority;
current_child_from_before_update_ = nullptr;
// Deactivate lower priorities.
for (uint32_t p = priority + 1; p < config_->priorities().size(); ++p) {
const std::string& child_name = config_->priorities()[p];
auto it = children_.find(child_name);
if (it != children_.end()) it->second->DeactivateLocked();
}
// Update picker.
auto& child = children_[config_->priorities()[priority]];
channel_control_helper()->UpdateState(child->connectivity_state(),
child->GetPicker());
}
//
// PriorityLb::ChildPriority
//
PriorityLb::ChildPriority::ChildPriority(
RefCountedPtr<PriorityLb> priority_policy, std::string name)
: priority_policy_(std::move(priority_policy)), name_(std::move(name)) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] creating child %s (%p)",
priority_policy_.get(), name_.c_str(), this);
}
GRPC_CLOSURE_INIT(&on_failover_timer_, OnFailoverTimer, this,
grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&on_failover_timer_locked_, OnFailoverTimerLocked, this,
nullptr);
// Start the failover timer.
StartFailoverTimerLocked();
}
void PriorityLb::ChildPriority::Orphan() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] child %s (%p): orphaned",
priority_policy_.get(), name_.c_str(), this);
}
MaybeCancelFailoverTimerLocked();
if (deactivation_timer_callback_pending_) {
grpc_timer_cancel(&deactivation_timer_);
}
// Remove the child policy's interested_parties pollset_set from the
// xDS policy.
grpc_pollset_set_del_pollset_set(child_policy_->interested_parties(),
priority_policy_->interested_parties());
child_policy_.reset();
// Drop our ref to the child's picker, in case it's holding a ref to
// the child.
picker_wrapper_.reset();
if (deactivation_timer_callback_pending_) {
grpc_timer_cancel(&deactivation_timer_);
}
Unref(DEBUG_LOCATION, "ChildPriority+Orphan");
}
void PriorityLb::ChildPriority::UpdateLocked(
RefCountedPtr<LoadBalancingPolicy::Config> config) {
if (priority_policy_->shutting_down_) return;
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] child %s (%p): start update",
priority_policy_.get(), name_.c_str(), this);
}
// Create policy if needed.
if (child_policy_ == nullptr) {
child_policy_ = CreateChildPolicyLocked(priority_policy_->args_);
}
// Construct update args.
UpdateArgs update_args;
update_args.config = std::move(config);
update_args.addresses = priority_policy_->addresses_[name_];
update_args.args = grpc_channel_args_copy(priority_policy_->args_);
// Update the policy.
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): updating child policy handler %p",
priority_policy_.get(), name_.c_str(), this, child_policy_.get());
}
child_policy_->UpdateLocked(std::move(update_args));
}
OrphanablePtr<LoadBalancingPolicy>
PriorityLb::ChildPriority::CreateChildPolicyLocked(
const grpc_channel_args* args) {
LoadBalancingPolicy::Args lb_policy_args;
lb_policy_args.combiner = priority_policy_->combiner();
lb_policy_args.args = args;
lb_policy_args.channel_control_helper =
absl::make_unique<Helper>(this->Ref(DEBUG_LOCATION, "Helper"));
OrphanablePtr<LoadBalancingPolicy> lb_policy =
MakeOrphanable<ChildPolicyHandler>(std::move(lb_policy_args),
&grpc_lb_priority_trace);
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): created new child policy "
"handler %p",
priority_policy_.get(), name_.c_str(), this, lb_policy.get());
}
// Add the parent's interested_parties pollset_set to that of the newly
// created child policy. This will make the child policy progress upon
// activity on the parent LB, which in turn is tied to the application's call.
grpc_pollset_set_add_pollset_set(lb_policy->interested_parties(),
priority_policy_->interested_parties());
return lb_policy;
}
void PriorityLb::ChildPriority::ExitIdleLocked() {
if (connectivity_state_ == GRPC_CHANNEL_IDLE &&
!failover_timer_callback_pending_) {
StartFailoverTimerLocked();
}
child_policy_->ExitIdleLocked();
}
void PriorityLb::ChildPriority::ResetBackoffLocked() {
child_policy_->ResetBackoffLocked();
}
void PriorityLb::ChildPriority::OnConnectivityStateUpdateLocked(
grpc_connectivity_state state, std::unique_ptr<SubchannelPicker> picker) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): state update: %s, picker %p",
priority_policy_.get(), name_.c_str(), this,
ConnectivityStateName(state), picker.get());
}
// Store the state and picker.
connectivity_state_ = state;
picker_wrapper_ = MakeRefCounted<RefCountedPicker>(std::move(picker));
// If READY or TRANSIENT_FAILURE, cancel failover timer.
if (state == GRPC_CHANNEL_READY || state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
MaybeCancelFailoverTimerLocked();
}
// Notify the parent policy.
priority_policy_->HandleChildConnectivityStateChangeLocked(this);
}
void PriorityLb::ChildPriority::StartFailoverTimerLocked() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): starting failover timer for %d ms",
priority_policy_.get(), name_.c_str(), this,
priority_policy_->child_failover_timeout_ms_);
}
Ref(DEBUG_LOCATION, "ChildPriority+OnFailoverTimerLocked").release();
grpc_timer_init(
&failover_timer_,
ExecCtx::Get()->Now() + priority_policy_->child_failover_timeout_ms_,
&on_failover_timer_);
failover_timer_callback_pending_ = true;
}
void PriorityLb::ChildPriority::MaybeCancelFailoverTimerLocked() {
if (failover_timer_callback_pending_) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): cancelling failover timer",
priority_policy_.get(), name_.c_str(), this);
}
grpc_timer_cancel(&failover_timer_);
failover_timer_callback_pending_ = false;
}
}
void PriorityLb::ChildPriority::OnFailoverTimer(void* arg, grpc_error* error) {
ChildPriority* self = static_cast<ChildPriority*>(arg);
self->priority_policy_->combiner()->Run(&self->on_failover_timer_locked_,
GRPC_ERROR_REF(error));
}
void PriorityLb::ChildPriority::OnFailoverTimerLocked(void* arg,
grpc_error* error) {
ChildPriority* self = static_cast<ChildPriority*>(arg);
if (error == GRPC_ERROR_NONE && self->failover_timer_callback_pending_ &&
!self->priority_policy_->shutting_down_) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): failover timer fired, "
"reporting TRANSIENT_FAILURE",
self->priority_policy_.get(), self->name_.c_str(), self);
}
self->failover_timer_callback_pending_ = false;
self->OnConnectivityStateUpdateLocked(GRPC_CHANNEL_TRANSIENT_FAILURE,
nullptr);
}
self->Unref(DEBUG_LOCATION, "ChildPriority+OnFailoverTimerLocked");
}
void PriorityLb::ChildPriority::DeactivateLocked() {
// If already deactivated, don't do it again.
if (deactivation_timer_callback_pending_) return;
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): deactivating -- will remove in %d "
"ms.",
priority_policy_.get(), name_.c_str(), this,
kChildRetentionIntervalMs);
}
MaybeCancelFailoverTimerLocked();
// Start a timer to delete the child.
Ref(DEBUG_LOCATION, "ChildPriority+timer").release();
GRPC_CLOSURE_INIT(&on_deactivation_timer_, OnDeactivationTimer, this,
grpc_schedule_on_exec_ctx);
grpc_timer_init(&deactivation_timer_,
ExecCtx::Get()->Now() + kChildRetentionIntervalMs,
&on_deactivation_timer_);
deactivation_timer_callback_pending_ = true;
}
void PriorityLb::ChildPriority::MaybeReactivateLocked() {
if (deactivation_timer_callback_pending_) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO, "[priority_lb %p] child %s (%p): reactivating",
priority_policy_.get(), name_.c_str(), this);
}
deactivation_timer_callback_pending_ = false;
grpc_timer_cancel(&deactivation_timer_);
}
}
void PriorityLb::ChildPriority::OnDeactivationTimer(void* arg,
grpc_error* error) {
ChildPriority* self = static_cast<ChildPriority*>(arg);
self->priority_policy_->combiner()->Run(
GRPC_CLOSURE_INIT(&self->on_deactivation_timer_,
OnDeactivationTimerLocked, self, nullptr),
GRPC_ERROR_REF(error));
}
void PriorityLb::ChildPriority::OnDeactivationTimerLocked(void* arg,
grpc_error* error) {
ChildPriority* self = static_cast<ChildPriority*>(arg);
if (error == GRPC_ERROR_NONE && self->deactivation_timer_callback_pending_ &&
!self->priority_policy_->shutting_down_) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_priority_trace)) {
gpr_log(GPR_INFO,
"[priority_lb %p] child %s (%p): deactivation timer fired, "
"deleting child",
self->priority_policy_.get(), self->name_.c_str(), self);
}
self->deactivation_timer_callback_pending_ = false;
self->priority_policy_->DeleteChild(self);
}
self->Unref(DEBUG_LOCATION, "ChildPriority+timer");
}
//
// PriorityLb::ChildPriority::Helper
//
void PriorityLb::ChildPriority::Helper::RequestReresolution() {
if (priority_->priority_policy_->shutting_down_) return;
priority_->priority_policy_->channel_control_helper()->RequestReresolution();
}
RefCountedPtr<SubchannelInterface>
PriorityLb::ChildPriority::Helper::CreateSubchannel(
const grpc_channel_args& args) {
if (priority_->priority_policy_->shutting_down_) return nullptr;
return priority_->priority_policy_->channel_control_helper()
->CreateSubchannel(args);
}
void PriorityLb::ChildPriority::Helper::UpdateState(
grpc_connectivity_state state, std::unique_ptr<SubchannelPicker> picker) {
if (priority_->priority_policy_->shutting_down_) return;
// Notify the priority.
priority_->OnConnectivityStateUpdateLocked(state, std::move(picker));
}
void PriorityLb::ChildPriority::Helper::AddTraceEvent(TraceSeverity severity,
StringView message) {
if (priority_->priority_policy_->shutting_down_) return;
priority_->priority_policy_->channel_control_helper()->AddTraceEvent(severity,
message);
}
//
// factory
//
class PriorityLbFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return MakeOrphanable<PriorityLb>(std::move(args));
}
const char* name() const override { return kPriority; }
RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const Json& json, grpc_error** error) const override {
GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE);
if (json.type() == Json::Type::JSON_NULL) {
// priority was mentioned as a policy in the deprecated
// loadBalancingPolicy field or in the client API.
*error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:loadBalancingPolicy error:priority policy requires "
"configuration. Please use loadBalancingConfig field of service "
"config instead.");
return nullptr;
}
std::vector<grpc_error*> error_list;
// Children.
std::map<std::string, RefCountedPtr<LoadBalancingPolicy::Config>> children;
auto it = json.object_value().find("children");
if (it == json.object_value().end()) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:children error:required field missing"));
} else if (it->second.type() != Json::Type::OBJECT) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:children error:type should be object"));
} else {
const Json::Object& object = it->second.object_value();
for (const auto& p : object) {
const std::string& child_name = p.first;
const Json& element = p.second;
if (element.type() != Json::Type::OBJECT) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("field:children key:", child_name,
" error:should be type object")
.c_str()));
} else {
auto it2 = element.object_value().find("config");
if (it2 == element.object_value().end()) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("field:children key:", child_name,
" error:missing 'config' field")
.c_str()));
} else {
grpc_error* parse_error = GRPC_ERROR_NONE;
auto config = LoadBalancingPolicyRegistry::ParseLoadBalancingConfig(
it2->second, &parse_error);
if (config == nullptr) {
GPR_DEBUG_ASSERT(parse_error != GRPC_ERROR_NONE);
error_list.push_back(
GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(
absl::StrCat("field:children key:", child_name).c_str(),
&parse_error, 1));
GRPC_ERROR_UNREF(parse_error);
}
children[child_name] = std::move(config);
}
}
}
}
// Priorities.
std::vector<std::string> priorities;
it = json.object_value().find("priorities");
if (it == json.object_value().end()) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:priorities error:required field missing"));
} else if (it->second.type() != Json::Type::ARRAY) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:priorities error:type should be array"));
} else {
const Json::Array& array = it->second.array_value();
for (size_t i = 0; i < array.size(); ++i) {
const Json& element = array[i];
if (element.type() != Json::Type::STRING) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("field:priorities element:", i,
" error:should be type string")
.c_str()));
} else if (children.find(element.string_value()) == children.end()) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("field:priorities element:", i,
" error:unknown child '", element.string_value(),
"'")
.c_str()));
} else {
priorities.emplace_back(element.string_value());
}
}
if (priorities.size() != children.size()) {
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("field:priorities error:priorities size (",
priorities.size(), ") != children size (",
children.size(), ")")
.c_str()));
}
}
if (error_list.empty()) {
return MakeRefCounted<PriorityLbConfig>(std::move(children),
std::move(priorities));
} else {
*error = GRPC_ERROR_CREATE_FROM_VECTOR(
"priority_experimental LB policy config", &error_list);
return nullptr;
}
}
};
} // namespace
} // namespace grpc_core
//
// Plugin registration
//
void grpc_lb_policy_priority_init() {
grpc_core::LoadBalancingPolicyRegistry::Builder::
RegisterLoadBalancingPolicyFactory(
absl::make_unique<grpc_core::PriorityLbFactory>());
}
void grpc_lb_policy_priority_shutdown() {}
|
/*
* Copyright (C) 2009-2014, Computing Systems Laboratory (CSLab), NTUA.
* Copyright (C) 2009-2011, Kornilios Kourtis
* Copyright (C) 2011-2014, Vasileios Karakasis
* Copyright (C) 2011-2012, Theodoros Gkountouvas
* Copyright (C) 2013, Athena Elafrou
* All rights reserved.
*
* This file is distributed under the BSD License. See LICENSE.txt for details.
*/
/**
* \file Csx.hpp
* \brief The CSX data structure (C front-end)
*
* \author Computing Systems Laboratory (CSLab), NTUA
* \date 2011–2014
* \copyright This file is distributed under the BSD License. See LICENSE.txt
* for details.
*/
#ifndef SPARSEX_INTERNALS_CSX_HPP
#define SPARSEX_INTERNALS_CSX_HPP
#include <sparsex/types.h>
#include <sparsex/internals/CtlUtil.hpp>
///< CSX matrix format
typedef struct {
spx_index_t rowptr; /* rowptr is the index in csx->ctl of
the first element of row i */
spx_index_t valptr; /* valptr is the index in csx->values of
the first element of row i */
spx_index_t span;
} row_info_t;
typedef struct {
spx_value_t *values;
uint8_t *ctl;
spx_index_t nnz;
spx_index_t ncols;
spx_index_t nrows;
spx_index_t ctl_size;
spx_index_t row_start;
uint8_t row_jumps;
long id_map[CTL_PATTERNS_MAX];
row_info_t *rows_info;
} csx_matrix_t;
typedef struct {
csx_matrix_t *lower_matrix;
spx_value_t *dvalues;
} csx_sym_matrix_t;
#ifdef __cplusplus
// C++ only
namespace sparsex {
namespace csx {
// FIXME: members of CsxMatrix MUST have the same order with csx_matrix_t
// This is error-prone with explicit casts between the two types
template<typename IndexType, typename ValueType>
struct CsxMatrix {
ValueType *values;
uint8_t *ctl;
IndexType nnz;
IndexType ncols;
IndexType nrows;
IndexType ctl_size;
IndexType row_start;
uint8_t row_jumps;
long id_map[CTL_PATTERNS_MAX];
row_info_t *rows_info;
};
template<typename IndexType, typename ValueType>
struct CsxSymMatrix {
CsxMatrix<IndexType, ValueType> *lower_matrix;
ValueType *dvalues;
};
} // end of namepsace csx
} // end of namepsace sparsex
#endif
#endif // SPARSEX_INTERNALS_CSX_HPP
|
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/assign/list_inserter.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <sstream>
#include <mutex>
#include <Brokers/Sina/sinadatafeed.h>
#include <Common/Util/util.h>
#include <Common/Order/orderstatus.h>
#include <Common/Logger/logger.h>
#include <Common/Data/datamanager.h>
#include <Common/Order/ordermanager.h>
class price_;
using namespace std;
using boost::asio::ip::tcp;
namespace EliteQuant
{
extern std::atomic<bool> gShutdown;
sinadatafeed::sinadatafeed() {
}
sinadatafeed::~sinadatafeed() {
}
// start http request thread
bool sinadatafeed::connectToMarketDataFeed()
{
return true;
}
// stop http request thread
void sinadatafeed::disconnectFromMarketDataFeed() {
}
// is http request thread running ?
bool sinadatafeed::isConnectedToMarketDataFeed() const {
return (!gShutdown); // automatic disconnect when shutdown
}
void sinadatafeed::processMarketMessages() {
if (!heatbeat(5)) {
disconnectFromMarketDataFeed();
return;
}
switch (_mkstate) {
case MK_ACCOUNT:
requestMarketDataAccountInformation(CConfig::instance().account);
break;
case MK_REQREALTIMEDATA:
subscribeMarketData();
break;
case MK_REQREALTIMEDATAACK:
Thread_GetQuoteLoop();
break;
}
}
void sinadatafeed::subscribeMarketData() {
ostringstream os;
//os << "/finance/info?q=" << "SPY,AAPL,VXX";
for (auto &s : CConfig::instance().securities)
{
auto sv = stringsplit(s, ' ');
if (sv[0].substr(0, 2) == "sh")
os << sv[0] << ","; // TODO: it ends with ","
}
//_path = "/list=" + os.str(); // hard code path for now
pricemap["usr_spy"] = 0.0;
pricemap["usr_aapl"] = 0.0;
pricemap["usr_amzn"] = 0.0;
pricemap["usr_tsla"] = 0.0;
pricemap["usr_googl"] = 0.0;
pricemap["usr_fb"] = 0.0;
pricemap["usr_bidu"] = 0.0;
pricemap["usr_baba"] = 0.0;
pricemap["usr_gs"] = 0.0;
pricemap["usr_jpm"] = 0.0;
pricemap["sh600028"] = 0.0;
pricemap["sh601857"] = 0.0;
pricemap["sh600036"] = 0.0;
pricemap["sh601668"] = 0.0;
pricemap["sh601988"] = 0.0;
pricemap["sh601166"] = 0.0;
pricemap["sh601377"] = 0.0;
pricemap["sh600958"] = 0.0;
_mkstate = MK_REQREALTIMEDATAACK;
}
void sinadatafeed::unsubscribeMarketData(TickerId reqId) {
}
void sinadatafeed::subscribeMarketDepth() {
}
void sinadatafeed::unsubscribeMarketDepth(TickerId reqId) {
}
void sinadatafeed::subscribeRealTimeBars(TickerId id, const Security& security, int barSize, const string& whatToShow, bool useRTH) {
}
void sinadatafeed::unsubscribeRealTimeBars(TickerId tickerId) {
}
void sinadatafeed::requestContractDetails() {
}
void sinadatafeed::requestHistoricalData(string contract, string enddate, string duration, string barsize, string useRTH) {
}
void sinadatafeed::requestMarketDataAccountInformation(const string& account)
{
if (_mkstate <= MK_REQREALTIMEDATA)
_mkstate = MK_REQREALTIMEDATA;
}
////////////////////////////////////////////////////// worker function ///////////////////////////////////////
void sinadatafeed::Thread_GetQuoteLoop()
{
std::string res = "";
while (!gShutdown) {
try {
boost::asio::io_service io_service;
// Get a list of endpoints corresponding to the server name.
tcp::resolver resolver(io_service);
tcp::resolver::query query(_host, "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
// Try each endpoint until we successfully establish a connection.
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end) {
socket.close();
socket.connect(*endpoint_iterator++, error);
}
if (error) { throw boost::system::system_error(error); }
// Form the request. We specify the "Connection: close" header so that the server will close the socket
// after transmitting the response. This will allow us to treat all data up until the EOF as the content.
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET " << _path << " HTTP/1.0\r\n";
request_stream << "Host: " << _host << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";
// Send the request.
boost::asio::write(socket, request);
// Read the response status line.
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
// Check that response is OK.
std::istream response_stream(&response);
std::string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
std::cout << "Invalid response\n";
}
if (status_code != 200) {
std::cout << "Response returned with status code " << status_code << "\n";
}
// Read the response headers, which are terminated by a blank line.
boost::asio::read_until(socket, response, "\r\n\r\n");
// Write whatever content we already have to output.
if (response.size() > 0) {
std::ostringstream oss;
oss << &response;
res = oss.str();
}
//std::cout << res << std::endl;
// Read until EOF, writing data to output as we go.
while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) {
//std::cout << &response; // don't want to print just return
std::ostringstream oss;
oss << &response;
res += oss.str();
}
//std::cout << res << std::endl;
if (error != boost::asio::error::eof) { throw boost::system::system_error(error); }
// split string
std::vector<string> strs;
boost::split(strs, res, boost::is_any_of("\n"));
//cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++) {
if (strs[i].find("var") != std::string::npos)
{
std::size_t pos1 = strs[i].find("_str_");
std::size_t pos2 = strs[i].find("=");
std::string symbol = strs[i].substr(pos1 + 5, pos2 - pos1 - 5);
std::vector<string> str2;
boost::split(str2, strs[i], boost::is_any_of(","));
//cout << "symbol = " << symbol << " price = " << price << endl;
Tick k;
time_t current_time;
time(¤t_time);
k.time_ = tointtime(current_time);
k.datatype_ = DataType::DT_TradePrice;
string price;
if (symbol.substr(0, 3) == "usr") {
price = str2[1];
k.fullsymbol_ = boost::to_upper_copy<std::string>(symbol.substr(4)) + " STK SMART";
}
else {
price = str2[3];
k.fullsymbol_ = symbol;
}
double price_tmp = atof(price.c_str());
if (price_tmp == pricemap[symbol]) {
pricemap[symbol] = price_tmp - 0.01;
k.price_ = price_tmp - 0.01;
}
else {
pricemap[symbol] = price_tmp;
k.price_ = price_tmp;
}
k.size_ = 100; // TODO: use actual size
msgq_pub_->sendmsg(k.serialize());
msleep(50);
}
}
}
catch (std::exception& e) {
std::cout << "Exception: " << e.what() << "\n";
}
msleep(1000);
}
}
}
|
#include <Model/ArrSessionManager.h>
#include <QDebug>
#include <ViewModel/ModelEditor/Scene/SceneTreeModel.h>
SceneTreeModel::SceneTreeModel(ArrSessionManager* sessionManager, QObject* parent)
: QAbstractItemModel(parent)
, m_sessionManager(sessionManager)
{
QObject::connect(sessionManager, &ArrSessionManager::sessionAboutToChange, this, [this]() {
reset(true);
});
QObject::connect(sessionManager, &ArrSessionManager::sessionChanged, this, [this]() {
reset();
});
QObject::connect(sessionManager, &ArrSessionManager::rootIdChanged, this, [this]() {
reset();
});
reset();
}
void SceneTreeModel::reset(bool makeEmpty)
{
QAbstractItemModel::beginResetModel();
m_indices.clear();
RR::ApiHandle<RR::Entity> root = nullptr;
if (m_sessionManager->loadedModel())
{
root = m_sessionManager->loadedModel()->GetRoot();
}
m_rootItem.reset(new EntityCache(root, QModelIndex()));
if (makeEmpty)
{
m_rootItem->m_childrenComputed = true;
}
m_indices.insert(root ? root : RR::ApiHandle<RR::Entity>(), QModelIndex());
QAbstractItemModel::endResetModel();
}
QModelIndex SceneTreeModel::index(int row, int column, const QModelIndex& parent) const
{
auto* cachedItem = toCachedItem(parent);
cachedItem->ensureChildrenComputed(this, parent);
const auto& children = cachedItem->m_children;
#ifdef QT_DEBUG
// this check is only to avoid a crash in an assert in QAbstractItemView::setModel
// which has the assumption that the model has at least one item under the root item
if (row >= children.size())
{
return {};
}
#endif
return createIndex(row, column, children[row]);
}
SceneTreeModel::EntityCache* SceneTreeModel::toCachedItem(const QModelIndex& index) const
{
if (!index.isValid())
{
return m_rootItem.get();
}
else
{
return reinterpret_cast<SceneTreeModel::EntityCache*>(index.internalPointer());
}
}
RR::ApiHandle<RR::Entity> SceneTreeModel::getEntityFromIndex(const QModelIndex& index) const
{
if (auto* item = toCachedItem(index))
{
return item->m_entity;
}
else
{
return {};
}
}
QModelIndex SceneTreeModel::getIndexFromEntity(const RR::ApiHandle<RR::Entity>& entity) const
{
auto it_first = m_indices.find(entity);
if (it_first != m_indices.end())
{
return it_first.value();
}
else
{
// couldn't find the index. It could mean it's not expanded yet.
// expand based on the parent chain
QList<RR::ApiHandle<RR::Entity>> parents;
RR::ApiHandle<RR::Entity> parent = nullptr;
if (entity && entity->GetValid())
{
parent = entity->GetParent();
}
while (parent)
{
parents.push_front(parent);
if (m_indices.contains(parent))
{
break;
}
parent = parent->GetParent();
}
if (!parent)
{
// couldn't find any matching index in any of the parent chain
return {};
}
// traverse in reverse order and expand
for (const RR::ApiHandle<RR::Entity>& p : parents)
{
auto it = m_indices.find(p);
if (it == m_indices.end())
{
qCritical() << tr("Error: can't find index in scene tree model");
return {};
}
QModelIndex index = it.value();
// trigger the child computation
this->index(index.row(), index.column(), index);
}
// try again. It should return
auto it = m_indices.find(entity);
if (it != m_indices.end())
{
return it.value();
}
else
{
qCritical() << tr("Error: can't find index in scene tree model");
}
}
return {};
}
QVariant SceneTreeModel::data(const QModelIndex& index, int role) const
{
return toCachedItem(index)->data(m_sessionManager, role);
}
QModelIndex SceneTreeModel::parent(const QModelIndex& index) const
{
return toCachedItem(index)->m_parent;
}
int SceneTreeModel::rowCount(const QModelIndex& parent) const
{
auto* cachedItem = toCachedItem(parent);
cachedItem->ensureChildrenComputed(this, parent);
return cachedItem->m_children.size();
}
SceneTreeModel::EntityCache::EntityCache(RR::ApiHandle<RR::Entity> entity, QModelIndex parent)
: m_parent(parent)
, m_entity(std::move(entity))
{
}
SceneTreeModel::EntityCache::~EntityCache()
{
for (auto* child : m_children)
{
delete child;
}
}
QVariant SceneTreeModel::EntityCache::data(ArrSessionManager* sessionManager, int role) const
{
if (auto clientApi = sessionManager->getClientApi())
{
switch (role)
{
case Qt::DisplayRole:
{
if (m_entity && m_entity->GetValid())
{
std::string name;
m_entity->GetName(name);
return QString::fromStdString(name);
}
return QString();
}
}
}
return {};
}
void SceneTreeModel::EntityCache::ensureChildrenComputed(const SceneTreeModel* model, QModelIndex thisModelIndex)
{
if (!m_childrenComputed)
{
m_childrenComputed = true;
if (auto clientApi = model->m_sessionManager->getClientApi())
{
if (m_entity && m_entity->GetValid())
{
int childNumber = 0;
std::vector<RR::ApiHandle<RR::Entity>> children;
m_entity->GetChildren(children);
for (auto&& child : children)
{
m_children.push_back(new EntityCache(child, thisModelIndex));
model->m_indices.insert(child, model->index(childNumber++, 0, thisModelIndex));
}
}
}
}
}
|
#include "pch.h"
#include "ElementParserRegistration.h"
#include "ChoiceSetInput.h"
#include "ColumnSet.h"
#include "Container.h"
#include "DateInput.h"
#include "FactSet.h"
#include "Image.h"
#include "ImageSet.h"
#include "Media.h"
#include "NumberInput.h"
#include "TextBlock.h"
#include "TextInput.h"
#include "TimeInput.h"
#include "ToggleInput.h"
#include "UnknownElement.h"
namespace AdaptiveSharedNamespace {
ElementParserRegistration::ElementParserRegistration()
{
m_knownElements.insert({
CardElementTypeToString(CardElementType::Container),
CardElementTypeToString(CardElementType::ColumnSet),
CardElementTypeToString(CardElementType::FactSet),
CardElementTypeToString(CardElementType::Image),
CardElementTypeToString(CardElementType::ImageSet),
CardElementTypeToString(CardElementType::ChoiceSetInput),
CardElementTypeToString(CardElementType::DateInput),
CardElementTypeToString(CardElementType::Media),
CardElementTypeToString(CardElementType::NumberInput),
CardElementTypeToString(CardElementType::TextBlock),
CardElementTypeToString(CardElementType::TextInput),
CardElementTypeToString(CardElementType::TimeInput),
CardElementTypeToString(CardElementType::ToggleInput),
CardElementTypeToString(CardElementType::Unknown),
});
m_cardElementParsers.insert({
{ CardElementTypeToString(CardElementType::Container), std::make_shared<ContainerParser>() },
{ CardElementTypeToString(CardElementType::ColumnSet), std::make_shared<ColumnSetParser>() },
{ CardElementTypeToString(CardElementType::FactSet), std::make_shared<FactSetParser>() },
{ CardElementTypeToString(CardElementType::Image), std::make_shared<ImageParser>() },
{ CardElementTypeToString(CardElementType::ImageSet), std::make_shared<ImageSetParser>() },
{ CardElementTypeToString(CardElementType::ChoiceSetInput), std::make_shared<ChoiceSetInputParser>() },
{ CardElementTypeToString(CardElementType::DateInput), std::make_shared<DateInputParser>() },
{ CardElementTypeToString(CardElementType::Media), std::make_shared<MediaParser>() },
{ CardElementTypeToString(CardElementType::NumberInput), std::make_shared<NumberInputParser>() },
{ CardElementTypeToString(CardElementType::TextBlock), std::make_shared<TextBlockParser>() },
{ CardElementTypeToString(CardElementType::TextInput), std::make_shared<TextInputParser>() },
{ CardElementTypeToString(CardElementType::TimeInput), std::make_shared<TimeInputParser>() },
{ CardElementTypeToString(CardElementType::ToggleInput), std::make_shared<ToggleInputParser>() },
{ CardElementTypeToString(CardElementType::Unknown), std::make_shared<UnknownElementParser>() }
});
}
void ElementParserRegistration::AddParser(std::string const &elementType, std::shared_ptr<BaseCardElementParser> parser)
{
if (m_knownElements.find(elementType) == m_knownElements.end())
{
ElementParserRegistration::m_cardElementParsers[elementType] = parser;
}
else
{
throw AdaptiveCardParseException(ErrorStatusCode::UnsupportedParserOverride, "Overriding known element parsers is unsupported");
}
}
void ElementParserRegistration::RemoveParser(std::string const &elementType)
{
if (m_knownElements.find(elementType) == m_knownElements.end())
{
ElementParserRegistration::m_cardElementParsers.erase(elementType);
}
else
{
throw AdaptiveCardParseException(ErrorStatusCode::UnsupportedParserOverride, "Overriding known element parsers is unsupported");
}
}
std::shared_ptr<BaseCardElementParser> ElementParserRegistration::GetParser(std::string const &elementType)
{
auto parser = m_cardElementParsers.find(elementType);
if (parser != ElementParserRegistration::m_cardElementParsers.end())
{
return parser->second;
}
else
{
return std::shared_ptr<BaseCardElementParser>(nullptr);
}
}
}
|
/**
* @file CpuRaw.cpp
* @brief CpuRaw class implementation.
* @author zer0
* @date 2018-01-10
*/
#include <libtbag/gpu/cpu/CpuRaw.hpp>
#include <libtbag/log/Log.hpp>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace gpu {
namespace cpu {
// ---------------
namespace __impl {
// ---------------
template <typename T>
static bool addByCpu(T const * v1, T const * v2, T * r, int count)
{
for (; count > 0; ++v1, ++v2, ++r, --count) {
*r = *v1 + *v2;
}
return true;
}
// --------------------
} // namespace __impl {
// --------------------
bool runCpuAdd1i(int const * v1, int const * v2, int * r, int count)
{ return __impl::addByCpu(v1, v2, r, count); }
bool runCpuAdd1u(unsigned const * v1, unsigned const * v2, unsigned * r, int count)
{ return __impl::addByCpu(v1, v2, r, count); }
bool runCpuAdd1f(float const * v1, float const * v2, float * r, int count)
{ return __impl::addByCpu(v1, v2, r, count); }
bool runCpuAdd1d(double const * v1, double const * v2, double * r, int count)
{ return __impl::addByCpu(v1, v2, r, count); }
} // namespace cpu
} // namespace gpu
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
|
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/application/common/application_storage_constants.h"
#include "base/strings/stringprintf.h"
namespace xwalk {
namespace application_storage_constants {
const char kAppTableName[] = "applications";
const char kPermissionTableName[] = "stored_permissions";
const char kGarbageCollectionTableName[] = "garbage_collection";
const char kCreateAppTableOp[] =
"CREATE TABLE applications ("
"id TEXT NOT NULL UNIQUE PRIMARY KEY,"
"manifest TEXT NOT NULL,"
"path TEXT NOT NULL,"
"install_time REAL)";
const char kCreatePermissionTableOp[] =
"CREATE TABLE stored_permissions ("
"id TEXT NOT NULL,"
"permission_names TEXT NOT NULL,"
"PRIMARY KEY (id),"
"FOREIGN KEY (id) REFERENCES applications(id)"
"ON DELETE CASCADE)";
const char kGetRowFromAppTableOp[] =
"SELECT A.id, A.manifest, A.path, A.install_time, "
"C.permission_names FROM applications as A "
"LEFT JOIN stored_permissions as C "
"ON A.id = C.id WHERE A.id = ?";
const char kGetAllRowsFromAppTableOp[] =
"SELECT A.id, A.manifest, A.path, A.install_time, "
"C.permission_names FROM applications as A "
"LEFT JOIN stored_permissions as C "
"ON A.id = C.id";
extern const char kGetAllIDsFromAppTableOp[] =
"SELECT id FROM applications";
const char kSetApplicationWithBindOp[] =
"INSERT INTO applications (manifest, path, install_time, id) "
"VALUES (?,?,?,?)";
const char kUpdateApplicationWithBindOp[] =
"UPDATE applications SET manifest = ?, path = ?,"
"install_time = ? WHERE id = ?";
const char kDeleteApplicationWithBindOp[] =
"DELETE FROM applications WHERE id = ?";
const char kInsertPermissionsWithBindOp[] =
"INSERT INTO stored_permissions (permission_names, id) "
"VALUES(?,?)";
const char kUpdatePermissionsWithBindOp[] =
"UPDATE stored_permissions SET permission_names = ? WHERE id = ?";
const char kDeletePermissionsWithBindOp[] =
"DELETE FROM stored_permissions WHERE id = ?";
} // namespace application_storage_constants
} // namespace xwalk
|
#include "taglistentry.hpp"
namespace clover {
namespace ui { namespace hid {
util::Map<ContextChannel::Name, TagListEntry::TagList> TagListEntry::tagLists;
TagListEntry::TagListEntry(const ContextChannel::Name& channel_name_, const Context::Tag& tag_)
: channelName(channel_name_)
, tag(tag_)
, iterator(endIter()){
appendToList();
}
TagListEntry::TagListEntry( const ContextChannel::Name& channel_name_,
const Context::Tag& tag_,
const Context::Tag& super_tag_)
: channelName(channel_name_)
, tag(tag_)
, superTag(super_tag_)
, iterator(endIter()){
appendToList();
}
TagListEntry::TagListEntry(const TagListEntry& other)
: channelName(other.channelName)
, tag(other.tag)
, superTag(other.superTag)
, iterator(endIter()){
appendToList();
}
TagListEntry::TagListEntry(TagListEntry&& other)
: iterator(endIter()){
*this = std::move(other);
}
TagListEntry::~TagListEntry(){
removeFromList();
}
TagListEntry& TagListEntry::operator=(const TagListEntry& other){
removeFromList();
channelName= other.channelName;
tag= other.tag;
superTag= other.superTag;
iterator= endIter();
appendToList();
return *this;
}
TagListEntry& TagListEntry::operator=(TagListEntry&& other){
removeFromList();
channelName= other.channelName;
tag= other.tag;
superTag= other.superTag;
iterator= other.iterator;
other.iterator= other.endIter();
return *this;
}
bool TagListEntry::isSet() const {
return iterator != endIter();
}
auto TagListEntry::endIter() const -> TagList::Iter {
return tagLists[channelName].end();
}
void TagListEntry::appendToList(){
ensure(iterator == endIter());
if (tag.length() == 0)
return;
auto& list= tagLists[channelName];
if (superTag.length() == 0){
iterator= list.insert(endIter(), tag);
}
else {
auto last_found= list.end();
for (auto it= list.begin(); it != list.end(); ++it){
if (*it == superTag)
last_found= std::next(it);
}
iterator= list.insert(last_found, tag);
}
ensure(iterator != tagLists[channelName].end());
if (iterator == std::prev(list.end(), 1)){
global::Event e(global::Event::OnHidTagChange);
e(global::Event::ContextChannelName)= channelName;
e(global::Event::Tag)= tag;
e.send();
}
#if 0
print(debug::Ch::General, debug::Vb::Critical, "Channel %s", channelName.cStr());
for (auto&& m : tagLists[channelName]){
print(debug::Ch::General, debug::Vb::Trivial, " %s", m.cStr());
}
#endif
}
void TagListEntry::removeFromList(){
TagList& list= tagLists[channelName];
if (iterator != list.end()){
list.erase(iterator);
iterator= list.end();
Context::Tag tag= ""; // Empty tag == no tag
if (!list.empty())
tag= list.back();
global::Event e(global::Event::OnHidTagChange);
e(global::Event::ContextChannelName)= channelName;
e(global::Event::Tag)= tag;
e.send();
}
}
}} // ui::hid
} // clover
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fs/transaction/writeback.h>
#include <zircon/assert.h>
#include <zxtest/zxtest.h>
namespace fs {
namespace {
// Number of device blocks per operation block.
constexpr uint32_t kDiskBlockRatio = 2;
class MockTransactionHandler : public LegacyTransactionHandler {
public:
using TransactionCallback =
fit::function<zx_status_t(const block_fifo_request_t* requests, size_t count)>;
MockTransactionHandler() = default;
virtual ~MockTransactionHandler() { EXPECT_EQ(transactions_expected_, transactions_seen_); }
void SetTransactionCallbacks(TransactionCallback* callbacks, size_t expected) {
callbacks_ = callbacks;
transactions_expected_ = expected;
transactions_seen_ = 0;
}
uint32_t FsBlockSize() const final {
return DeviceBlockSize() * static_cast<uint32_t>(kDiskBlockRatio);
}
uint32_t DeviceBlockSize() const final { return 8192; }
uint64_t BlockNumberToDevice(uint64_t block_num) const final { return block_num; }
block_client::BlockDevice* GetDevice() final { return nullptr; }
zx_status_t Transaction(block_fifo_request_t* requests, size_t count) override {
EXPECT_LT(transactions_seen_, transactions_expected_);
return callbacks_[transactions_seen_++](requests, count);
}
private:
TransactionCallback* callbacks_ = nullptr;
size_t transactions_expected_ = 0;
size_t transactions_seen_ = 0;
};
TEST(FlushRequestsTest, FlushNoRequests) {
class TestTransactionHandler : public MockTransactionHandler {
zx_status_t Transaction(block_fifo_request_t* requests, size_t count) final {
ZX_ASSERT_MSG(false, "Zero requests should not invoke the Transaction operation");
}
} handler;
fbl::Vector<storage::BufferedOperation> operations;
EXPECT_OK(FlushRequests(&handler, operations));
}
TEST(FlushRequestsTest, FlushOneRequest) {
static constexpr vmoid_t kVmoid = 4;
class TestTransactionHandler : public MockTransactionHandler {
zx_status_t Transaction(block_fifo_request_t* requests, size_t count) final {
if (count != 1) {
ADD_FAILURE("Unexpected count");
return ZX_ERR_OUT_OF_RANGE;
}
EXPECT_EQ(1 * kDiskBlockRatio, requests[0].vmo_offset);
EXPECT_EQ(2 * kDiskBlockRatio, requests[0].dev_offset);
EXPECT_EQ(3 * kDiskBlockRatio, requests[0].length);
EXPECT_EQ(kVmoid, requests[0].vmoid);
return ZX_OK;
}
} handler;
fbl::Vector<storage::BufferedOperation> operations;
operations.push_back(storage::BufferedOperation{
kVmoid, storage::Operation{storage::OperationType::kWrite, 1, 2, 3}});
EXPECT_OK(FlushRequests(&handler, operations));
}
TEST(FlushRequestsTest, FlushManyRequests) {
static constexpr vmoid_t kVmoidA = 7;
static constexpr vmoid_t kVmoidB = 8;
class TestTransactionHandler : public MockTransactionHandler {
zx_status_t Transaction(block_fifo_request_t* requests, size_t count) final {
if (count != 2) {
ADD_FAILURE("Unexpected count");
return ZX_ERR_OUT_OF_RANGE;
}
EXPECT_EQ(1 * kDiskBlockRatio, requests[0].vmo_offset);
EXPECT_EQ(2 * kDiskBlockRatio, requests[0].dev_offset);
EXPECT_EQ(3 * kDiskBlockRatio, requests[0].length);
EXPECT_EQ(4 * kDiskBlockRatio, requests[1].vmo_offset);
EXPECT_EQ(5 * kDiskBlockRatio, requests[1].dev_offset);
EXPECT_EQ(6 * kDiskBlockRatio, requests[1].length);
EXPECT_EQ(kVmoidA, requests[0].vmoid);
EXPECT_EQ(kVmoidB, requests[1].vmoid);
return ZX_OK;
}
} handler;
fbl::Vector<storage::BufferedOperation> operations;
operations.push_back(storage::BufferedOperation{
kVmoidA, storage::Operation{storage::OperationType::kWrite, 1, 2, 3}});
operations.push_back(storage::BufferedOperation{
kVmoidB, storage::Operation{storage::OperationType::kWrite, 4, 5, 6}});
EXPECT_OK(FlushRequests(&handler, operations));
}
// This acts as a regression test against a previous implementation of
// "FlushRequests", which could pop the stack with a large enough number
// of requests. The new implementation utilizes heap allocation when necessary,
// and should be able to withstand very large request counts.
TEST(FlushRequestsTest, FlushAVeryLargeNumberOfRequests) {
static constexpr vmoid_t kVmoid = 7;
static constexpr size_t kOperationCount = 10000;
class TestTransactionHandler : public MockTransactionHandler {
zx_status_t Transaction(block_fifo_request_t* requests, size_t count) final {
if (count != kOperationCount) {
ADD_FAILURE("Unexpected count");
return ZX_ERR_OUT_OF_RANGE;
}
for (size_t i = 0; i < count; i++) {
EXPECT_EQ(i * 2 * kDiskBlockRatio, requests[i].vmo_offset);
EXPECT_EQ(i * 2 * kDiskBlockRatio, requests[i].dev_offset);
EXPECT_EQ(1 * kDiskBlockRatio, requests[i].length);
EXPECT_EQ(kVmoid, requests[i].vmoid);
}
return ZX_OK;
}
} handler;
fbl::Vector<storage::BufferedOperation> operations;
for (size_t i = 0; i < kOperationCount; i++) {
operations.push_back(storage::BufferedOperation{
kVmoid, storage::Operation{storage::OperationType::kWrite, i * 2, i * 2, 1}});
}
EXPECT_OK(FlushRequests(&handler, operations));
}
TEST(FlushRequestsTest, BadFlush) {
class TestTransactionHandler : public MockTransactionHandler {
zx_status_t Transaction(block_fifo_request_t* requests, size_t count) final {
return ZX_ERR_NOT_SUPPORTED;
}
} handler;
fbl::Vector<storage::BufferedOperation> operations;
operations.push_back(
storage::BufferedOperation{1, storage::Operation{storage::OperationType::kWrite, 1, 2, 3}});
EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, FlushRequests(&handler, operations));
}
TEST(FlushRequestsTest, FlushTrimRequest) {
static constexpr vmoid_t kVmoid = 4;
class TestTransactionHandler : public MockTransactionHandler {
zx_status_t Transaction(block_fifo_request_t* requests, size_t count) final {
if (count != 1) {
ADD_FAILURE("Unexpected count");
return ZX_ERR_OUT_OF_RANGE;
}
EXPECT_EQ(BLOCKIO_TRIM, requests[0].opcode);
EXPECT_EQ(2 * kDiskBlockRatio, requests[0].dev_offset);
EXPECT_EQ(3 * kDiskBlockRatio, requests[0].length);
return ZX_OK;
}
} handler;
fbl::Vector<storage::BufferedOperation> operations;
operations.push_back(
storage::BufferedOperation{kVmoid,
storage::Operation{storage::OperationType::kTrim, 1, 2, 3}});
EXPECT_OK(FlushRequests(&handler, operations));
}
} // namespace
} // namespace fs
|
/*
Copyright 2017 Glen Joseph Fernandes
<glenjofe -at- gmail.com>
Distributed under the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt
or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "test.hpp"
#include "check_type.hpp"
#ifdef TEST_STD
#include <type_traits>
#else
#include <boost/type_traits/make_void.hpp>
#endif
TT_TEST_BEGIN(make_void)
BOOST_CHECK_TYPE(::tt::make_void<int>::type, void);
BOOST_CHECK_TYPE(::tt::make_void<const volatile int>::type, void);
BOOST_CHECK_TYPE(::tt::make_void<int&>::type, void);
BOOST_CHECK_TYPE(::tt::make_void<void>::type, void);
BOOST_CHECK_TYPE(::tt::make_void<int(*)(int)>::type, void);
BOOST_CHECK_TYPE(::tt::make_void<int[]>::type, void);
BOOST_CHECK_TYPE(::tt::make_void<int[1]>::type, void);
BOOST_CHECK_TYPE(::tt::make_void<>::type, void);
BOOST_CHECK_TYPE3(::tt::make_void<int, int>::type, void);
#ifndef BOOST_NO_CXX11_TEMPLATE_ALIASES
BOOST_CHECK_TYPE(::tt::void_t<int>, void);
BOOST_CHECK_TYPE(::tt::void_t<const volatile int>, void);
BOOST_CHECK_TYPE(::tt::void_t<int&>, void);
BOOST_CHECK_TYPE(::tt::void_t<void>, void);
BOOST_CHECK_TYPE(::tt::void_t<int(*)(int)>, void);
BOOST_CHECK_TYPE(::tt::void_t<int[]>, void);
BOOST_CHECK_TYPE(::tt::void_t<int[1]>, void);
BOOST_CHECK_TYPE(::tt::void_t<>, void);
BOOST_CHECK_TYPE3(::tt::void_t<int, int>, void);
#endif
TT_TEST_END
|
#include "Angular_Discretization_Factory.hh"
#include "Angular_Discretization.hh"
#include "Gauss_Legendre_Quadrature.hh"
#include "LDFE_Quadrature.hh"
using namespace std;
Angular_Discretization_Factory::
Angular_Discretization_Factory()
{
}
shared_ptr<Angular_Discretization> Angular_Discretization_Factory::
get_angular_discretization(int dimension,
int number_of_moments,
int angular_rule)
{
if (dimension == 1)
{
return make_shared<Gauss_Legendre_Quadrature>(dimension,
number_of_moments,
angular_rule);
}
else
{
return make_shared<LDFE_Quadrature>(dimension,
number_of_moments,
angular_rule);
}
}
|
#include "../PVZ.h"
PVZ::Lawnmover::Lawnmover(int indexoraddress)
{
if (indexoraddress > 1024)
BaseAddress = indexoraddress;
else
BaseAddress = Memory::ReadMemory<int>(PVZBASEADDRESS + 0x100) + indexoraddress * 0x48;
#if _DEBUG
DebugType = Type;
#endif
}
|
#include "objects.h"
#include "objects/objects.h"
#include "BlinkerSystem.h"
#include "scb/ScbHal.h"
#include "rcc/RccHal.h"
#include "flash/FlashHal.h"
#include "pwr/PwrHal.h"
#include "gpio/GpioDriver.h"
#include "systick/SysTickHal.h"
#include <array>
#include "irq/IrqAdapterTable.h"
#include "irq.h"
namespace stm32::objects {
using namespace stm32::hal;
using namespace stm32::irq;
using namespace stm32::system;
template<>
system::System& getObject<system::System>()
{
static system::BlinkerSystem system(
getObject<ScbHal>(),
getObject<RccHal>(),
getObject<FlashHal>(),
getObject<PwrHal>(),
getObject<SysTickHal>(),
getObject<GpioDriver>(),
getObject<IrqManager<IrqNumber>>()
);
return system;
}
const IrqAdapterPointer* getIrqVectorTable()
{
__attribute__ (( section (".irq_vector_table")))
static const std::array<IrqAdapterPointer, IrqNumber> IrqVectorTable = IrqAdapterTable<IrqNumber>::Table;
return reinterpret_cast<IrqAdapterPointer const*>(IrqVectorTable.data());
}
} // namespace
|
#include "stdafx.h"
#include "PonyGameXInput.h"
bool PonyGame::ButtonPressed(const int userIndex, WORD button)
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
DWORD dwResult = XInputGetState(userIndex, &state);
return dwResult == ERROR_SUCCESS && state.Gamepad.wButtons & button;
}
PONYGAMENATIVE_API bool DPadUpPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_DPAD_UP);
}
PONYGAMENATIVE_API bool DPadDownPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_DPAD_DOWN);
}
PONYGAMENATIVE_API bool DPadLeftPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_DPAD_LEFT);
}
PONYGAMENATIVE_API bool DPadRightPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_DPAD_RIGHT);
}
PONYGAMENATIVE_API bool StartButtonPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_START);
}
PONYGAMENATIVE_API bool BackButtonPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_BACK);
}
PONYGAMENATIVE_API bool LeftThumbPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_LEFT_THUMB);
}
PONYGAMENATIVE_API bool RightThumbPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_RIGHT_THUMB);
}
PONYGAMENATIVE_API bool LeftShoulderButtonPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_LEFT_SHOULDER);
}
PONYGAMENATIVE_API bool RightShoulderButtonPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_RIGHT_SHOULDER);
}
PONYGAMENATIVE_API bool ButtonAPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_A);
}
PONYGAMENATIVE_API bool ButtonBPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_B);
}
PONYGAMENATIVE_API bool ButtonXPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_X);
}
PONYGAMENATIVE_API bool ButtonYPressed(const int userIndex)
{
return PonyGame::ButtonPressed(userIndex, XINPUT_GAMEPAD_Y);
}
PONYGAMENATIVE_API float GetLeftTrigger(const int userIndex)
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
DWORD dwResult = XInputGetState(userIndex, &state);
return dwResult == ERROR_SUCCESS && state.Gamepad.bLeftTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD
? state.Gamepad.bLeftTrigger / 256.0f
: 0.0f;
}
PONYGAMENATIVE_API float GetRightTrigger(const int userIndex)
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
DWORD dwResult = XInputGetState(userIndex, &state);
return dwResult == ERROR_SUCCESS && state.Gamepad.bRightTrigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD
? state.Gamepad.bRightTrigger / 256.0f
: 0.0f;
}
PONYGAMENATIVE_API float GetLeftThumbX(const int userIndex)
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
DWORD dwResult = XInputGetState(userIndex, &state);
return dwResult == ERROR_SUCCESS && abs(state.Gamepad.sThumbLX) > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE
? state.Gamepad.sThumbLX / 32767.0f
: 0.0f;
}
PONYGAMENATIVE_API float GetLeftThumbY(const int userIndex)
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
DWORD dwResult = XInputGetState(userIndex, &state);
return dwResult == ERROR_SUCCESS && abs(state.Gamepad.sThumbLY) > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE
? state.Gamepad.sThumbLY / 32767.0f
: 0.0f;
}
PONYGAMENATIVE_API float GetRightThumbX(const int userIndex)
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
DWORD dwResult = XInputGetState(userIndex, &state);
return dwResult == ERROR_SUCCESS && abs(state.Gamepad.sThumbRX) > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE
? state.Gamepad.sThumbRX / 32767.0f
: 0.0f;
}
PONYGAMENATIVE_API float GetRightThumbY(const int userIndex)
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
DWORD dwResult = XInputGetState(userIndex, &state);
return dwResult == ERROR_SUCCESS && abs(state.Gamepad.sThumbRY) > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE
? state.Gamepad.sThumbRY / 32767.0f
: 0.0f;
}
PONYGAMENATIVE_API void SetVibration(const int userIndex, const float leftMotorSpeed, const float rightMotorSpeed)
{
XINPUT_VIBRATION vibration;
ZeroMemory(&vibration, sizeof(XINPUT_VIBRATION));
vibration.wLeftMotorSpeed = (WORD)(leftMotorSpeed * 65535);
vibration.wRightMotorSpeed = (WORD)(rightMotorSpeed * 65535);
XInputSetState(userIndex, &vibration);
}
|
#include<iostream>
#include<process.h>
#include "../include/operation.h"
void menu_choice(INFO *info){
// if (info->_page > 100) return ;
std::cout << "\n_page = " << info->_page << "\n" << std::endl;
std::cout << "Choose your operation: ";
std::cin.getline(info->command, 256);
std::cin.clear();
if (info->_page == MAIN_MENU){
if (chareq(info->command, "1") || chareq(info->command, "login")){
info->_page = LOGIN;
login_page(info);
}
else if (chareq(info->command, "2") || chareq(info->command, "sign up") || chareq(info->command, "register")){
info->_page = REGISTER;
register_page(info);
}
else if (chareq(info->command, "3") || chareq(info->command, "exit")){
info->_page = EXIT;
exit_page(info);
}
else
std::cout << "\n[error] |Unexpected command, try again. \n";
} /* Main Menu page */
else if (info->_page == USER_MENU){
if (chareq(info->command, "1") || chareq(info->command, "manage")){
info->_page = 101;
manage_items(info);
}
else if (chareq(info->command, "2") || chareq(info->command, "items"))
info->_page = 102;
else if (chareq(info->command, "3") || chareq(info->command, "search"))
info->_page = 103;
else if (chareq(info->command, "4") || chareq(info->command, "orders"))
info->_page = 104;
else if (chareq(info->command, "5") || chareq(info->command, "logout")){
info->_page = LOGOUT;
logout_page(info);
}
else if (chareq(info->command, "6") || chareq(info->command, "help"))
info->_page = 106;
else if (chareq(info->command, "7") || chareq(info->command, "account"))
info->_page = 107;
else
std::cout << "\n[error] |Unexpected command, try again. \n";
} /* User Menu */
else if (info->_page == ADMIN_MENU){
if (chareq(info->command, "1") || chareq(info->command, "items"))
info->_page = 201;
else if (chareq(info->command, "2") || chareq(info->command, "orders"))
info->_page = 202;
else if (chareq(info->command, "3") || chareq(info->command, "users"))
info->_page = 203;
else if (chareq(info->command, "4") || chareq(info->command, "logout")){
info->_page = LOGOUT;
logout_page(info);
}
else
std::cout << "\n[error] |Unexpected command, try again. \n";
} /* Admin Menu */
else
std::cout << "\n[error] |Unexpected command, try again. \n";
} /* menu_choice */
void login_page(INFO *info){
char name[40], passward[20];
std::cout << "# Sign in #\nUser Name: ";
std::cin.getline(name, 40);
std::cin.clear();
std::cout << "Passward: ";
std::cin.getline(passward, 20);
std::cin.clear();
if (!userSign(info, name, passward)){
std::cout << "\n[info] |Wrong user name or passward! Try again.\n";
std::cout << "****Failed****\n";
info->_page = MAIN_MENU;
}
else
system("cls");
} /* login_page */
void register_page(INFO *info){
char name[40], passward[20];
std::cout << "# Sign Up #\nUser Name: ";
std::cin.getline(name, 40);
std::cin.clear();
std::cout << "Passward: ";
std::cin.getline(passward, 20);
std::cin.clear();
if ((contains(name, " ")) || (contains(passward, " ")) || (contains(name, "\t")) || (contains(passward, "\t"))){
std::cout << "\n[warning] |Name and passward should not have space or tab.\n";
std::cout << "****Failed****\n";
}
else if (!userSign(info, name, passward)){
std::cout << "\n[info] |The user name is already exist. \n";
std::cout << "****Failed****\n";
}
info->_page = MAIN_MENU;
} /* register_page */
void logout_page(INFO *info){
char choice;
std::cout << "\n[confirm] |Logout?(y/n): ";
std::cin >> choice;
std::cin.get();
if (choice == 'y'){
system("cls");
info->_page = MAIN_MENU;
}
} /* logout_page */
void exit_page(INFO *info){
char choice;
std::cout << "\n[confirm] |Exit?(y/n): ";
std::cin >> choice;
std::cin.get();
if (choice == 'y'){
system("cls");
std::exit(1);
}
else
info->_page = MAIN_MENU;
} /* exit_page */
void show_result(INFO *info);
// control all the operations
void _show(INFO *info);
|
/******************************************************************************
*
* Project: PCI .aux Driver
* Purpose: Implementation of PAuxDataset
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1999, Frank Warmerdam
* Copyright (c) 2008-2010, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "cpl_string.h"
#include "gdal_frmts.h"
#include "ogr_spatialref.h"
#include "rawdataset.h"
#include <cmath>
CPL_CVSID("$Id: pauxdataset.cpp f946b03da9b425043fed0a0c58a329295240840f 2017-12-15 13:36:23Z Kurt Schwehr $")
/************************************************************************/
/* ==================================================================== */
/* PAuxDataset */
/* ==================================================================== */
/************************************************************************/
class PAuxRasterBand;
class PAuxDataset : public RawDataset
{
friend class PAuxRasterBand;
VSILFILE *fpImage; // Image data file.
int nGCPCount;
GDAL_GCP *pasGCPList;
char *pszGCPProjection;
void ScanForGCPs();
char *PCI2WKT( const char *pszGeosys, const char *pszProjParms );
char *pszProjection;
public:
PAuxDataset();
~PAuxDataset() override;
// TODO(schwehr): Why are these public?
char *pszAuxFilename;
char **papszAuxLines;
int bAuxUpdated;
const char *GetProjectionRef() override;
CPLErr GetGeoTransform( double * ) override;
CPLErr SetGeoTransform( double * ) override;
int GetGCPCount() override;
const char *GetGCPProjection() override;
const GDAL_GCP *GetGCPs() override;
char **GetFileList() override;
static GDALDataset *Open( GDALOpenInfo * );
static GDALDataset *Create( const char * pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType, char ** papszParmList );
};
/************************************************************************/
/* ==================================================================== */
/* PAuxRasterBand */
/* ==================================================================== */
/************************************************************************/
class PAuxRasterBand : public RawRasterBand
{
public:
PAuxRasterBand( GDALDataset *poDS, int nBand, VSILFILE * fpRaw,
vsi_l_offset nImgOffset, int nPixelOffset,
int nLineOffset,
GDALDataType eDataType, int bNativeOrder );
~PAuxRasterBand() override;
double GetNoDataValue( int *pbSuccess = nullptr ) override;
CPLErr SetNoDataValue( double ) override;
GDALColorTable *GetColorTable() override;
GDALColorInterp GetColorInterpretation() override;
void SetDescription( const char *pszNewDescription ) override;
};
/************************************************************************/
/* PAuxRasterBand() */
/************************************************************************/
PAuxRasterBand::PAuxRasterBand( GDALDataset *poDSIn, int nBandIn,
VSILFILE * fpRawIn, vsi_l_offset nImgOffsetIn,
int nPixelOffsetIn, int nLineOffsetIn,
GDALDataType eDataTypeIn, int bNativeOrderIn ) :
RawRasterBand( poDSIn, nBandIn, fpRawIn,
nImgOffsetIn, nPixelOffsetIn, nLineOffsetIn,
eDataTypeIn, bNativeOrderIn, TRUE )
{
PAuxDataset *poPDS = reinterpret_cast<PAuxDataset *>( poDS );
/* -------------------------------------------------------------------- */
/* Does this channel have a description? */
/* -------------------------------------------------------------------- */
char szTarget[128] = { '\0' };
snprintf( szTarget, sizeof(szTarget), "ChanDesc-%d", nBand );
if( CSLFetchNameValue( poPDS->papszAuxLines, szTarget ) != nullptr )
GDALRasterBand::SetDescription(
CSLFetchNameValue( poPDS->papszAuxLines, szTarget ) );
/* -------------------------------------------------------------------- */
/* See if we have colors. Currently we must have color zero, */
/* but this should not really be a limitation. */
/* -------------------------------------------------------------------- */
snprintf( szTarget, sizeof(szTarget),
"METADATA_IMG_%d_Class_%d_Color", nBand, 0 );
if( CSLFetchNameValue( poPDS->papszAuxLines, szTarget ) != nullptr )
{
poCT = new GDALColorTable();
for( int i = 0; i < 256; i++ )
{
snprintf( szTarget, sizeof(szTarget),
"METADATA_IMG_%d_Class_%d_Color", nBand, i );
const char *pszLine
= CSLFetchNameValue( poPDS->papszAuxLines, szTarget );
while( pszLine && *pszLine == ' ' )
pszLine++;
int nRed = 0;
int nGreen = 0;
int nBlue = 0;
// TODO(schwehr): Replace sscanf with something safe.
if( pszLine != nullptr
&& STARTS_WITH_CI(pszLine, "(RGB:")
&& sscanf( pszLine+5, "%d %d %d",
&nRed, &nGreen, &nBlue ) == 3 )
{
GDALColorEntry oColor = {
static_cast<short>(nRed),
static_cast<short>(nGreen),
static_cast<short>(nBlue),
255
};
poCT->SetColorEntry( i, &oColor );
}
}
}
}
/************************************************************************/
/* ~PAuxRasterBand() */
/************************************************************************/
PAuxRasterBand::~PAuxRasterBand()
{
}
/************************************************************************/
/* GetNoDataValue() */
/************************************************************************/
double PAuxRasterBand::GetNoDataValue( int *pbSuccess )
{
char szTarget[128] = { '\0' };
snprintf( szTarget, sizeof(szTarget),
"METADATA_IMG_%d_NO_DATA_VALUE", nBand );
PAuxDataset *poPDS = reinterpret_cast<PAuxDataset *>( poDS );
const char *pszLine = CSLFetchNameValue( poPDS->papszAuxLines, szTarget );
if( pbSuccess != nullptr )
*pbSuccess = (pszLine != nullptr);
if( pszLine == nullptr )
return -1.0e8;
return CPLAtof(pszLine);
}
/************************************************************************/
/* SetNoDataValue() */
/************************************************************************/
CPLErr PAuxRasterBand::SetNoDataValue( double dfNewValue )
{
if( GetAccess() == GA_ReadOnly )
{
CPLError( CE_Failure, CPLE_NoWriteAccess,
"Can't update readonly dataset." );
return CE_Failure;
}
char szTarget[128] = { '\0' };
char szValue[128] = { '\0' };
snprintf( szTarget, sizeof(szTarget),
"METADATA_IMG_%d_NO_DATA_VALUE", nBand );
CPLsnprintf( szValue, sizeof(szValue),
"%24.12f", dfNewValue );
PAuxDataset *poPDS = reinterpret_cast<PAuxDataset *>( poDS );
poPDS->papszAuxLines =
CSLSetNameValue( poPDS->papszAuxLines, szTarget, szValue );
poPDS->bAuxUpdated = TRUE;
return CE_None;
}
/************************************************************************/
/* SetDescription() */
/* */
/* We override the set description so we can mark the auxfile */
/* info as changed. */
/************************************************************************/
void PAuxRasterBand::SetDescription( const char *pszNewDescription )
{
if( GetAccess() == GA_Update )
{
char szTarget[128] = { '\0' };
snprintf( szTarget, sizeof(szTarget), "ChanDesc-%d", nBand );
PAuxDataset *poPDS = reinterpret_cast<PAuxDataset *>( poDS );
poPDS->papszAuxLines =
CSLSetNameValue( poPDS->papszAuxLines,
szTarget, pszNewDescription );
poPDS->bAuxUpdated = TRUE;
}
GDALRasterBand::SetDescription( pszNewDescription );
}
/************************************************************************/
/* GetColorTable() */
/************************************************************************/
GDALColorTable *PAuxRasterBand::GetColorTable()
{
return poCT;
}
/************************************************************************/
/* GetColorInterpretation() */
/************************************************************************/
GDALColorInterp PAuxRasterBand::GetColorInterpretation()
{
if( poCT == nullptr )
return GCI_Undefined;
return GCI_PaletteIndex;
}
/************************************************************************/
/* ==================================================================== */
/* PAuxDataset */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* PAuxDataset() */
/************************************************************************/
PAuxDataset::PAuxDataset() :
fpImage(nullptr),
nGCPCount(0),
pasGCPList(nullptr),
pszGCPProjection(nullptr),
pszProjection(nullptr),
pszAuxFilename(nullptr),
papszAuxLines(nullptr),
bAuxUpdated(FALSE)
{}
/************************************************************************/
/* ~PAuxDataset() */
/************************************************************************/
PAuxDataset::~PAuxDataset()
{
FlushCache();
if( fpImage != nullptr && VSIFCloseL( fpImage ) != 0 )
{
CPLError( CE_Failure, CPLE_FileIO, "I/O error" );
}
if( bAuxUpdated )
{
CSLSetNameValueSeparator( papszAuxLines, ": " );
CSLSave( papszAuxLines, pszAuxFilename );
}
CPLFree( pszProjection );
CPLFree( pszGCPProjection );
GDALDeinitGCPs( nGCPCount, pasGCPList );
CPLFree( pasGCPList );
CPLFree( pszAuxFilename );
CSLDestroy( papszAuxLines );
}
/************************************************************************/
/* GetFileList() */
/************************************************************************/
char **PAuxDataset::GetFileList()
{
char **papszFileList = RawDataset::GetFileList();
papszFileList = CSLAddString( papszFileList, pszAuxFilename );
return papszFileList;
}
/************************************************************************/
/* PCI2WKT() */
/* */
/* Convert PCI coordinate system to WKT. For now this is very */
/* incomplete, but can be filled out in the future. */
/************************************************************************/
char *PAuxDataset::PCI2WKT( const char *pszGeosys,
const char *pszProjParms )
{
while( *pszGeosys == ' ' )
pszGeosys++;
/* -------------------------------------------------------------------- */
/* Parse projection parameters array. */
/* -------------------------------------------------------------------- */
double adfProjParms[16] = { 0.0 };
if( pszProjParms != nullptr )
{
char **papszTokens = CSLTokenizeString( pszProjParms );
for( int i = 0;
i < 16 && papszTokens != nullptr && papszTokens[i] != nullptr;
i++ )
adfProjParms[i] = CPLAtof(papszTokens[i]);
CSLDestroy( papszTokens );
}
/* -------------------------------------------------------------------- */
/* Convert to SRS. */
/* -------------------------------------------------------------------- */
OGRSpatialReference oSRS;
if( oSRS.importFromPCI( pszGeosys, nullptr, adfProjParms ) == OGRERR_NONE )
{
char *pszResult = nullptr;
oSRS.exportToWkt( &pszResult );
return pszResult;
}
return nullptr;
}
/************************************************************************/
/* ScanForGCPs() */
/************************************************************************/
void PAuxDataset::ScanForGCPs()
{
const int MAX_GCP = 256;
nGCPCount = 0;
CPLAssert( pasGCPList == nullptr );
pasGCPList = reinterpret_cast<GDAL_GCP *>(
CPLCalloc( sizeof(GDAL_GCP), MAX_GCP ) );
/* -------------------------------------------------------------------- */
/* Get the GCP coordinate system. */
/* -------------------------------------------------------------------- */
const char *pszMapUnits =
CSLFetchNameValue( papszAuxLines, "GCP_1_MapUnits" );
const char *pszProjParms =
CSLFetchNameValue( papszAuxLines, "GCP_1_ProjParms" );
if( pszMapUnits != nullptr )
pszGCPProjection = PCI2WKT( pszMapUnits, pszProjParms );
/* -------------------------------------------------------------------- */
/* Collect standalone GCPs. They look like: */
/* */
/* GCP_1_n = row, col, x, y [,z [,"id"[, "desc"]]] */
/* -------------------------------------------------------------------- */
for( int i = 0; nGCPCount < MAX_GCP; i++ )
{
char szName[50] = { '\0' };
snprintf( szName, sizeof(szName), "GCP_1_%d", i+1 );
if( CSLFetchNameValue( papszAuxLines, szName ) == nullptr )
break;
char **papszTokens = CSLTokenizeStringComplex(
CSLFetchNameValue( papszAuxLines, szName ),
" ", TRUE, FALSE );
if( CSLCount(papszTokens) >= 4 )
{
GDALInitGCPs( 1, pasGCPList + nGCPCount );
pasGCPList[nGCPCount].dfGCPX = CPLAtof(papszTokens[2]);
pasGCPList[nGCPCount].dfGCPY = CPLAtof(papszTokens[3]);
pasGCPList[nGCPCount].dfGCPPixel = CPLAtof(papszTokens[0]);
pasGCPList[nGCPCount].dfGCPLine = CPLAtof(papszTokens[1]);
if( CSLCount(papszTokens) > 4 )
pasGCPList[nGCPCount].dfGCPZ = CPLAtof(papszTokens[4]);
CPLFree( pasGCPList[nGCPCount].pszId );
if( CSLCount(papszTokens) > 5 )
{
pasGCPList[nGCPCount].pszId = CPLStrdup(papszTokens[5]);
}
else
{
snprintf( szName, sizeof(szName), "GCP_%d", i+1 );
pasGCPList[nGCPCount].pszId = CPLStrdup( szName );
}
if( CSLCount(papszTokens) > 6 )
{
CPLFree( pasGCPList[nGCPCount].pszInfo );
pasGCPList[nGCPCount].pszInfo = CPLStrdup(papszTokens[6]);
}
nGCPCount++;
}
CSLDestroy(papszTokens);
}
}
/************************************************************************/
/* GetGCPCount() */
/************************************************************************/
int PAuxDataset::GetGCPCount()
{
return nGCPCount;
}
/************************************************************************/
/* GetGCPProjection() */
/************************************************************************/
const char *PAuxDataset::GetGCPProjection()
{
if( nGCPCount > 0 && pszGCPProjection != nullptr )
return pszGCPProjection;
return "";
}
/************************************************************************/
/* GetGCP() */
/************************************************************************/
const GDAL_GCP *PAuxDataset::GetGCPs()
{
return pasGCPList;
}
/************************************************************************/
/* GetProjectionRef() */
/************************************************************************/
const char *PAuxDataset::GetProjectionRef()
{
if( pszProjection )
return pszProjection;
return GDALPamDataset::GetProjectionRef();
}
/************************************************************************/
/* GetGeoTransform() */
/************************************************************************/
CPLErr PAuxDataset::GetGeoTransform( double * padfGeoTransform )
{
if( CSLFetchNameValue(papszAuxLines, "UpLeftX") == nullptr
|| CSLFetchNameValue(papszAuxLines, "UpLeftY") == nullptr
|| CSLFetchNameValue(papszAuxLines, "LoRightX") == nullptr
|| CSLFetchNameValue(papszAuxLines, "LoRightY") == nullptr )
{
padfGeoTransform[0] = 0.0;
padfGeoTransform[1] = 1.0;
padfGeoTransform[2] = 0.0;
padfGeoTransform[3] = 0.0;
padfGeoTransform[4] = 0.0;
padfGeoTransform[5] = 1.0;
return CE_Failure;
}
const double dfUpLeftX =
CPLAtof(CSLFetchNameValue(papszAuxLines, "UpLeftX" ));
const double dfUpLeftY =
CPLAtof(CSLFetchNameValue(papszAuxLines, "UpLeftY" ));
const double dfLoRightX =
CPLAtof(CSLFetchNameValue(papszAuxLines, "LoRightX" ));
const double dfLoRightY =
CPLAtof(CSLFetchNameValue(papszAuxLines, "LoRightY" ));
padfGeoTransform[0] = dfUpLeftX;
padfGeoTransform[1] = (dfLoRightX - dfUpLeftX) / GetRasterXSize();
padfGeoTransform[2] = 0.0;
padfGeoTransform[3] = dfUpLeftY;
padfGeoTransform[4] = 0.0;
padfGeoTransform[5] = (dfLoRightY - dfUpLeftY) / GetRasterYSize();
return CE_None;
}
/************************************************************************/
/* SetGeoTransform() */
/************************************************************************/
CPLErr PAuxDataset::SetGeoTransform( double * padfGeoTransform )
{
char szUpLeftX[128] = { '\0' };
char szUpLeftY[128] = { '\0' };
char szLoRightX[128] = { '\0' };
char szLoRightY[128] = { '\0' };
if( std::abs(padfGeoTransform[0]) < 181
&& std::abs(padfGeoTransform[1]) < 1 )
{
CPLsnprintf( szUpLeftX, sizeof(szUpLeftX), "%.12f",
padfGeoTransform[0] );
CPLsnprintf( szUpLeftY, sizeof(szUpLeftY), "%.12f",
padfGeoTransform[3] );
CPLsnprintf( szLoRightX, sizeof(szLoRightX), "%.12f",
padfGeoTransform[0] +
padfGeoTransform[1] * GetRasterXSize() );
CPLsnprintf( szLoRightY, sizeof(szLoRightY), "%.12f",
padfGeoTransform[3] +
padfGeoTransform[5] * GetRasterYSize() );
}
else
{
CPLsnprintf( szUpLeftX, sizeof(szUpLeftX), "%.3f",
padfGeoTransform[0] );
CPLsnprintf( szUpLeftY, sizeof(szUpLeftY), "%.3f",
padfGeoTransform[3] );
CPLsnprintf( szLoRightX, sizeof(szLoRightX), "%.3f",
padfGeoTransform[0] +
padfGeoTransform[1] * GetRasterXSize() );
CPLsnprintf( szLoRightY, sizeof(szLoRightY), "%.3f",
padfGeoTransform[3] +
padfGeoTransform[5] * GetRasterYSize() );
}
papszAuxLines = CSLSetNameValue( papszAuxLines, "UpLeftX", szUpLeftX );
papszAuxLines = CSLSetNameValue( papszAuxLines, "UpLeftY", szUpLeftY );
papszAuxLines = CSLSetNameValue( papszAuxLines, "LoRightX", szLoRightX );
papszAuxLines = CSLSetNameValue( papszAuxLines, "LoRightY", szLoRightY );
bAuxUpdated = TRUE;
return CE_None;
}
/************************************************************************/
/* Open() */
/************************************************************************/
GDALDataset *PAuxDataset::Open( GDALOpenInfo * poOpenInfo )
{
if( poOpenInfo->nHeaderBytes < 1 )
return nullptr;
/* -------------------------------------------------------------------- */
/* If this is an .aux file, fetch out and form the name of the */
/* file it references. */
/* -------------------------------------------------------------------- */
CPLString osTarget = poOpenInfo->pszFilename;
if( EQUAL(CPLGetExtension( poOpenInfo->pszFilename ),"aux")
&& STARTS_WITH_CI(reinterpret_cast<char *>( poOpenInfo->pabyHeader ),
"AuxilaryTarget: ") )
{
const char *pszSrc = reinterpret_cast<const char *>(
poOpenInfo->pabyHeader+16 );
char szAuxTarget[1024] = { '\0' };
for( int i = 0;
i < static_cast<int>( sizeof(szAuxTarget) ) - 1 &&
pszSrc[i] != 10 && pszSrc[i] != 13 && pszSrc[i] != '\0';
i++ )
{
szAuxTarget[i] = pszSrc[i];
}
szAuxTarget[sizeof(szAuxTarget) - 1] = '\0';
const std::string osPath(CPLGetPath(poOpenInfo->pszFilename));
osTarget = CPLFormFilename(osPath.c_str(), szAuxTarget, nullptr);
}
/* -------------------------------------------------------------------- */
/* Now we need to tear apart the filename to form a .aux */
/* filename. */
/* -------------------------------------------------------------------- */
CPLString osAuxFilename = CPLResetExtension(osTarget,"aux");
/* -------------------------------------------------------------------- */
/* Do we have a .aux file? */
/* -------------------------------------------------------------------- */
char** papszSiblingFiles = poOpenInfo->GetSiblingFiles();
if( papszSiblingFiles != nullptr
&& CSLFindString( papszSiblingFiles,
CPLGetFilename(osAuxFilename) ) == -1 )
{
return nullptr;
}
VSILFILE *fp = VSIFOpenL( osAuxFilename, "r" );
if( fp == nullptr )
{
osAuxFilename = CPLResetExtension(osTarget,"AUX");
fp = VSIFOpenL( osAuxFilename, "r" );
}
if( fp == nullptr )
return nullptr;
/* -------------------------------------------------------------------- */
/* Is this file a PCI .aux file? Check the first line for the */
/* telltale AuxilaryTarget keyword. */
/* */
/* At this point we should be verifying that it refers to our */
/* binary file, but that is a pretty involved test. */
/* -------------------------------------------------------------------- */
const char *pszLine = CPLReadLineL( fp );
CPL_IGNORE_RET_VAL(VSIFCloseL( fp ));
if( pszLine == nullptr
|| (!STARTS_WITH_CI(pszLine, "AuxilaryTarget")
&& !STARTS_WITH_CI(pszLine, "AuxiliaryTarget")) )
{
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Create a corresponding GDALDataset. */
/* -------------------------------------------------------------------- */
PAuxDataset *poDS = new PAuxDataset();
/* -------------------------------------------------------------------- */
/* Load the .aux file into a string list suitable to be */
/* searched with CSLFetchNameValue(). */
/* -------------------------------------------------------------------- */
poDS->papszAuxLines = CSLLoad( osAuxFilename );
poDS->pszAuxFilename = CPLStrdup(osAuxFilename);
/* -------------------------------------------------------------------- */
/* Find the RawDefinition line to establish overall parameters. */
/* -------------------------------------------------------------------- */
pszLine = CSLFetchNameValue(poDS->papszAuxLines, "RawDefinition");
// It seems PCI now writes out .aux files without RawDefinition in
// some cases. See bug 947.
if( pszLine == nullptr )
{
delete poDS;
return nullptr;
}
char **papszTokens = CSLTokenizeString(pszLine);
if( CSLCount(papszTokens) < 3 )
{
CPLError( CE_Failure, CPLE_AppDefined,
"RawDefinition missing or corrupt in %s.",
poOpenInfo->pszFilename );
delete poDS;
CSLDestroy( papszTokens );
return nullptr;
}
poDS->nRasterXSize = atoi(papszTokens[0]);
poDS->nRasterYSize = atoi(papszTokens[1]);
poDS->nBands = atoi(papszTokens[2]);
poDS->eAccess = poOpenInfo->eAccess;
CSLDestroy( papszTokens );
if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize) ||
!GDALCheckBandCount(poDS->nBands, FALSE))
{
delete poDS;
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Open the file. */
/* -------------------------------------------------------------------- */
if( poOpenInfo->eAccess == GA_Update )
{
poDS->fpImage = VSIFOpenL( osTarget, "rb+" );
if( poDS->fpImage == nullptr )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"File %s is missing or read-only, check permissions.",
osTarget.c_str() );
delete poDS;
return nullptr;
}
}
else
{
poDS->fpImage = VSIFOpenL( osTarget, "rb" );
if( poDS->fpImage == nullptr )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"File %s is missing or unreadable.",
osTarget.c_str() );
delete poDS;
return nullptr;
}
}
/* -------------------------------------------------------------------- */
/* Collect raw definitions of each channel and create */
/* corresponding bands. */
/* -------------------------------------------------------------------- */
int iBand = 0;
for( int i = 0; i < poDS->nBands; i++ )
{
char szDefnName[32] = { '\0' };
snprintf( szDefnName, sizeof(szDefnName), "ChanDefinition-%d", i+1 );
pszLine = CSLFetchNameValue(poDS->papszAuxLines, szDefnName);
if (pszLine == nullptr)
{
continue;
}
papszTokens = CSLTokenizeString(pszLine);
if( CSLCount(papszTokens) < 4 )
{
// Skip the band with broken description
CSLDestroy( papszTokens );
continue;
}
GDALDataType eType = GDT_Unknown;
if( EQUAL(papszTokens[0],"16U") )
eType = GDT_UInt16;
else if( EQUAL(papszTokens[0],"16S") )
eType = GDT_Int16;
else if( EQUAL(papszTokens[0],"32R") )
eType = GDT_Float32;
else
eType = GDT_Byte;
bool bNative = true;
if( CSLCount(papszTokens) > 4 )
{
#ifdef CPL_LSB
bNative = EQUAL(papszTokens[4], "Swapped");
#else
bNative = EQUAL(papszTokens[4], "Unswapped");
#endif
}
const vsi_l_offset nBandOffset =
CPLScanUIntBig( papszTokens[1],
static_cast<int>(strlen(papszTokens[1])) );
const int nPixelOffset = atoi(papszTokens[2]);
const int nLineOffset = atoi(papszTokens[3]);
if (nPixelOffset <= 0 || nLineOffset <= 0)
{
// Skip the band with broken offsets.
CSLDestroy( papszTokens );
continue;
}
poDS->SetBand( iBand+1,
new PAuxRasterBand( poDS, iBand+1, poDS->fpImage,
nBandOffset,
nPixelOffset,
nLineOffset, eType, bNative ) );
iBand++;
CSLDestroy( papszTokens );
}
poDS->nBands = iBand;
/* -------------------------------------------------------------------- */
/* Get the projection. */
/* -------------------------------------------------------------------- */
const char *pszMapUnits =
CSLFetchNameValue( poDS->papszAuxLines, "MapUnits" );
const char *pszProjParms =
CSLFetchNameValue( poDS->papszAuxLines, "ProjParms" );
if( pszMapUnits != nullptr )
poDS->pszProjection = poDS->PCI2WKT( pszMapUnits, pszProjParms );
/* -------------------------------------------------------------------- */
/* Initialize any PAM information. */
/* -------------------------------------------------------------------- */
poDS->SetDescription( osTarget );
poDS->TryLoadXML();
/* -------------------------------------------------------------------- */
/* Check for overviews. */
/* -------------------------------------------------------------------- */
poDS->oOvManager.Initialize( poDS, osTarget );
poDS->ScanForGCPs();
poDS->bAuxUpdated = FALSE;
return poDS;
}
/************************************************************************/
/* Create() */
/************************************************************************/
GDALDataset *PAuxDataset::Create( const char * pszFilename,
int nXSize, int nYSize, int nBands,
GDALDataType eType,
char **papszOptions )
{
const char *pszInterleave = CSLFetchNameValue( papszOptions, "INTERLEAVE" );
if( pszInterleave == nullptr )
pszInterleave = "BAND";
/* -------------------------------------------------------------------- */
/* Verify input options. */
/* -------------------------------------------------------------------- */
if( eType != GDT_Byte && eType != GDT_Float32 && eType != GDT_UInt16
&& eType != GDT_Int16 )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Attempt to create PCI .Aux labelled dataset with an illegal\n"
"data type (%s).\n",
GDALGetDataTypeName(eType) );
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Sum the sizes of the band pixel types. */
/* -------------------------------------------------------------------- */
int nPixelSizeSum = 0;
for( int iBand = 0; iBand < nBands; iBand++ )
nPixelSizeSum += GDALGetDataTypeSizeBytes(eType);
/* -------------------------------------------------------------------- */
/* Try to create the file. */
/* -------------------------------------------------------------------- */
VSILFILE *fp = VSIFOpenL( pszFilename, "w" );
if( fp == nullptr )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"Attempt to create file `%s' failed.\n",
pszFilename );
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Just write out a couple of bytes to establish the binary */
/* file, and then close it. */
/* -------------------------------------------------------------------- */
CPL_IGNORE_RET_VAL(VSIFWriteL( "\0\0", 2, 1, fp ));
CPL_IGNORE_RET_VAL(VSIFCloseL( fp ));
/* -------------------------------------------------------------------- */
/* Create the aux filename. */
/* -------------------------------------------------------------------- */
char *pszAuxFilename = static_cast<char *>(
CPLMalloc( strlen( pszFilename ) + 5 ) );
strcpy( pszAuxFilename, pszFilename );
for( int i = static_cast<int>(strlen(pszAuxFilename))-1; i > 0; i-- )
{
if( pszAuxFilename[i] == '.' )
{
pszAuxFilename[i] = '\0';
break;
}
}
strcat( pszAuxFilename, ".aux" );
/* -------------------------------------------------------------------- */
/* Open the file. */
/* -------------------------------------------------------------------- */
fp = VSIFOpenL( pszAuxFilename, "wt" );
if( fp == nullptr )
{
CPLError( CE_Failure, CPLE_OpenFailed,
"Attempt to create file `%s' failed.\n",
pszAuxFilename );
return nullptr;
}
CPLFree( pszAuxFilename );
/* -------------------------------------------------------------------- */
/* We need to write out the original filename but without any */
/* path components in the AuxilaryTarget line. Do so now. */
/* -------------------------------------------------------------------- */
int iStart = static_cast<int>(strlen(pszFilename))-1;
while( iStart > 0 && pszFilename[iStart-1] != '/'
&& pszFilename[iStart-1] != '\\' )
iStart--;
CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "AuxilaryTarget: %s\n", pszFilename + iStart ));
/* -------------------------------------------------------------------- */
/* Write out the raw definition for the dataset as a whole. */
/* -------------------------------------------------------------------- */
CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "RawDefinition: %d %d %d\n",
nXSize, nYSize, nBands ));
/* -------------------------------------------------------------------- */
/* Write out a definition for each band. We always write band */
/* sequential files for now as these are pretty efficiently */
/* handled by GDAL. */
/* -------------------------------------------------------------------- */
vsi_l_offset nImgOffset = 0;
for( int iBand = 0; iBand < nBands; iBand++ )
{
int nPixelOffset = 0;
int nLineOffset = 0;
vsi_l_offset nNextImgOffset = 0;
/* -------------------------------------------------------------------- */
/* Establish our file layout based on supplied interleaving. */
/* -------------------------------------------------------------------- */
if( EQUAL(pszInterleave,"LINE") )
{
nPixelOffset = GDALGetDataTypeSizeBytes(eType);
nLineOffset = nXSize * nPixelSizeSum;
nNextImgOffset = nImgOffset + nPixelOffset * nXSize;
}
else if( EQUAL(pszInterleave,"PIXEL") )
{
nPixelOffset = nPixelSizeSum;
nLineOffset = nXSize * nPixelOffset;
nNextImgOffset = nImgOffset + GDALGetDataTypeSizeBytes(eType);
}
else /* default to band */
{
nPixelOffset = GDALGetDataTypeSize(eType)/8;
nLineOffset = nXSize * nPixelOffset;
nNextImgOffset =
nImgOffset + nYSize * static_cast<vsi_l_offset>( nLineOffset );
}
/* -------------------------------------------------------------------- */
/* Write out line indicating layout. */
/* -------------------------------------------------------------------- */
const char *pszTypeName = nullptr;
if( eType == GDT_Float32 )
pszTypeName = "32R";
else if( eType == GDT_Int16 )
pszTypeName = "16S";
else if( eType == GDT_UInt16 )
pszTypeName = "16U";
else
pszTypeName = "8U";
CPL_IGNORE_RET_VAL(
VSIFPrintfL( fp, "ChanDefinition-%d: %s " CPL_FRMT_GIB " %d %d %s\n",
iBand+1,
pszTypeName, static_cast<GIntBig>( nImgOffset ),
nPixelOffset, nLineOffset,
#ifdef CPL_LSB
"Swapped"
#else
"Unswapped"
#endif
) );
nImgOffset = nNextImgOffset;
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
CPL_IGNORE_RET_VAL(VSIFCloseL( fp ));
return static_cast<GDALDataset *>(
GDALOpen( pszFilename, GA_Update ) );
}
/************************************************************************/
/* PAuxDelete() */
/************************************************************************/
static CPLErr PAuxDelete( const char * pszBasename )
{
VSILFILE *fp = VSIFOpenL( CPLResetExtension( pszBasename, "aux" ), "r" );
if( fp == nullptr )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s does not appear to be a PAux dataset: "
"there is no .aux file.",
pszBasename );
return CE_Failure;
}
const char *pszLine = CPLReadLineL( fp );
CPL_IGNORE_RET_VAL(VSIFCloseL( fp ));
if( pszLine == nullptr || !STARTS_WITH_CI(pszLine, "AuxilaryTarget") )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s does not appear to be a PAux dataset:"
"the .aux file does not start with AuxilaryTarget",
pszBasename );
return CE_Failure;
}
if( VSIUnlink( pszBasename ) != 0 )
{
CPLError( CE_Failure, CPLE_AppDefined,
"OS unlinking file %s.", pszBasename );
return CE_Failure;
}
VSIUnlink( CPLResetExtension( pszBasename, "aux" ) );
return CE_None;
}
/************************************************************************/
/* GDALRegister_PAux() */
/************************************************************************/
void GDALRegister_PAux()
{
if( GDALGetDriverByName( "PAux" ) != nullptr )
return;
GDALDriver *poDriver = new GDALDriver();
poDriver->SetDescription( "PAux" );
poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" );
poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "PCI .aux Labelled" );
poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_various.html#PAux" );
poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES,
"Byte Int16 UInt16 Float32" );
poDriver->SetMetadataItem(
GDAL_DMD_CREATIONOPTIONLIST,
"<CreationOptionList>"
" <Option name='INTERLEAVE' type='string-select' default='BAND'>"
" <Value>BAND</Value>"
" <Value>LINE</Value>"
" <Value>PIXEL</Value>"
" </Option>"
"</CreationOptionList>" );
poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );
poDriver->pfnOpen = PAuxDataset::Open;
poDriver->pfnCreate = PAuxDataset::Create;
poDriver->pfnDelete = PAuxDelete;
GetGDALDriverManager()->RegisterDriver( poDriver );
}
|
/**********************************************************************
* Copyright (c) 2008-2015, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef ANALYSIS_UNCERTAINTYDESCRIPTION_HPP
#define ANALYSIS_UNCERTAINTYDESCRIPTION_HPP
#include "AnalysisAPI.hpp"
#include "AnalysisEnums.hpp"
#include "../utilities/core/Logger.hpp"
#include "../utilities/data/Attribute.hpp"
#include <boost/optional.hpp>
namespace openstudio {
namespace analysis {
namespace detail {
class UncertaintyDescription_Impl;
}
/** UncertaintyDescription is an abstract base class that can be used to append uncertainty information
* to a Variable. At this time, such descriptions are only used if the variables are sampled using
* SamplingAlgorithm (which is available through DAKOTA). */
class ANALYSIS_API UncertaintyDescription {
public:
/** @name Constructors and Destructors */
//@{
virtual ~UncertaintyDescription() {}
UncertaintyDescription clone() const;
//@}
/** Returns all the \link UncertaintyDescriptionType UncertaintyDescriptionTypes\endlink that are
* applicable to variableValueType (VariableValueType::Continuous or VariableValueType::Discrete). */
static std::vector<UncertaintyDescriptionType> validTypes(const VariableValueType& variableValueType);
/** Returns all the \link UncertaintyDescriptionType UncertaintyDescriptionTypes\endlink that are
* applicable to the specified combination of variableValueType (VariableValueType::Continuous or
* VariableValueType::Discrete) and uncertaintyType (UncertaintyType::Aleatory or
* UncertaintyType::Epistemic). */
static std::vector<UncertaintyDescriptionType> validTypes(const VariableValueType& variableValueType,
const UncertaintyType& uncertaintyType);
/** @name Getters and Queries */
//@{
UncertaintyDescriptionType type() const;
//@}
/** @name Setters */
//@{
/** Restores the default options for this UncertaintyDescription and its type(). */
void restoreDefaults();
//@}
/** @name Type Casting */
//@{
// ETH@20120921 TODO: cast() should allow casts to the base class, but I don't think it does right now.
/** Casts the UncertaintyDescription to type T, if possible. All descriptions can be cast to
* GenericUncertaintyDescription, which provides a unified interface for all types. Otherwise, the
* cast will only succeed if type() == T::type(). */
template<typename T>
T cast() const {
bool isCorrectType(type() == T::type());
if (!isCorrectType && (T::type() != UncertaintyDescriptionType(UncertaintyDescriptionType::Generic))) {
throw(std::bad_cast());
}
return T(impl());
}
template<typename T>
boost::optional<T> optionalCast() const {
boost::optional<T> result;
bool isCorrectType(type() == T::type());
if (!isCorrectType && (T::type() != UncertaintyDescriptionType(UncertaintyDescriptionType::Generic))) {
return result;
}
return T(impl());
}
//@}
protected:
explicit UncertaintyDescription(std::shared_ptr<detail::UncertaintyDescription_Impl> impl);
typedef detail::UncertaintyDescription_Impl ImplType;
friend class detail::UncertaintyDescription_Impl;
friend class AnalysisObject;
std::shared_ptr<detail::UncertaintyDescription_Impl> impl() const;
private:
std::shared_ptr<detail::UncertaintyDescription_Impl> m_impl;
// private, unimplemented default constructor
UncertaintyDescription();
REGISTER_LOGGER("openstudio.analysis.UncertaintyDescription");
};
/** \relates UncertaintyDescription */
typedef boost::optional<UncertaintyDescription> OptionalUncertaintyDescription;
namespace detail {
QVariant toVariant(const UncertaintyDescription& udesc);
UncertaintyDescription toUncertaintyDescription(const QVariant& variant,
const VersionString& version);
}
} // analysis
} // openstudio
#endif // ANALYSIS_UNCERTAINTYDESCRIPTION_HPP
|
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "lib/zip/unique_unzipper.h"
#include "third_party/zlib/contrib/minizip/unzip.h"
namespace zip {
void UniqueUnzipperTraits::Free(void* file) {
unzClose(file);
}
} // namespace zip
|
/*
* Copyright (C) 2015 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef IGNITION_RENDERING_MESHDESCRIPTOR_HH_
#define IGNITION_RENDERING_MESHDESCRIPTOR_HH_
#include <string>
#include <ignition/common/SuppressWarning.hh>
#include "ignition/rendering/config.hh"
#include "ignition/rendering/Export.hh"
namespace ignition
{
namespace common
{
class Mesh;
}
}
namespace ignition
{
namespace rendering
{
inline namespace IGNITION_RENDERING_VERSION_NAMESPACE {
//
/// \struct MeshDescriptor MeshDescriptor.hh
/// ignition/rendering/MeshDescriptor.hh
/// \brief Describes how a Mesh should be loaded
struct IGNITION_RENDERING_VISIBLE MeshDescriptor
{
/// \brief Constructor
public: MeshDescriptor();
/// \brief Constructor. A common::Mesh will be retrieved from the
/// MeshManager by the given name upon a call to Normalize.
/// \param[in] _meshName Name of the mesh to load
public: explicit MeshDescriptor(const std::string &_meshName);
/// \brief Constructor
/// \param[in] _mesh Mesh to load
public: explicit MeshDescriptor(const common::Mesh *_mesh);
/// \brief Ensures both the meshName and mesh member variables have been
/// assigned. If mesh is not null, it will be used to override the value
/// of meshName.
public: void Load();
IGN_COMMON_WARN_IGNORE__DLL_INTERFACE_MISSING
/// \brief common::Mesh object
public: const common::Mesh *mesh = nullptr;
IGN_COMMON_WARN_RESUME__DLL_INTERFACE_MISSING
/// \brief Name of the registered Mesh
public: std::string meshName;
/// \brief Name of the sub-mesh to be loaded. An empty string signifies
/// all sub-meshes should be loaded.
public: std::string subMeshName;
/// \brief Denotes if the loaded sub-mesh vertices should be centered
public: bool centerSubMesh = false;
};
}
}
}
#endif
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include "../ForwardTranslator.hpp"
#include "../../model/Model.hpp"
#include "../../model/ModelObject.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToActuator.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImportToActuator_Impl.hpp"
#include "../../model/ExternalInterfaceFunctionalMockupUnitImport.hpp"
#include <utilities/idd/ExternalInterface_FunctionalMockupUnitImport_To_Actuator_FieldEnums.hxx>
#include "../../utilities/idd/IddEnums.hpp"
#include <utilities/idd/IddEnums.hxx>
using namespace openstudio::model;
using namespace std;
namespace openstudio {
namespace energyplus {
boost::optional<IdfObject> ForwardTranslator::translateExternalInterfaceFunctionalMockupUnitImportToActuator(
ExternalInterfaceFunctionalMockupUnitImportToActuator& modelObject) {
boost::optional<std::string> s;
boost::optional<double> d;
IdfObject idfObject(openstudio::IddObjectType::ExternalInterface_FunctionalMockupUnitImport_To_Actuator);
m_idfObjects.push_back(idfObject);
//Name
s = modelObject.name();
if (s) {
idfObject.setName(*s);
}
const boost::optional<ModelObject> m = modelObject.actuatedComponentUnique();
if (m.is_initialized()) {
idfObject.setString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentUniqueName, m.get().nameString());
}
s = modelObject.actuatedComponentType();
if (s.is_initialized()) {
idfObject.setString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentType, s.get());
}
s = modelObject.actuatedComponentControlType();
if (s.is_initialized()) {
idfObject.setString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::ActuatedComponentControlType, s.get());
}
boost::optional<ExternalInterfaceFunctionalMockupUnitImport> file = modelObject.fMUFile();
if (file.is_initialized()) {
idfObject.setString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::FMUFileName, file.get().fMUFileName());
}
s = modelObject.fMUInstanceName();
if (s.is_initialized()) {
idfObject.setString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::FMUInstanceName, s.get());
}
s = modelObject.fMUVariableName();
if (s.is_initialized()) {
idfObject.setString(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::FMUVariableName, s.get());
}
d = modelObject.initialValue();
if (d.is_initialized()) {
idfObject.setDouble(ExternalInterface_FunctionalMockupUnitImport_To_ActuatorFields::InitialValue, d.get());
}
return idfObject;
}
} // namespace energyplus
} // namespace openstudio
|
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
#include "thread_pool.h"
#include "common.h"
#include "utils/arguments.h"
#include "p4_api.h"
#include "minitrace.h"
ThreadPool* ThreadPool::GetSingleton()
{
static ThreadPool singleton;
return &singleton;
}
void ThreadPool::AddJob(Job function)
{
{
std::unique_lock<std::mutex> lock(m_JobsMutex);
m_Jobs.push_back(function);
m_JobsProcessing++;
}
m_CV.notify_one();
}
void ThreadPool::Wait()
{
while (true)
{
if (m_JobsProcessing == 0)
{
return;
}
}
}
void ThreadPool::RaiseCaughtExceptions()
{
for (auto& exceptionPtr : m_ThreadExceptions)
{
if (exceptionPtr)
{
std::rethrow_exception(exceptionPtr);
}
}
}
void ThreadPool::ShutDown()
{
if (m_HasShutDownBeenCalled)
{
return;
}
m_HasShutDownBeenCalled = true;
{
std::unique_lock<std::mutex> lock(m_JobsMutex);
m_ShouldStop = true;
}
m_CV.notify_all();
for (auto& thread : m_Threads)
{
thread.join();
}
m_Threads.clear();
m_ThreadExceptions.clear();
m_ThreadNames.clear();
SUCCESS("Thread pool shut down successfully");
}
void ThreadPool::Resize(int size)
{
ShutDown();
Initialize(size);
}
void ThreadPool::Initialize(int size)
{
m_HasShutDownBeenCalled = false;
m_ShouldStop = false;
m_JobsProcessing = 0;
m_P4Contexts.resize(size);
for (int i = 0; i < size; i++)
{
m_ThreadExceptions.push_back(nullptr);
m_ThreadNames.push_back("Worker #" + std::to_string(i));
m_Threads.push_back(std::thread([this, i]()
{
MTR_META_THREAD_NAME(m_ThreadNames.at(i).c_str());
P4API* localP4 = &m_P4Contexts[i];
while (true)
{
Job job;
{
std::unique_lock<std::mutex> lock(m_JobsMutex);
m_CV.wait(lock, [this]()
{ return !m_Jobs.empty() || m_ShouldStop; });
if (m_ShouldStop)
{
break;
}
job = m_Jobs.front();
m_Jobs.pop_front();
}
try
{
job(localP4);
}
catch (const std::exception& e)
{
m_ThreadExceptions[i] = std::current_exception();
}
m_JobsProcessing--;
}
}));
}
SUCCESS("Created " << size << " threads in thread pool");
}
ThreadPool::~ThreadPool()
{
ShutDown();
}
|
////////////////////////////////////////////////////////////////////////////
// Module : property_integer.hpp
// Created : 07.12.2007
// Modified : 07.12.2007
// Author : Dmitriy Iassenev
// Description : integer property implementation class
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "property_holder_include.hpp"
public ref class property_integer : public IProperty {
public:
typedef editor::property_holder::integer_getter_type integer_getter_type;
typedef editor::property_holder::integer_setter_type integer_setter_type;
public:
property_integer (
integer_getter_type const &getter,
integer_setter_type const &setter
);
virtual ~property_integer ();
!property_integer ();
virtual System::Object ^GetValue ();
virtual void SetValue (System::Object ^object);
private:
integer_getter_type *m_getter;
integer_setter_type *m_setter;
}; // ref class property_integer
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/invalidation/impl/invalidation_prefs.h"
namespace invalidation {
namespace prefs {
// An ID to uniquely identify this client to the invalidator service.
const char kInvalidatorClientId[] = "invalidator.client_id";
// Opaque state from the invalidation subsystem that is persisted via prefs.
// The value is base 64 encoded.
const char kInvalidatorInvalidationState[] = "invalidator.invalidation_state";
// List of received invalidations that have not been acted on by any clients
// yet. Used to keep invalidation clients in sync in case of a restart.
const char kInvalidatorSavedInvalidations[] = "invalidator.saved_invalidations";
// Boolean indicating that TiclInvalidationService should use GCM channel.
// False or lack of settings means XMPPPushClient channel.
const char kInvalidationServiceUseGCMChannel[] =
"invalidation_service.use_gcm_channel";
} // namespace prefs
} // namespace invalidation
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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.
#include <google/protobuf/util/internal/json_stream_parser.h>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <memory>
#include <stack>
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/status.h>
#include <google/protobuf/util/internal/object_writer.h>
#include <google/protobuf/util/internal/json_escaping.h>
namespace google {
namespace protobuf {
namespace util {
namespace converter {
// Number of digits in an escaped UTF-16 code unit ('\\' 'u' X X X X)
static const int kUnicodeEscapedLength = 6;
static const int kDefaultMaxRecursionDepth = 100;
// These cannot be constexpr for portability with VS2015.
static const StringPiece kKeywordTrue = "true";
static const StringPiece kKeywordFalse = "false";
static const StringPiece kKeywordNull = "null";
inline bool IsLetter(char c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || (c == '_') ||
(c == '$');
}
inline bool IsAlphanumeric(char c) {
return IsLetter(c) || ('0' <= c && c <= '9');
}
// Indicates a character may not be part of an unquoted key.
inline bool IsKeySeparator(char c) {
return (ascii_isspace(c) || c == '"' || c == '\'' || c == '{' ||
c == '}' || c == '[' || c == ']' || c == ':' || c == ',');
}
inline void ReplaceInvalidCodePoints(StringPiece str,
const std::string& replacement,
std::string* dst) {
while (!str.empty()) {
int n_valid_bytes = internal::UTF8SpnStructurallyValid(str);
StringPiece valid_part = str.substr(0, n_valid_bytes);
StrAppend(dst, valid_part);
if (n_valid_bytes == str.size()) {
break;
}
// Append replacement value.
StrAppend(dst, replacement);
// Move past valid bytes + one invalid byte.
str.remove_prefix(n_valid_bytes + 1);
}
}
static bool ConsumeKey(StringPiece* input, StringPiece* key) {
if (input->empty() || !IsLetter((*input)[0])) return false;
int len = 1;
for (; len < input->size(); ++len) {
if (!IsAlphanumeric((*input)[len])) {
break;
}
}
*key = StringPiece(input->data(), len);
*input = StringPiece(input->data() + len, input->size() - len);
return true;
}
// Same as 'ConsumeKey', but allows a widened set of key characters.
static bool ConsumeKeyPermissive(StringPiece* input,
StringPiece* key) {
if (input->empty() || !IsLetter((*input)[0])) return false;
int len = 1;
for (; len < input->size(); ++len) {
if (IsKeySeparator((*input)[len])) {
break;
}
}
*key = StringPiece(input->data(), len);
*input = StringPiece(input->data() + len, input->size() - len);
return true;
}
static bool MatchKey(StringPiece input) {
return !input.empty() && IsLetter(input[0]);
}
JsonStreamParser::JsonStreamParser(ObjectWriter* ow)
: ow_(ow),
stack_(),
leftover_(),
json_(),
p_(),
key_(),
key_storage_(),
finishing_(false),
seen_non_whitespace_(false),
allow_no_root_element_(false),
parsed_(),
parsed_storage_(),
string_open_(0),
chunk_storage_(),
coerce_to_utf8_(false),
utf8_replacement_character_(" "),
allow_empty_null_(false),
allow_permissive_key_naming_(false),
loose_float_number_conversion_(false),
recursion_depth_(0),
max_recursion_depth_(kDefaultMaxRecursionDepth) {
// Initialize the stack with a single value to be parsed.
stack_.push(VALUE);
}
JsonStreamParser::~JsonStreamParser() {}
util::Status JsonStreamParser::Parse(StringPiece json) {
StringPiece chunk = json;
// If we have leftovers from a previous chunk, append the new chunk to it
// and create a new StringPiece pointing at the string's data. This could
// be large but we rely on the chunks to be small, assuming they are
// fragments of a Cord.
if (!leftover_.empty()) {
// Don't point chunk to leftover_ because leftover_ will be updated in
// ParseChunk(chunk).
chunk_storage_.swap(leftover_);
StrAppend(&chunk_storage_, json);
chunk = StringPiece(chunk_storage_);
}
// Find the structurally valid UTF8 prefix and parse only that.
int n = internal::UTF8SpnStructurallyValid(chunk);
if (n > 0) {
util::Status status = ParseChunk(chunk.substr(0, n));
// Any leftover characters are stashed in leftover_ for later parsing when
// there is more data available.
StrAppend(&leftover_, chunk.substr(n));
return status;
} else {
leftover_.assign(chunk.data(), chunk.size());
return util::Status();
}
}
util::Status JsonStreamParser::FinishParse() {
// If we do not expect anything and there is nothing left to parse we're all
// done.
if (stack_.empty() && leftover_.empty()) {
return util::Status();
}
// Lifetime needs to last until RunParser returns, so keep this variable
// outside of the coerce_to_utf8 block.
std::unique_ptr<std::string> scratch;
bool is_valid_utf8 = internal::IsStructurallyValidUTF8(leftover_);
if (coerce_to_utf8_ && !is_valid_utf8) {
scratch.reset(new std::string);
scratch->reserve(leftover_.size() * utf8_replacement_character_.size());
ReplaceInvalidCodePoints(leftover_, utf8_replacement_character_,
scratch.get());
p_ = json_ = *scratch;
} else {
p_ = json_ = leftover_;
if (!is_valid_utf8) {
return ReportFailure("Encountered non UTF-8 code points.",
ParseErrorType::NON_UTF_8);
}
}
// Parse the remainder in finishing mode, which reports errors for things like
// unterminated strings or unknown tokens that would normally be retried.
finishing_ = true;
util::Status result = RunParser();
if (result.ok()) {
SkipWhitespace();
if (!p_.empty()) {
result =
ReportFailure("Parsing terminated before end of input.",
ParseErrorType::PARSING_TERMINATED_BEFORE_END_OF_INPUT);
}
}
return result;
}
util::Status JsonStreamParser::ParseChunk(StringPiece chunk) {
// Do not do any work if the chunk is empty.
if (chunk.empty()) return util::Status();
p_ = json_ = chunk;
finishing_ = false;
util::Status result = RunParser();
if (!result.ok()) return result;
SkipWhitespace();
if (p_.empty()) {
// If we parsed everything we had, clear the leftover.
leftover_.clear();
} else {
// If we do not expect anything i.e. stack is empty, and we have non-empty
// string left to parse, we report an error.
if (stack_.empty()) {
return ReportFailure(
"Parsing terminated before end of input.",
ParseErrorType::PARSING_TERMINATED_BEFORE_END_OF_INPUT);
}
// If we expect future data i.e. stack is non-empty, and we have some
// unparsed data left, we save it for later parse.
leftover_ = std::string(p_);
}
return util::Status();
}
bool JsonStreamParser::IsInputAllWhiteSpaces(TokenType type) {
// Conclude the whole input is full of white spaces by:
// - it is at the finishing stage
// - we have run out of the input data
// - haven't seen non-whitespace char so far
if (finishing_ && p_.empty() && type == UNKNOWN && !seen_non_whitespace_) {
return true;
}
return false;
}
util::Status JsonStreamParser::RunParser() {
while (!stack_.empty()) {
ParseType type = stack_.top();
TokenType t = (string_open_ == 0) ? GetNextTokenType() : BEGIN_STRING;
stack_.pop();
util::Status result;
switch (type) {
case VALUE:
if (allow_no_root_element_ && IsInputAllWhiteSpaces(t)) {
return util::Status();
}
result = ParseValue(t);
break;
case OBJ_MID:
result = ParseObjectMid(t);
break;
case ENTRY:
result = ParseEntry(t);
break;
case ENTRY_MID:
result = ParseEntryMid(t);
break;
case ARRAY_VALUE:
result = ParseArrayValue(t);
break;
case ARRAY_MID:
result = ParseArrayMid(t);
break;
default:
result =
util::InternalError(StrCat("Unknown parse type: ", type));
break;
}
if (!result.ok()) {
// If we were cancelled, save our state and try again later.
if (!finishing_ && util::IsCancelled(result)) {
stack_.push(type);
// If we have a key we still need to render, make sure to save off the
// contents in our own storage.
if (!key_.empty() && key_storage_.empty()) {
StrAppend(&key_storage_, key_);
key_ = StringPiece(key_storage_);
}
result = util::Status();
}
return result;
}
}
return util::Status();
}
util::Status JsonStreamParser::ParseValue(TokenType type) {
switch (type) {
case BEGIN_OBJECT:
return HandleBeginObject();
case BEGIN_ARRAY:
return HandleBeginArray();
case BEGIN_STRING:
return ParseString();
case BEGIN_NUMBER:
return ParseNumber();
case BEGIN_TRUE:
return ParseTrue();
case BEGIN_FALSE:
return ParseFalse();
case BEGIN_NULL:
return ParseNull();
case UNKNOWN:
return ReportUnknown("Expected a value.", ParseErrorType::EXPECTED_VALUE);
default: {
// Special case for having been cut off while parsing, wait for more data.
// This handles things like 'fals' being at the end of the string, we
// don't know if the next char would be e, completing it, or something
// else, making it invalid.
if (!finishing_ && p_.length() < kKeywordFalse.length()) {
return util::CancelledError("");
}
if (allow_empty_null_ && IsEmptyNullAllowed(type)) {
return ParseEmptyNull();
}
return ReportFailure("Unexpected token.",
ParseErrorType::UNEXPECTED_TOKEN);
}
}
}
util::Status JsonStreamParser::ParseString() {
util::Status result = ParseStringHelper();
if (result.ok()) {
ow_->RenderString(key_, parsed_);
key_ = StringPiece();
parsed_ = StringPiece();
parsed_storage_.clear();
}
return result;
}
util::Status JsonStreamParser::ParseStringHelper() {
// If we haven't seen the start quote, grab it and remember it for later.
if (string_open_ == 0) {
string_open_ = *p_.data();
GOOGLE_DCHECK(string_open_ == '\"' || string_open_ == '\'');
Advance();
}
// Track where we last copied data from so we can minimize copying.
const char* last = p_.data();
while (!p_.empty()) {
const char* data = p_.data();
if (*data == '\\') {
// We're about to handle an escape, copy all bytes from last to data.
if (last < data) {
parsed_storage_.append(last, data - last);
}
// If we ran out of string after the \, cancel or report an error
// depending on if we expect more data later.
if (p_.length() == 1) {
if (!finishing_) {
return util::CancelledError("");
}
return ReportFailure("Closing quote expected in string.",
ParseErrorType::EXPECTED_CLOSING_QUOTE);
}
// Parse a unicode escape if we found \u in the string.
if (data[1] == 'u') {
util::Status result = ParseUnicodeEscape();
if (!result.ok()) {
return result;
}
// Move last pointer past the unicode escape and continue.
last = p_.data();
continue;
}
// Handle the standard set of backslash-escaped characters.
switch (data[1]) {
case 'b':
parsed_storage_.push_back('\b');
break;
case 'f':
parsed_storage_.push_back('\f');
break;
case 'n':
parsed_storage_.push_back('\n');
break;
case 'r':
parsed_storage_.push_back('\r');
break;
case 't':
parsed_storage_.push_back('\t');
break;
case 'v':
parsed_storage_.push_back('\v');
break;
default:
parsed_storage_.push_back(data[1]);
}
// We handled two characters, so advance past them and continue.
p_.remove_prefix(2);
last = p_.data();
continue;
}
// If we found the closing quote note it, advance past it, and return.
if (*data == string_open_) {
// If we didn't copy anything, reuse the input buffer.
if (parsed_storage_.empty()) {
parsed_ = StringPiece(last, data - last);
} else {
if (last < data) {
parsed_storage_.append(last, data - last);
}
parsed_ = StringPiece(parsed_storage_);
}
// Clear the quote char so next time we try to parse a string we'll
// start fresh.
string_open_ = 0;
Advance();
return util::Status();
}
// Normal character, just advance past it.
Advance();
}
// If we ran out of characters, copy over what we have so far.
if (last < p_.data()) {
parsed_storage_.append(last, p_.data() - last);
}
// If we didn't find the closing quote but we expect more data, cancel for now
if (!finishing_) {
return util::CancelledError("");
}
// End of string reached without a closing quote, report an error.
string_open_ = 0;
return ReportFailure("Closing quote expected in string.",
ParseErrorType::EXPECTED_CLOSING_QUOTE);
}
// Converts a unicode escaped character to a decimal value stored in a char32
// for use in UTF8 encoding utility. We assume that str begins with \uhhhh and
// convert that from the hex number to a decimal value.
//
// There are some security exploits with UTF-8 that we should be careful of:
// - http://www.unicode.org/reports/tr36/#UTF-8_Exploit
// - http://sites/intl-eng/design-guide/core-application
util::Status JsonStreamParser::ParseUnicodeEscape() {
if (p_.length() < kUnicodeEscapedLength) {
if (!finishing_) {
return util::CancelledError("");
}
return ReportFailure("Illegal hex string.",
ParseErrorType::ILLEGAL_HEX_STRING);
}
GOOGLE_DCHECK_EQ('\\', p_.data()[0]);
GOOGLE_DCHECK_EQ('u', p_.data()[1]);
uint32 code = 0;
for (int i = 2; i < kUnicodeEscapedLength; ++i) {
if (!isxdigit(p_.data()[i])) {
return ReportFailure("Invalid escape sequence.",
ParseErrorType::INVALID_ESCAPE_SEQUENCE);
}
code = (code << 4) + hex_digit_to_int(p_.data()[i]);
}
if (code >= JsonEscaping::kMinHighSurrogate &&
code <= JsonEscaping::kMaxHighSurrogate) {
if (p_.length() < 2 * kUnicodeEscapedLength) {
if (!finishing_) {
return util::CancelledError("");
}
if (!coerce_to_utf8_) {
return ReportFailure("Missing low surrogate.",
ParseErrorType::MISSING_LOW_SURROGATE);
}
} else if (p_.data()[kUnicodeEscapedLength] == '\\' &&
p_.data()[kUnicodeEscapedLength + 1] == 'u') {
uint32 low_code = 0;
for (int i = kUnicodeEscapedLength + 2; i < 2 * kUnicodeEscapedLength;
++i) {
if (!isxdigit(p_.data()[i])) {
return ReportFailure("Invalid escape sequence.",
ParseErrorType::INVALID_ESCAPE_SEQUENCE);
}
low_code = (low_code << 4) + hex_digit_to_int(p_.data()[i]);
}
if (low_code >= JsonEscaping::kMinLowSurrogate &&
low_code <= JsonEscaping::kMaxLowSurrogate) {
// Convert UTF-16 surrogate pair to 21-bit Unicode codepoint.
code = (((code & 0x3FF) << 10) | (low_code & 0x3FF)) +
JsonEscaping::kMinSupplementaryCodePoint;
// Advance past the first code unit escape.
p_.remove_prefix(kUnicodeEscapedLength);
} else if (!coerce_to_utf8_) {
return ReportFailure("Invalid low surrogate.",
ParseErrorType::INVALID_LOW_SURROGATE);
}
} else if (!coerce_to_utf8_) {
return ReportFailure("Missing low surrogate.",
ParseErrorType::MISSING_LOW_SURROGATE);
}
}
if (!coerce_to_utf8_ && !IsValidCodePoint(code)) {
return ReportFailure("Invalid unicode code point.",
ParseErrorType::INVALID_UNICODE);
}
char buf[UTFmax];
int len = EncodeAsUTF8Char(code, buf);
// Advance past the [final] code unit escape.
p_.remove_prefix(kUnicodeEscapedLength);
parsed_storage_.append(buf, len);
return util::Status();
}
util::Status JsonStreamParser::ParseNumber() {
NumberResult number;
util::Status result = ParseNumberHelper(&number);
if (result.ok()) {
switch (number.type) {
case NumberResult::DOUBLE:
ow_->RenderDouble(key_, number.double_val);
key_ = StringPiece();
break;
case NumberResult::INT:
ow_->RenderInt64(key_, number.int_val);
key_ = StringPiece();
break;
case NumberResult::UINT:
ow_->RenderUint64(key_, number.uint_val);
key_ = StringPiece();
break;
default:
return ReportFailure("Unable to parse number.",
ParseErrorType::UNABLE_TO_PARSE_NUMBER);
}
}
return result;
}
util::Status JsonStreamParser::ParseDoubleHelper(const std::string& number,
NumberResult* result) {
if (!safe_strtod(number, &result->double_val)) {
return ReportFailure("Unable to parse number.",
ParseErrorType::UNABLE_TO_PARSE_NUMBER);
}
if (!loose_float_number_conversion_ && !std::isfinite(result->double_val)) {
return ReportFailure("Number exceeds the range of double.",
ParseErrorType::NUMBER_EXCEEDS_RANGE_DOUBLE);
}
result->type = NumberResult::DOUBLE;
return util::Status();
}
util::Status JsonStreamParser::ParseNumberHelper(NumberResult* result) {
const char* data = p_.data();
int length = p_.length();
// Look for the first non-numeric character, or the end of the string.
int index = 0;
bool floating = false;
bool negative = data[index] == '-';
// Find the first character that cannot be part of the number. Along the way
// detect if the number needs to be parsed as a double.
// Note that this restricts numbers to the JSON specification, so for example
// we do not support hex or octal notations.
for (; index < length; ++index) {
char c = data[index];
if (isdigit(c)) continue;
if (c == '.' || c == 'e' || c == 'E') {
floating = true;
continue;
}
if (c == '+' || c == '-' || c == 'x') continue;
// Not a valid number character, break out.
break;
}
// If the entire input is a valid number, and we may have more content in the
// future, we abort for now and resume when we know more.
if (index == length && !finishing_) {
return util::CancelledError("");
}
// Create a string containing just the number, so we can use safe_strtoX
std::string number = std::string(p_.substr(0, index));
// Floating point number, parse as a double.
if (floating) {
util::Status status = ParseDoubleHelper(number, result);
if (status.ok()) {
p_.remove_prefix(index);
}
return status;
}
// Positive non-floating point number, parse as a uint64.
if (!negative) {
// Octal/Hex numbers are not valid JSON values.
if (number.length() >= 2 && number[0] == '0') {
return ReportFailure(
"Octal/hex numbers are not valid JSON values.",
ParseErrorType::OCTAL_OR_HEX_ARE_NOT_VALID_JSON_VALUES);
}
if (safe_strtou64(number, &result->uint_val)) {
result->type = NumberResult::UINT;
p_.remove_prefix(index);
return util::Status();
} else {
// If the value is too large, parse it as double.
util::Status status = ParseDoubleHelper(number, result);
if (status.ok()) {
p_.remove_prefix(index);
}
return status;
}
}
// Octal/Hex numbers are not valid JSON values.
if (number.length() >= 3 && number[1] == '0') {
return ReportFailure(
"Octal/hex numbers are not valid JSON values.",
ParseErrorType::OCTAL_OR_HEX_ARE_NOT_VALID_JSON_VALUES);
}
// Negative non-floating point number, parse as an int64.
if (safe_strto64(number, &result->int_val)) {
result->type = NumberResult::INT;
p_.remove_prefix(index);
return util::Status();
} else {
// If the value is too large, parse it as double.
util::Status status = ParseDoubleHelper(number, result);
if (status.ok()) {
p_.remove_prefix(index);
}
return status;
}
}
util::Status JsonStreamParser::HandleBeginObject() {
GOOGLE_DCHECK_EQ('{', *p_.data());
Advance();
ow_->StartObject(key_);
auto status = IncrementRecursionDepth(key_);
if (!status.ok()) {
return status;
}
key_ = StringPiece();
stack_.push(ENTRY);
return util::Status();
}
util::Status JsonStreamParser::ParseObjectMid(TokenType type) {
if (type == UNKNOWN) {
return ReportUnknown("Expected , or } after key:value pair.",
ParseErrorType::EXPECTED_COMMA_OR_BRACES);
}
// Object is complete, advance past the comma and render the EndObject.
if (type == END_OBJECT) {
Advance();
ow_->EndObject();
--recursion_depth_;
return util::Status();
}
// Found a comma, advance past it and get ready for an entry.
if (type == VALUE_SEPARATOR) {
Advance();
stack_.push(ENTRY);
return util::Status();
}
// Illegal token after key:value pair.
return ReportFailure("Expected , or } after key:value pair.",
ParseErrorType::EXPECTED_COMMA_OR_BRACES);
}
util::Status JsonStreamParser::ParseEntry(TokenType type) {
if (type == UNKNOWN) {
return ReportUnknown("Expected an object key or }.",
ParseErrorType::EXPECTED_OBJECT_KEY_OR_BRACES);
}
// Close the object and return. This allows for trailing commas.
if (type == END_OBJECT) {
ow_->EndObject();
Advance();
--recursion_depth_;
return util::Status();
}
util::Status result;
if (type == BEGIN_STRING) {
// Key is a string (standard JSON), parse it and store the string.
result = ParseStringHelper();
if (result.ok()) {
key_storage_.clear();
if (!parsed_storage_.empty()) {
parsed_storage_.swap(key_storage_);
key_ = StringPiece(key_storage_);
} else {
key_ = parsed_;
}
parsed_ = StringPiece();
}
} else if (type == BEGIN_KEY) {
// Key is a bare key (back compat), create a StringPiece pointing to it.
result = ParseKey();
} else if (type == BEGIN_NULL || type == BEGIN_TRUE || type == BEGIN_FALSE) {
// Key may be a bare key that begins with a reserved word.
result = ParseKey();
if (result.ok() && (key_ == kKeywordNull || key_ == kKeywordTrue ||
key_ == kKeywordFalse)) {
result = ReportFailure("Expected an object key or }.",
ParseErrorType::EXPECTED_OBJECT_KEY_OR_BRACES);
}
} else {
// Unknown key type, report an error.
result = ReportFailure("Expected an object key or }.",
ParseErrorType::EXPECTED_OBJECT_KEY_OR_BRACES);
}
// On success we next expect an entry mid ':' then an object mid ',' or '}'
if (result.ok()) {
stack_.push(OBJ_MID);
stack_.push(ENTRY_MID);
}
return result;
}
util::Status JsonStreamParser::ParseEntryMid(TokenType type) {
if (type == UNKNOWN) {
return ReportUnknown("Expected : between key:value pair.",
ParseErrorType::EXPECTED_COLON);
}
if (type == ENTRY_SEPARATOR) {
Advance();
stack_.push(VALUE);
return util::Status();
}
return ReportFailure("Expected : between key:value pair.",
ParseErrorType::EXPECTED_COLON);
}
util::Status JsonStreamParser::HandleBeginArray() {
GOOGLE_DCHECK_EQ('[', *p_.data());
Advance();
ow_->StartList(key_);
key_ = StringPiece();
stack_.push(ARRAY_VALUE);
return util::Status();
}
util::Status JsonStreamParser::ParseArrayValue(TokenType type) {
if (type == UNKNOWN) {
return ReportUnknown("Expected a value or ] within an array.",
ParseErrorType::EXPECTED_VALUE_OR_BRACKET);
}
if (type == END_ARRAY) {
ow_->EndList();
Advance();
return util::Status();
}
// The ParseValue call may push something onto the stack so we need to make
// sure an ARRAY_MID is after it, so we push it on now. Also, the parsing of
// empty-null array value is relying on this ARRAY_MID token.
stack_.push(ARRAY_MID);
util::Status result = ParseValue(type);
if (util::IsCancelled(result)) {
// If we were cancelled, pop back off the ARRAY_MID so we don't try to
// push it on again when we try over.
stack_.pop();
}
return result;
}
util::Status JsonStreamParser::ParseArrayMid(TokenType type) {
if (type == UNKNOWN) {
return ReportUnknown("Expected , or ] after array value.",
ParseErrorType::EXPECTED_COMMA_OR_BRACKET);
}
if (type == END_ARRAY) {
ow_->EndList();
Advance();
return util::Status();
}
// Found a comma, advance past it and expect an array value next.
if (type == VALUE_SEPARATOR) {
Advance();
stack_.push(ARRAY_VALUE);
return util::Status();
}
// Illegal token after array value.
return ReportFailure("Expected , or ] after array value.",
ParseErrorType::EXPECTED_COMMA_OR_BRACKET);
}
util::Status JsonStreamParser::ParseTrue() {
ow_->RenderBool(key_, true);
key_ = StringPiece();
p_.remove_prefix(kKeywordTrue.length());
return util::Status();
}
util::Status JsonStreamParser::ParseFalse() {
ow_->RenderBool(key_, false);
key_ = StringPiece();
p_.remove_prefix(kKeywordFalse.length());
return util::Status();
}
util::Status JsonStreamParser::ParseNull() {
ow_->RenderNull(key_);
key_ = StringPiece();
p_.remove_prefix(kKeywordNull.length());
return util::Status();
}
util::Status JsonStreamParser::ParseEmptyNull() {
ow_->RenderNull(key_);
key_ = StringPiece();
return util::Status();
}
bool JsonStreamParser::IsEmptyNullAllowed(TokenType type) {
if (stack_.empty()) return false;
return (stack_.top() == ARRAY_MID && type == VALUE_SEPARATOR) ||
stack_.top() == OBJ_MID;
}
util::Status JsonStreamParser::ReportFailure(StringPiece message,
ParseErrorType parse_code) {
static const int kContextLength = 20;
const char* p_start = p_.data();
const char* json_start = json_.data();
const char* begin = std::max(p_start - kContextLength, json_start);
const char* end =
std::min(p_start + kContextLength, json_start + json_.size());
StringPiece segment(begin, end - begin);
std::string location(p_start - begin, ' ');
location.push_back('^');
auto status = util::InvalidArgumentError(
StrCat(message, "\n", segment, "\n", location));
return status;
}
util::Status JsonStreamParser::ReportUnknown(StringPiece message,
ParseErrorType parse_code) {
// If we aren't finishing the parse, cancel parsing and try later.
if (!finishing_) {
return util::CancelledError("");
}
if (p_.empty()) {
return ReportFailure(StrCat("Unexpected end of string. ", message),
parse_code);
}
return ReportFailure(message, parse_code);
}
util::Status JsonStreamParser::IncrementRecursionDepth(
StringPiece key) const {
if (++recursion_depth_ > max_recursion_depth_) {
return util::InvalidArgumentError(StrCat(
"Message too deep. Max recursion depth reached for key '", key, "'"));
}
return util::Status();
}
void JsonStreamParser::SkipWhitespace() {
while (!p_.empty() && ascii_isspace(*p_.data())) {
Advance();
}
if (!p_.empty() && !ascii_isspace(*p_.data())) {
seen_non_whitespace_ = true;
}
}
void JsonStreamParser::Advance() {
// Advance by moving one UTF8 character while making sure we don't go beyond
// the length of StringPiece.
p_.remove_prefix(std::min<int>(
p_.length(), UTF8FirstLetterNumBytes(p_.data(), p_.length())));
}
util::Status JsonStreamParser::ParseKey() {
StringPiece original = p_;
if (allow_permissive_key_naming_) {
if (!ConsumeKeyPermissive(&p_, &key_)) {
return ReportFailure("Invalid key or variable name.",
ParseErrorType::INVALID_KEY_OR_VARIABLE_NAME);
}
} else {
if (!ConsumeKey(&p_, &key_)) {
return ReportFailure("Invalid key or variable name.",
ParseErrorType::INVALID_KEY_OR_VARIABLE_NAME);
}
}
// If we consumed everything but expect more data, reset p_ and cancel since
// we can't know if the key was complete or not.
if (!finishing_ && p_.empty()) {
p_ = original;
return util::CancelledError("");
}
// Since we aren't using the key storage, clear it out.
key_storage_.clear();
return util::Status();
}
JsonStreamParser::TokenType JsonStreamParser::GetNextTokenType() {
SkipWhitespace();
int size = p_.size();
if (size == 0) {
// If we ran out of data, report unknown and we'll place the previous parse
// type onto the stack and try again when we have more data.
return UNKNOWN;
}
// TODO(sven): Split this method based on context since different contexts
// support different tokens. Would slightly speed up processing?
const char* data = p_.data();
StringPiece data_view = StringPiece(data, size);
if (*data == '\"' || *data == '\'') return BEGIN_STRING;
if (*data == '-' || ('0' <= *data && *data <= '9')) {
return BEGIN_NUMBER;
}
if (size >= kKeywordTrue.length() &&
HasPrefixString(data_view, kKeywordTrue)) {
return BEGIN_TRUE;
}
if (size >= kKeywordFalse.length() &&
HasPrefixString(data_view, kKeywordFalse)) {
return BEGIN_FALSE;
}
if (size >= kKeywordNull.length() &&
HasPrefixString(data_view, kKeywordNull)) {
return BEGIN_NULL;
}
if (*data == '{') return BEGIN_OBJECT;
if (*data == '}') return END_OBJECT;
if (*data == '[') return BEGIN_ARRAY;
if (*data == ']') return END_ARRAY;
if (*data == ':') return ENTRY_SEPARATOR;
if (*data == ',') return VALUE_SEPARATOR;
if (MatchKey(p_)) {
return BEGIN_KEY;
}
// We don't know that we necessarily have an invalid token here, just that we
// can't parse what we have so far. So we don't report an error and just
// return UNKNOWN so we can try again later when we have more data, or if we
// finish and we have leftovers.
return UNKNOWN;
}
} // namespace converter
} // namespace util
} // namespace protobuf
} // namespace google
|
//ๆญคๆบ็ ่ขซๆธ
ๅๅญฆ็ฅๅฐนๆๅคง้ญ็ไธไธ็ฟป่ฏๅๆๅนถไฟฎๆน
//ๅฐนๆQQ77025077
//ๅฐนๆๅพฎไฟก18510341407
//ๅฐนๆๆๅจQQ็พค721929980
//ๅฐนๆ้ฎ็ฎฑ yinc13@mails.tsinghua.edu.cn
//ๅฐนๆๆฏไธไบๆธ
ๅๅคงๅญฆ,ๅพฎ่ฝฏๅบๅ้พ้ขๅๅ
จ็ๆๆไปทๅผไธๅฎถ
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/*
ๆญคๆไปถๆฏRippled็ไธ้จๅ๏ผhttps://github.com/ripple/rippled
็ๆๆๆ๏ผc๏ผ2012๏ผ2013 Ripple Labs Inc.
ไฝฟ็จใๅคๅถใไฟฎๆนๅ/ๆๅๅๆฌ่ฝฏไปถ็ๆ้
็นๆญคๆไบๅ
่ดนๆไธๆถ่ดน็็ฎ็๏ผๅๆๆฏ
็ๆๅฃฐๆๅๆฌ่ฎธๅฏๅฃฐๆๅบ็ฐๅจๆๆๅฏๆฌไธญใ
ๆฌ่ฝฏไปถๆโๅๆ ทโๆไพ๏ผไฝ่
ไธไฝไปปไฝไฟ่ฏใ
ๅ
ณไบๆฌ่ฝฏไปถ๏ผๅ
ๆฌ
้้ๆงๅ้็จๆงใๅจไปปไฝๆ
ๅตไธ๏ผไฝ่
้ฝไธๅฏน
ไปปไฝ็นๆฎใ็ดๆฅใ้ดๆฅๆๅๆๆงๆๅฎณๆไปปไฝๆๅฎณ
ๅ ไฝฟ็จใๆฐๆฎๆๅฉๆถฆๆๅคฑ่ๅฏผ่ด็ไปปไฝๆ
ๅต๏ผๆ ่ฎบๆฏๅจ
ๅๅ่กไธบใ็ๅฟฝๆๅ
ถไปไพตๆ่กไธบ
ๆไธๆฌ่ฝฏไปถ็ไฝฟ็จๆๆง่ฝๆๅ
ณใ
**/
//==============================================================
#include <ripple/basics/Log.h>
#include <ripple/basics/random.h>
#include <ripple/protocol/STAmount.h>
#include <ripple/beast/unit_test.h>
namespace ripple {
class STAmount_test : public beast::unit_test::suite
{
public:
static STAmount serializeAndDeserialize (STAmount const& s)
{
Serializer ser;
s.add (ser);
SerialIter sit (ser.slice());
return STAmount(sit, sfGeneric);
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
STAmount roundSelf (STAmount const& amount)
{
if (amount.native ())
return amount;
std::uint64_t mantissa = amount.mantissa ();
std::uint64_t valueDigits = mantissa % 1000000000;
if (valueDigits == 1)
{
mantissa--;
if (mantissa < STAmount::cMinValue)
return { amount.issue (), mantissa, amount.exponent (),
amount.negative () };
return { amount.issue (), mantissa, amount.exponent (),
amount.native(), amount.negative (), STAmount::unchecked {} };
}
if (valueDigits == 999999999)
{
mantissa++;
if (mantissa > STAmount::cMaxValue)
return { amount.issue (), mantissa, amount.exponent (),
amount.negative () };
return { amount.issue (), mantissa, amount.exponent (),
amount.native(), amount.negative (), STAmount::unchecked {} };
}
return amount;
}
void roundTest (int n, int d, int m)
{
//ๆฃๆฅStamCount่ๅ
ฅ
STAmount num (noIssue(), n);
STAmount den (noIssue(), d);
STAmount mul (noIssue(), m);
STAmount quot = divide (n, d, noIssue());
STAmount res = roundSelf (multiply (quot, mul, noIssue()));
BEAST_EXPECT(! res.native ());
STAmount cmp (noIssue(), (n * m) / d);
BEAST_EXPECT(! cmp.native ());
BEAST_EXPECT(cmp.issue().currency == res.issue().currency);
if (res != cmp)
{
log <<
"(" << num.getText () << "/" << den.getText () <<
") X " << mul.getText () << " = " << res.getText () <<
" not " << cmp.getText ();
fail ("Rounding");
return;
}
}
void mulTest (int a, int b)
{
STAmount aa (noIssue(), a);
STAmount bb (noIssue(), b);
STAmount prod1 (multiply (aa, bb, noIssue()));
BEAST_EXPECT(! prod1.native ());
STAmount prod2 (noIssue(), static_cast<std::uint64_t> (a) * static_cast<std::uint64_t> (b));
if (prod1 != prod2)
{
log <<
"nn(" << aa.getFullText () << " * " << bb.getFullText () <<
") = " << prod1.getFullText () << " not " << prod2.getFullText ();
fail ("Multiplication result is not exact");
}
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void testSetValue (
std::string const& value, Issue const& issue, bool success = true)
{
try
{
STAmount const amount = amountFromString (issue, value);
BEAST_EXPECT(amount.getText () == value);
}
catch (std::exception const&)
{
BEAST_EXPECT(!success);
}
}
void testSetValue ()
{
{
testcase ("set value (native)");
Issue const xrp (xrpIssue ());
//้จๅxrp๏ผๅณๆปดๅ๏ผ
testSetValue ("1", xrp);
testSetValue ("22", xrp);
testSetValue ("333", xrp);
testSetValue ("4444", xrp);
testSetValue ("55555", xrp);
testSetValue ("666666", xrp);
//1 XRP้ซ่พพ1000ไบฟ๏ผ10ๆฌกๆน๏ผๆปด๏ผ
testSetValue ("1000000", xrp);
testSetValue ("10000000", xrp);
testSetValue ("100000000", xrp);
testSetValue ("1000000000", xrp);
testSetValue ("10000000000", xrp);
testSetValue ("100000000000", xrp);
testSetValue ("1000000000000", xrp);
testSetValue ("10000000000000", xrp);
testSetValue ("100000000000000", xrp);
testSetValue ("1000000000000000", xrp);
testSetValue ("10000000000000000", xrp);
testSetValue ("100000000000000000", xrp);
//ๆ ๆ็ๆฌๆบๅผ๏ผ
testSetValue ("1.1", xrp, false);
testSetValue ("100000000000000001", xrp, false);
testSetValue ("1000000000000000000", xrp, false);
}
{
testcase ("set value (iou)");
Issue const usd (Currency (0x5553440000000000), AccountID (0x4985601));
testSetValue ("1", usd);
testSetValue ("10", usd);
testSetValue ("100", usd);
testSetValue ("1000", usd);
testSetValue ("10000", usd);
testSetValue ("100000", usd);
testSetValue ("1000000", usd);
testSetValue ("10000000", usd);
testSetValue ("100000000", usd);
testSetValue ("1000000000", usd);
testSetValue ("10000000000", usd);
testSetValue ("1234567.1", usd);
testSetValue ("1234567.12", usd);
testSetValue ("1234567.123", usd);
testSetValue ("1234567.1234", usd);
testSetValue ("1234567.12345", usd);
testSetValue ("1234567.123456", usd);
testSetValue ("1234567.1234567", usd);
testSetValue ("1234567.12345678", usd);
testSetValue ("1234567.123456789", usd);
}
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void testNativeCurrency ()
{
testcase ("native currency");
STAmount zeroSt, one (1), hundred (100);
//vfalcๆณจ๏ผไธบไปไน้ๅคโstamount failโ่ฟไนๅคๆฌก๏ผ๏ผ
unexpected (serializeAndDeserialize (zeroSt) != zeroSt, "STAmount fail");
unexpected (serializeAndDeserialize (one) != one, "STAmount fail");
unexpected (serializeAndDeserialize (hundred) != hundred, "STAmount fail");
unexpected (!zeroSt.native (), "STAmount fail");
unexpected (!hundred.native (), "STAmount fail");
unexpected (zeroSt != beast::zero, "STAmount fail");
unexpected (one == beast::zero, "STAmount fail");
unexpected (hundred == beast::zero, "STAmount fail");
unexpected ((zeroSt < zeroSt), "STAmount fail");
unexpected (! (zeroSt < one), "STAmount fail");
unexpected (! (zeroSt < hundred), "STAmount fail");
unexpected ((one < zeroSt), "STAmount fail");
unexpected ((one < one), "STAmount fail");
unexpected (! (one < hundred), "STAmount fail");
unexpected ((hundred < zeroSt), "STAmount fail");
unexpected ((hundred < one), "STAmount fail");
unexpected ((hundred < hundred), "STAmount fail");
unexpected ((zeroSt > zeroSt), "STAmount fail");
unexpected ((zeroSt > one), "STAmount fail");
unexpected ((zeroSt > hundred), "STAmount fail");
unexpected (! (one > zeroSt), "STAmount fail");
unexpected ((one > one), "STAmount fail");
unexpected ((one > hundred), "STAmount fail");
unexpected (! (hundred > zeroSt), "STAmount fail");
unexpected (! (hundred > one), "STAmount fail");
unexpected ((hundred > hundred), "STAmount fail");
unexpected (! (zeroSt <= zeroSt), "STAmount fail");
unexpected (! (zeroSt <= one), "STAmount fail");
unexpected (! (zeroSt <= hundred), "STAmount fail");
unexpected ((one <= zeroSt), "STAmount fail");
unexpected (! (one <= one), "STAmount fail");
unexpected (! (one <= hundred), "STAmount fail");
unexpected ((hundred <= zeroSt), "STAmount fail");
unexpected ((hundred <= one), "STAmount fail");
unexpected (! (hundred <= hundred), "STAmount fail");
unexpected (! (zeroSt >= zeroSt), "STAmount fail");
unexpected ((zeroSt >= one), "STAmount fail");
unexpected ((zeroSt >= hundred), "STAmount fail");
unexpected (! (one >= zeroSt), "STAmount fail");
unexpected (! (one >= one), "STAmount fail");
unexpected ((one >= hundred), "STAmount fail");
unexpected (! (hundred >= zeroSt), "STAmount fail");
unexpected (! (hundred >= one), "STAmount fail");
unexpected (! (hundred >= hundred), "STAmount fail");
unexpected (! (zeroSt == zeroSt), "STAmount fail");
unexpected ((zeroSt == one), "STAmount fail");
unexpected ((zeroSt == hundred), "STAmount fail");
unexpected ((one == zeroSt), "STAmount fail");
unexpected (! (one == one), "STAmount fail");
unexpected ((one == hundred), "STAmount fail");
unexpected ((hundred == zeroSt), "STAmount fail");
unexpected ((hundred == one), "STAmount fail");
unexpected (! (hundred == hundred), "STAmount fail");
unexpected ((zeroSt != zeroSt), "STAmount fail");
unexpected (! (zeroSt != one), "STAmount fail");
unexpected (! (zeroSt != hundred), "STAmount fail");
unexpected (! (one != zeroSt), "STAmount fail");
unexpected ((one != one), "STAmount fail");
unexpected (! (one != hundred), "STAmount fail");
unexpected (! (hundred != zeroSt), "STAmount fail");
unexpected (! (hundred != one), "STAmount fail");
unexpected ((hundred != hundred), "STAmount fail");
unexpected (STAmount ().getText () != "0", "STAmount fail");
unexpected (STAmount (31).getText () != "31", "STAmount fail");
unexpected (STAmount (310).getText () != "310", "STAmount fail");
unexpected (to_string (Currency ()) != "XRP", "cHC(XRP)");
Currency c;
unexpected (!to_currency (c, "USD"), "create USD currency");
unexpected (to_string (c) != "USD", "check USD currency");
const std::string cur = "015841551A748AD2C1F76FF6ECB0CCCD00000000";
unexpected (!to_currency (c, cur), "create custom currency");
unexpected (to_string (c) != cur, "check custom currency");
unexpected (c != Currency (
from_hex_text<Currency>(cur)), "check custom currency");
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void testCustomCurrency ()
{
testcase ("custom currency");
STAmount zeroSt (noIssue()), one (noIssue(), 1), hundred (noIssue(), 100);
unexpected (serializeAndDeserialize (zeroSt) != zeroSt, "STAmount fail");
unexpected (serializeAndDeserialize (one) != one, "STAmount fail");
unexpected (serializeAndDeserialize (hundred) != hundred, "STAmount fail");
unexpected (zeroSt.native (), "STAmount fail");
unexpected (hundred.native (), "STAmount fail");
unexpected (zeroSt != beast::zero, "STAmount fail");
unexpected (one == beast::zero, "STAmount fail");
unexpected (hundred == beast::zero, "STAmount fail");
unexpected ((zeroSt < zeroSt), "STAmount fail");
unexpected (! (zeroSt < one), "STAmount fail");
unexpected (! (zeroSt < hundred), "STAmount fail");
unexpected ((one < zeroSt), "STAmount fail");
unexpected ((one < one), "STAmount fail");
unexpected (! (one < hundred), "STAmount fail");
unexpected ((hundred < zeroSt), "STAmount fail");
unexpected ((hundred < one), "STAmount fail");
unexpected ((hundred < hundred), "STAmount fail");
unexpected ((zeroSt > zeroSt), "STAmount fail");
unexpected ((zeroSt > one), "STAmount fail");
unexpected ((zeroSt > hundred), "STAmount fail");
unexpected (! (one > zeroSt), "STAmount fail");
unexpected ((one > one), "STAmount fail");
unexpected ((one > hundred), "STAmount fail");
unexpected (! (hundred > zeroSt), "STAmount fail");
unexpected (! (hundred > one), "STAmount fail");
unexpected ((hundred > hundred), "STAmount fail");
unexpected (! (zeroSt <= zeroSt), "STAmount fail");
unexpected (! (zeroSt <= one), "STAmount fail");
unexpected (! (zeroSt <= hundred), "STAmount fail");
unexpected ((one <= zeroSt), "STAmount fail");
unexpected (! (one <= one), "STAmount fail");
unexpected (! (one <= hundred), "STAmount fail");
unexpected ((hundred <= zeroSt), "STAmount fail");
unexpected ((hundred <= one), "STAmount fail");
unexpected (! (hundred <= hundred), "STAmount fail");
unexpected (! (zeroSt >= zeroSt), "STAmount fail");
unexpected ((zeroSt >= one), "STAmount fail");
unexpected ((zeroSt >= hundred), "STAmount fail");
unexpected (! (one >= zeroSt), "STAmount fail");
unexpected (! (one >= one), "STAmount fail");
unexpected ((one >= hundred), "STAmount fail");
unexpected (! (hundred >= zeroSt), "STAmount fail");
unexpected (! (hundred >= one), "STAmount fail");
unexpected (! (hundred >= hundred), "STAmount fail");
unexpected (! (zeroSt == zeroSt), "STAmount fail");
unexpected ((zeroSt == one), "STAmount fail");
unexpected ((zeroSt == hundred), "STAmount fail");
unexpected ((one == zeroSt), "STAmount fail");
unexpected (! (one == one), "STAmount fail");
unexpected ((one == hundred), "STAmount fail");
unexpected ((hundred == zeroSt), "STAmount fail");
unexpected ((hundred == one), "STAmount fail");
unexpected (! (hundred == hundred), "STAmount fail");
unexpected ((zeroSt != zeroSt), "STAmount fail");
unexpected (! (zeroSt != one), "STAmount fail");
unexpected (! (zeroSt != hundred), "STAmount fail");
unexpected (! (one != zeroSt), "STAmount fail");
unexpected ((one != one), "STAmount fail");
unexpected (! (one != hundred), "STAmount fail");
unexpected (! (hundred != zeroSt), "STAmount fail");
unexpected (! (hundred != one), "STAmount fail");
unexpected ((hundred != hundred), "STAmount fail");
unexpected (STAmount (noIssue()).getText () != "0", "STAmount fail");
unexpected (STAmount (noIssue(), 31).getText () != "31", "STAmount fail");
unexpected (STAmount (noIssue(), 31, 1).getText () != "310", "STAmount fail");
unexpected (STAmount (noIssue(), 31, -1).getText () != "3.1", "STAmount fail");
unexpected (STAmount (noIssue(), 31, -2).getText () != "0.31", "STAmount fail");
unexpected (multiply (STAmount (noIssue(), 20), STAmount (3), noIssue()).getText () != "60",
"STAmount multiply fail 1");
unexpected (multiply (STAmount (noIssue(), 20), STAmount (3), xrpIssue ()).getText () != "60",
"STAmount multiply fail 2");
unexpected (multiply (STAmount (20), STAmount (3), noIssue()).getText () != "60",
"STAmount multiply fail 3");
unexpected (multiply (STAmount (20), STAmount (3), xrpIssue ()).getText () != "60",
"STAmount multiply fail 4");
if (divide (STAmount (noIssue(), 60), STAmount (3), noIssue()).getText () != "20")
{
log << "60/3 = " <<
divide (STAmount (noIssue(), 60),
STAmount (3), noIssue()).getText ();
fail ("STAmount divide fail");
}
else
{
pass ();
}
unexpected (divide (STAmount (noIssue(), 60), STAmount (3), xrpIssue ()).getText () != "20",
"STAmount divide fail");
unexpected (divide (STAmount (noIssue(), 60), STAmount (noIssue(), 3), noIssue()).getText () != "20",
"STAmount divide fail");
unexpected (divide (STAmount (noIssue(), 60), STAmount (noIssue(), 3), xrpIssue ()).getText () != "20",
"STAmount divide fail");
STAmount a1 (noIssue(), 60), a2 (noIssue(), 10, -1);
unexpected (divide (a2, a1, noIssue()) != amountFromQuality (getRate (a1, a2)),
"STAmount setRate(getRate) fail");
unexpected (divide (a1, a2, noIssue()) != amountFromQuality (getRate (a2, a1)),
"STAmount setRate(getRate) fail");
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void testArithmetic ()
{
testcase ("arithmetic");
//ๆต่ฏ่ดงๅธ็ไนๆณๅ้คๆณ่ฟ็ฎ๏ผๅฆ
//convertToDisplayAmountใconvertToInternalAmountใgetRateใgetClaimedๅgetNeeded
unexpected (getRate (STAmount (1), STAmount (10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 1");
unexpected (getRate (STAmount (10), STAmount (1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 2");
unexpected (getRate (STAmount (noIssue(), 1), STAmount (noIssue(), 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 3");
unexpected (getRate (STAmount (noIssue(), 10), STAmount (noIssue(), 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 4");
unexpected (getRate (STAmount (noIssue(), 1), STAmount (10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 5");
unexpected (getRate (STAmount (noIssue(), 10), STAmount (1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 6");
unexpected (getRate (STAmount (1), STAmount (noIssue(), 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 7");
unexpected (getRate (STAmount (10), STAmount (noIssue(), 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull),
"STAmount getRate fail 8");
roundTest (1, 3, 3);
roundTest (2, 3, 9);
roundTest (1, 7, 21);
roundTest (1, 2, 4);
roundTest (3, 9, 18);
roundTest (7, 11, 44);
for (int i = 0; i <= 100000; ++i)
{
mulTest (
rand_int(10000000),
rand_int(10000000));
}
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void testUnderflow ()
{
testcase ("underflow");
STAmount bigNative (STAmount::cMaxNative / 2);
STAmount bigValue (noIssue(),
(STAmount::cMinValue + STAmount::cMaxValue) / 2,
STAmount::cMaxOffset - 1);
STAmount smallValue (noIssue(),
(STAmount::cMinValue + STAmount::cMaxValue) / 2,
STAmount::cMinOffset + 1);
STAmount zeroSt (noIssue(), 0);
STAmount smallXsmall = multiply (smallValue, smallValue, noIssue());
BEAST_EXPECT(smallXsmall == beast::zero);
STAmount bigDsmall = divide (smallValue, bigValue, noIssue());
BEAST_EXPECT(bigDsmall == beast::zero);
BEAST_EXPECT(bigDsmall == beast::zero);
bigDsmall = divide (smallValue, bigValue, xrpIssue ());
BEAST_EXPECT(bigDsmall == beast::zero);
bigDsmall = divide (smallValue, bigNative, xrpIssue ());
BEAST_EXPECT(bigDsmall == beast::zero);
//้ๅธธ็ณ็ณ็ๆฅไปท
std::uint64_t r = getRate (smallValue, bigValue);
BEAST_EXPECT(r == 0);
//ๅพๅฅฝ็ๆฅไปท
r = getRate (bigValue, smallValue);
BEAST_EXPECT(r == 0);
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void testRounding ()
{
//vfalc todo่ฟ้ๆฒกๆๅฎ้
ๆต่ฏ๏ผๅชๆฏๆๅฐ่พๅบ๏ผ
//ๆ่ฟไธชๆนๆๅฎ้
็ไบๆ
ใ
#if 0
beginTestCase ("rounding ");
std::uint64_t value = 25000000000000000ull;
int offset = -14;
canonicalizeRound (false, value, offset, true);
STAmount one (noIssue(), 1);
STAmount two (noIssue(), 2);
STAmount three (noIssue(), 3);
STAmount oneThird1 = divRound (one, three, noIssue(), false);
STAmount oneThird2 = divide (one, three, noIssue());
STAmount oneThird3 = divRound (one, three, noIssue(), true);
log << oneThird1;
log << oneThird2;
log << oneThird3;
STAmount twoThird1 = divRound (two, three, noIssue(), false);
STAmount twoThird2 = divide (two, three, noIssue());
STAmount twoThird3 = divRound (two, three, noIssue(), true);
log << twoThird1;
log << twoThird2;
log << twoThird3;
STAmount oneA = mulRound (oneThird1, three, noIssue(), false);
STAmount oneB = multiply (oneThird2, three, noIssue());
STAmount oneC = mulRound (oneThird3, three, noIssue(), true);
log << oneA;
log << oneB;
log << oneC;
STAmount fourThirdsB = twoThird2 + twoThird2;
log << fourThirdsA;
log << fourThirdsB;
log << fourThirdsC;
STAmount dripTest1 = mulRound (twoThird2, two, xrpIssue (), false);
STAmount dripTest2 = multiply (twoThird2, two, xrpIssue ());
STAmount dripTest3 = mulRound (twoThird2, two, xrpIssue (), true);
log << dripTest1;
log << dripTest2;
log << dripTest3;
#endif
}
void
testConvertXRP ()
{
testcase ("STAmount to XRPAmount conversions");
Issue const usd { Currency (0x5553440000000000), AccountID (0x4985601) };
Issue const xrp { xrpIssue () };
for (std::uint64_t drops = 100000000000000000; drops != 1; drops = drops / 10)
{
auto const t = amountFromString (xrp, std::to_string (drops));
auto const s = t.xrp ();
BEAST_EXPECT(s.drops() == drops);
BEAST_EXPECT(t == STAmount (XRPAmount (drops)));
BEAST_EXPECT(s == XRPAmount (drops));
}
try
{
auto const t = amountFromString (usd, "136500");
fail (to_string (t.xrp ()));
}
catch (std::logic_error const&)
{
pass ();
}
catch (std::exception const&)
{
fail ("wrong exception");
}
}
void
testConvertIOU ()
{
testcase ("STAmount to IOUAmount conversions");
Issue const usd { Currency (0x5553440000000000), AccountID (0x4985601) };
Issue const xrp { xrpIssue () };
for (std::uint64_t dollars = 10000000000; dollars != 1; dollars = dollars / 10)
{
auto const t = amountFromString (usd, std::to_string (dollars));
auto const s = t.iou ();
BEAST_EXPECT(t == STAmount (s, usd));
BEAST_EXPECT(s.mantissa () == t.mantissa ());
BEAST_EXPECT(s.exponent () == t.exponent ());
}
try
{
auto const t = amountFromString (xrp, "136500");
fail (to_string (t.iou ()));
}
catch (std::logic_error const&)
{
pass ();
}
catch (std::exception const&)
{
fail ("wrong exception");
}
}
//โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void run () override
{
testSetValue ();
testNativeCurrency ();
testCustomCurrency ();
testArithmetic ();
testUnderflow ();
testRounding ();
testConvertXRP ();
testConvertIOU ();
}
};
BEAST_DEFINE_TESTSUITE(STAmount,ripple_data,ripple);
} //ๆถๆผช
|
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.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:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <AK/ScopeGuard.h>
#include <AK/Time.h>
#include <Kernel/FileSystem/FileDescription.h>
#include <Kernel/Process.h>
//#define DEBUG_IO
//#define DEBUG_POLL_SELECT
namespace Kernel {
int Process::sys$select(const Syscall::SC_select_params* user_params)
{
REQUIRE_PROMISE(stdio);
Syscall::SC_select_params params;
SmapDisabler disabler;
if (!copy_from_user(¶ms, user_params))
return -EFAULT;
if (params.nfds < 0)
return -EINVAL;
timespec computed_timeout;
bool select_has_timeout = false;
if (params.timeout) {
timespec timeout_copy;
if (!copy_from_user(&timeout_copy, params.timeout))
return -EFAULT;
if (timeout_copy.tv_sec || timeout_copy.tv_nsec) {
timespec ts_since_boot;
timeval_to_timespec(Scheduler::time_since_boot(), ts_since_boot);
timespec_add(ts_since_boot, timeout_copy, computed_timeout);
select_has_timeout = true;
}
}
auto current_thread = Thread::current();
u32 previous_signal_mask = 0;
if (params.sigmask) {
sigset_t sigmask_copy;
if (!copy_from_user(&sigmask_copy, params.sigmask))
return -EFAULT;
previous_signal_mask = current_thread->update_signal_mask(sigmask_copy);
}
ScopeGuard rollback_signal_mask([&]() {
if (params.sigmask)
current_thread->update_signal_mask(previous_signal_mask);
});
Thread::SelectBlocker::FDVector rfds;
Thread::SelectBlocker::FDVector wfds;
Thread::SelectBlocker::FDVector efds;
auto transfer_fds = [&](auto* fds_unsafe, auto& vector) -> int {
vector.clear_with_capacity();
if (!fds_unsafe)
return 0;
fd_set fds;
if (!copy_from_user(&fds, fds_unsafe))
return -EFAULT;
for (int fd = 0; fd < params.nfds; ++fd) {
if (FD_ISSET(fd, &fds)) {
if (!file_description(fd)) {
dbg() << "sys$select: Bad fd number " << fd;
return -EBADF;
}
vector.append(fd);
}
}
return 0;
};
if (int error = transfer_fds(params.writefds, wfds))
return error;
if (int error = transfer_fds(params.readfds, rfds))
return error;
if (int error = transfer_fds(params.exceptfds, efds))
return error;
#if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
dbg() << "selecting on (read:" << rfds.size() << ", write:" << wfds.size() << "), timeout=" << params.timeout;
#endif
if (!params.timeout || select_has_timeout) {
if (current_thread->block<Thread::SelectBlocker>(select_has_timeout ? &computed_timeout : nullptr, rfds, wfds, efds).was_interrupted())
return -EINTR;
}
int marked_fd_count = 0;
auto mark_fds = [&](auto* fds_unsafe, auto& vector, auto should_mark) {
if (!fds_unsafe)
return 0;
fd_set fds;
FD_ZERO(&fds);
for (int fd : vector) {
if (auto description = file_description(fd); description && should_mark(*description)) {
FD_SET(fd, &fds);
++marked_fd_count;
}
}
if (!copy_to_user(fds_unsafe, &fds))
return -EFAULT;
return 0;
};
if (int error = mark_fds(params.readfds, rfds, [](auto& description) { return description.can_read(); }))
return error;
if (int error = mark_fds(params.writefds, wfds, [](auto& description) { return description.can_write(); }))
return error;
// FIXME: We should also mark exceptfds as appropriate.
return marked_fd_count;
}
int Process::sys$poll(Userspace<const Syscall::SC_poll_params*> user_params)
{
REQUIRE_PROMISE(stdio);
// FIXME: Return -EINVAL if timeout is invalid.
Syscall::SC_poll_params params;
if (!copy_from_user(¶ms, user_params))
return -EFAULT;
SmapDisabler disabler;
timespec timeout = {};
if (params.timeout && !copy_from_user(&timeout, params.timeout))
return -EFAULT;
sigset_t sigmask = {};
if (params.sigmask && !copy_from_user(&sigmask, params.sigmask))
return -EFAULT;
Vector<pollfd> fds_copy;
if (params.nfds > 0) {
Checked nfds_checked = sizeof(pollfd);
nfds_checked *= params.nfds;
if (nfds_checked.has_overflow())
return -EFAULT;
fds_copy.resize(params.nfds);
if (!copy_from_user(&fds_copy[0], ¶ms.fds[0], params.nfds * sizeof(pollfd)))
return -EFAULT;
}
Thread::SelectBlocker::FDVector rfds;
Thread::SelectBlocker::FDVector wfds;
for (unsigned i = 0; i < params.nfds; ++i) {
auto& pfd = fds_copy[i];
if (pfd.events & POLLIN)
rfds.append(pfd.fd);
if (pfd.events & POLLOUT)
wfds.append(pfd.fd);
}
timespec actual_timeout;
bool has_timeout = false;
if (params.timeout && (timeout.tv_sec || timeout.tv_nsec)) {
timespec ts_since_boot;
timeval_to_timespec(Scheduler::time_since_boot(), ts_since_boot);
timespec_add(ts_since_boot, timeout, actual_timeout);
has_timeout = true;
}
auto current_thread = Thread::current();
u32 previous_signal_mask = 0;
if (params.sigmask)
previous_signal_mask = current_thread->update_signal_mask(sigmask);
ScopeGuard rollback_signal_mask([&]() {
if (params.sigmask)
current_thread->update_signal_mask(previous_signal_mask);
});
#if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
dbg() << "polling on (read:" << rfds.size() << ", write:" << wfds.size() << "), timeout=" << timeout.tv_sec << "s" << timeout.tv_nsec << "ns";
#endif
if (!params.timeout || has_timeout) {
if (current_thread->block<Thread::SelectBlocker>(has_timeout ? &actual_timeout : nullptr, rfds, wfds, Thread::SelectBlocker::FDVector()).was_interrupted())
return -EINTR;
}
int fds_with_revents = 0;
for (unsigned i = 0; i < params.nfds; ++i) {
auto& pfd = fds_copy[i];
auto description = file_description(pfd.fd);
if (!description) {
pfd.revents = POLLNVAL;
} else {
pfd.revents = 0;
if (pfd.events & POLLIN && description->can_read())
pfd.revents |= POLLIN;
if (pfd.events & POLLOUT && description->can_write())
pfd.revents |= POLLOUT;
if (pfd.revents)
++fds_with_revents;
}
}
if (params.nfds > 0 && !copy_to_user(¶ms.fds[0], &fds_copy[0], params.nfds * sizeof(pollfd)))
return -EFAULT;
return fds_with_revents;
}
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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: Ioan Sucan */
#define BOOST_TEST_MODULE "Grid"
#include <boost/test/unit_test.hpp>
#include "ompl/datastructures/Grid.h"
#include "ompl/datastructures/GridN.h"
#include "../BoostTestTeamCityReporter.h"
using namespace ompl;
BOOST_AUTO_TEST_CASE(Grid_Simple)
{
Grid<int> g(2);
BOOST_CHECK_EQUAL((unsigned int)2, g.getDimension());
Grid<int>::Coord coord(2);
coord[0] = 1;
coord[1] = 0;
BOOST_CHECK_EQUAL(g.has(coord), false);
Grid<int>::Cell *cell1 = g.createCell(coord);
BOOST_CHECK(cell1 != nullptr);
cell1->data = 1;
g.add(cell1);
BOOST_CHECK(g.has(coord));
coord[1] = 1;
BOOST_CHECK_EQUAL(g.has(coord), false);
Grid<int>::Cell *cell2 = g.createCell(coord);
BOOST_CHECK(cell2 != nullptr);
cell2->data = 2;
g.add(cell2);
BOOST_CHECK(g.has(coord));
Grid<int>::CellArray ca;
g.neighbors(cell2, ca);
BOOST_CHECK_EQUAL((unsigned int)1, ca.size());
BOOST_CHECK_EQUAL(ca[0], cell1);
coord[0] = 0;
BOOST_CHECK_EQUAL(g.has(coord), false);
ca.clear();
g.neighbors(coord, ca);
BOOST_CHECK_EQUAL((unsigned int)1, ca.size());
BOOST_CHECK_EQUAL(ca[0], cell2);
Grid<int>::Cell *cell3 = g.createCell(coord);
BOOST_CHECK(cell3 != nullptr);
cell3->data = 3;
g.add(cell3);
BOOST_CHECK(g.has(coord));
BOOST_CHECK_EQUAL((unsigned int)3, g.size());
int sum = 0;
for (const auto & it : g)
sum += it.second->data;
BOOST_CHECK_EQUAL(6, sum);
g.remove(cell2);
g.destroyCell(cell2);
BOOST_CHECK_EQUAL((unsigned int)2, g.size());
sum = 0;
for (const auto & it : g)
sum += it.second->data;
BOOST_CHECK_EQUAL(4, sum);
}
BOOST_AUTO_TEST_CASE(GridN_Simple)
{
GridN<int> g(0);
g.setDimension(2);
BOOST_CHECK_EQUAL((unsigned int)2, g.getDimension());
GridN<int>::Coord coord(2);
coord[0] = 1;
coord[1] = 0;
BOOST_CHECK_EQUAL(g.has(coord), false);
GridN<int>::Cell *cell1 = dynamic_cast<GridN<int>::Cell*>(g.createCell(coord));
BOOST_CHECK(cell1 != nullptr);
BOOST_CHECK(cell1->neighbors == 0);
cell1->data = 1;
g.add(cell1);
BOOST_CHECK(g.has(coord));
coord[1] = 1;
BOOST_CHECK_EQUAL(g.has(coord), false);
GridN<int>::Cell *cell2 = dynamic_cast<GridN<int>::Cell*>(g.createCell(coord));
BOOST_CHECK(cell1->neighbors == 1);
BOOST_CHECK(cell2->neighbors == 1);
BOOST_CHECK(cell2 != nullptr);
cell2->data = 2;
g.add(cell2);
BOOST_CHECK(g.has(coord));
GridN<int>::CellArray ca;
g.neighbors(cell2, ca);
BOOST_CHECK_EQUAL((unsigned int)1, ca.size());
BOOST_CHECK_EQUAL(ca[0], cell1);
coord[0] = 0;
BOOST_CHECK_EQUAL(g.has(coord), false);
ca.clear();
g.neighbors(coord, ca);
BOOST_CHECK_EQUAL((unsigned int)1, ca.size());
BOOST_CHECK_EQUAL(ca[0], cell2);
GridN<int>::Cell *cell3 = dynamic_cast<GridN<int>::Cell*>(g.createCell(coord));
BOOST_CHECK(cell3 != nullptr);
BOOST_CHECK(cell1->neighbors == 1);
BOOST_CHECK(cell2->neighbors == 2);
BOOST_CHECK(cell3->neighbors == 1);
cell3->data = 3;
g.add(cell3);
BOOST_CHECK(g.has(coord));
BOOST_CHECK_EQUAL((unsigned int)3, g.size());
int sum = 0;
for (const auto & it : g)
sum += it.second->data;
BOOST_CHECK_EQUAL(6, sum);
coord[0] = 2;
GridN<int>::Cell *cell4 = dynamic_cast<GridN<int>::Cell*>(g.createCell(coord));
BOOST_CHECK(cell4 != nullptr);
cell4->data = 4;
g.add(cell4);
BOOST_CHECK(cell2->neighbors == 3);
BOOST_CHECK(cell2->border);
coord[0] = 1;
coord[1] = 2;
GridN<int>::Cell *cell5 = dynamic_cast<GridN<int>::Cell*>(g.createCell(coord));
BOOST_CHECK(cell5 != nullptr);
cell5->data = 5;
g.add(cell5);
BOOST_CHECK(cell2->neighbors == 4);
BOOST_CHECK_EQUAL(cell2->border, false);
BOOST_CHECK(cell1->border);
BOOST_CHECK(cell3->border);
BOOST_CHECK(cell4->border);
BOOST_CHECK(cell5->border);
BOOST_CHECK(g.getCell(cell5->coord) == cell5);
g.remove(cell1);
g.destroyCell(cell1);
BOOST_CHECK(cell2->border);
BOOST_CHECK_EQUAL((unsigned int)4, g.size());
sum = 0;
for (const auto & it : g)
sum += it.second->data;
BOOST_CHECK_EQUAL(14, sum);
BOOST_CHECK_EQUAL((unsigned int)1, g.components().size());
coord[0] = 10;
coord[1] = 2;
GridN<int>::Cell *cell6 = dynamic_cast<GridN<int>::Cell*>(g.createCell(coord));
g.add(cell6);
BOOST_CHECK_EQUAL((unsigned int)2, g.components().size());
BOOST_CHECK_EQUAL(g.components()[0].size() + g.components()[1].size(), g.size());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.