text
stringlengths 5
1.04M
|
|---|
/**
* \file RadPropsEvaluator.cc
* \date Jun 6, 2013
* \author "James C. Sutherland"
*
*
* The MIT License
*
* Copyright (c) 2013-2018 The University of Utah
*
* 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 "RadPropsEvaluator.h"
#include <radprops/Particles.h>
template< typename FieldT >
RadPropsEvaluator<FieldT>::
RadPropsEvaluator( const Expr::Tag& tempTag,
const RadSpecMap& species,
const std::string& fileName )
: Expr::Expression<FieldT>(),
greyGas_( new RadProps::GreyGas(fileName) )
{
this->set_gpu_runnable( true );
// obtain the list of species from the file:
Expr::TagList indepVarNames;
const std::vector<RadProps::RadiativeSpecies>& specOrder = greyGas_->species();
BOOST_FOREACH( const RadProps::RadiativeSpecies& sp, specOrder ){
const RadSpecMap::const_iterator isp = species.find(sp);
if( isp == species.end() ){
std::ostringstream msg;
msg << __FILE__ << " : " << __LINE__ << std::endl
<< "Species '" << species_name(sp) << "' was found in file " << fileName
<< " but no corresponding species was provided in the input file." << std::endl;
throw std::invalid_argument( msg.str() );
}
else{
indepVarNames.push_back( isp->second );
}
}
temp_ = this->template create_field_request<FieldT>(tempTag);
this->template create_field_vector_request<FieldT>(indepVarNames, indepVars_);
}
//--------------------------------------------------------------------
template< typename FieldT >
RadPropsEvaluator<FieldT>::
~RadPropsEvaluator()
{
delete greyGas_;
}
//--------------------------------------------------------------------
template< typename FieldT >
void
RadPropsEvaluator<FieldT>::
evaluate()
{
FieldT& result = this->value();
# ifdef HAVE_CUDA
std::vector<const double *> molefracs( indepVars_.size(), NULL );
for( size_t i=0; i<indepVars_.size(); ++i ){
molefracs[i] = indepVars_[i]->field_ref().field_values(GPU_INDEX);
}
greyGas_->gpu_mixture_coeffs(result.field_values(GPU_INDEX), molefracs, temp_->field_ref().field_values(GPU_INDEX), result.window_with_ghost().glob_npts(), RadProps::EFF_ABS_COEFF);
# else
typedef typename FieldT::const_iterator Iterator;
typedef std::vector<Iterator> IVarIter;
IVarIter ivarIters;
for( size_t i=0; i<indepVars_.size(); ++i ){
const FieldT iVar = indepVars_[i]->field_ref();
ivarIters.push_back(iVar.begin());
}
std::vector<double> ivarsPoint( indepVars_.size(), 0.0 );
const FieldT& temp = temp_->field_ref();
// loop over grid points. iii is a dummy variable.
Iterator itemp=temp.begin();
for( typename FieldT::iterator iprop=result.begin(); iprop!=result.end(); ++iprop, ++itemp ){
// extract indep vars at this grid point
ivarsPoint.clear();
for( typename IVarIter::iterator i=ivarIters.begin(); i!=ivarIters.end(); ++i ){
ivarsPoint.push_back( **i );
++(*i);
}
// for now, we only pull out the effective radiative coefficient
greyGas_->mixture_coeffs( *iprop, ivarsPoint, *itemp, RadProps::EFF_ABS_COEFF );
}
# endif // HAVE_CUDA
}
//--------------------------------------------------------------------
template< typename FieldT >
RadPropsEvaluator<FieldT>::
Builder::Builder( const Expr::Tag& resultTag,
const Expr::Tag& tempTag,
const RadSpecMap& species,
const std::string& fileName )
: ExpressionBuilder( resultTag ),
rsm_( species ),
tempTag_( tempTag ),
fileName_( fileName )
{}
//--------------------------------------------------------------------
template< typename FieldT >
Expr::ExpressionBase*
RadPropsEvaluator<FieldT>::
Builder::build() const
{
return new RadPropsEvaluator<FieldT>( tempTag_, rsm_, fileName_ );
}
//==========================================================================
template< typename FieldT >
ParticleRadProps<FieldT>::
ParticleRadProps( const ParticleRadProp prop,
const Expr::Tag& tempTag,
const Expr::Tag& pRadiusTag,
const std::complex<double>& refIndex )
: Expr::Expression<FieldT>(),
props_( new RadProps::ParticleRadCoeffs(refIndex,
1e-7, /// min particle size
1e-4, // max particle size
10, // number of sizes
1 ) ), // order of interpolant
prop_( prop )
{
temp_ = this->template create_field_request<FieldT>(tempTag );
pRadius_ = this->template create_field_request<FieldT>(pRadiusTag);
}
//--------------------------------------------------------------------
template< typename FieldT >
ParticleRadProps<FieldT>::
~ParticleRadProps()
{}
//--------------------------------------------------------------------
template< typename FieldT >
void
ParticleRadProps<FieldT>::
evaluate()
{
FieldT& result = this->value();
typedef typename FieldT::const_iterator Iterator;
const FieldT& temp = temp_->field_ref();
const FieldT& pRadius = pRadius_->field_ref();
Iterator itemp=temp.begin(), irad = pRadius.begin();
const Iterator ite=temp.end();
for( typename FieldT::iterator iprop=result.begin(); itemp!=ite; ++iprop, ++itemp, ++irad ){
switch( prop_ ){
case PLANCK_ABSORPTION_COEFF : *iprop = props_->planck_abs_coeff( *irad, *itemp ); break;
case PLANCK_SCATTERING_COEFF : *iprop = props_->planck_sca_coeff( *irad, *itemp ); break;
case ROSSELAND_ABSORPTION_COEFF: *iprop = props_->ross_abs_coeff ( *irad, *itemp ); break;
case ROSSELAND_SCATTERING_COEFF: *iprop = props_->ross_sca_coeff ( *irad, *itemp ); break;
}
}
}
//--------------------------------------------------------------------
template< typename FieldT >
ParticleRadProps<FieldT>::
Builder::Builder( const ParticleRadProp prop,
const Expr::Tag& resultTag,
const Expr::Tag& tempTag,
const Expr::Tag& pRadiusTag,
const std::complex<double> refIndex )
: ExpressionBuilder( resultTag ),
prop_( prop ),
tempTag_( tempTag ),
pRadiusTag_( pRadiusTag ),
refIndex_( refIndex )
{}
//--------------------------------------------------------------------
template< typename FieldT >
Expr::ExpressionBase*
ParticleRadProps<FieldT>::
Builder::build() const
{
return new ParticleRadProps<FieldT>( prop_, tempTag_, pRadiusTag_, refIndex_ );
}
//==========================================================================
// Explicit template instantiation for supported versions of this expression
#include <spatialops/structured/FVStaggered.h>
template class RadPropsEvaluator<SpatialOps::SVolField>;
template class ParticleRadProps <SpatialOps::SVolField>;
//==========================================================================
|
#include "point_cat.h"
void point_cat_forward_kernel(at::Tensor in_features, at::Tensor key, int n_cat,
at::Tensor out_features);
at::Tensor point_cat_forward(at::Tensor in_features, at::Tensor key,
int n_cat) {
CHECK_INPUT_CUDA_DIM(in_features, 2);
const int64_t channels = in_features.size(1);
CHECK_INPUT_CUDA_DIM(key, 1);
const int64_t prefix_sum = key.size(0);
auto out_features =
torch::zeros({prefix_sum - 1, n_cat * channels},
torch::TensorOptions()
.dtype(in_features.dtype())
.device(in_features.device().type())
.requires_grad(in_features.requires_grad()));
point_cat_forward_kernel(in_features, key, n_cat, out_features);
return out_features;
}
void point_cat_backward_kernel(at::Tensor grad_out_features, at::Tensor key,
int n_cat, at::Tensor grad_in_features);
at::Tensor point_cat_backward(at::Tensor grad_out_features, at::Tensor key,
int n_cat, int nelems) {
CHECK_INPUT_CUDA_DIM(grad_out_features, 2);
const int64_t prefix_sum = grad_out_features.size(0) + 1;
const int64_t channels = grad_out_features.size(1) / n_cat;
CHECK_INPUT_CUDA_DIM(key, 1);
AT_ASSERTM(key.size(0) == 1 * prefix_sum,
"prefix_sum of key does not match");
auto grad_in_features =
torch::zeros({nelems, channels},
torch::TensorOptions()
.dtype(grad_out_features.dtype())
.device(grad_out_features.device().type())
.requires_grad(grad_out_features.requires_grad()));
point_cat_backward_kernel(grad_out_features, key, n_cat, grad_in_features);
return grad_in_features;
}
void point_cat_pybind_init(py::module& m) {
m.def("point_cat_forward", &point_cat_forward);
m.def("point_cat_backward", &point_cat_backward);
}
|
/**
* Copyright (C) 2016 Turi
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <iostream>
#include <string>
#include <sstream>
#include <thread>
int main(int argc, char **argv) {
std::stringstream ss;
ss << "Hello world! ";
for(int i = 0; i < argc; ++i) {
ss << argv[i];
ss << " ";
}
std::cout << ss.str();
//std::cerr << "ERRORS AND STUFF!!!";
return 0;
}
|
#include <PnC/DracoPnC/TestSet/TestSet.hpp>
#include <PnC/DracoPnC/CtrlSet/CtrlSet.hpp>
#include <PnC/RobotSystem/RobotSystem.hpp>
#include <PnC/DracoPnC/DracoStateProvider.hpp>
DCMWalkTest::DCMWalkTest(RobotSystem* robot) : Test(robot) {
myUtils::pretty_constructor(1, "DCM Walk Test");
cfg_ = YAML::LoadFile(THIS_COM"Config/Draco/TEST/DCM_WALK_TEST.yaml");
phase_ = DCMWalkTestPhase::DCMWalkTestPhase_initial_jpos;
// phase_ = DCMWalkTestPhase::DCMWalkTestPhase_force_ctrl;
state_list_.clear();
jpos_target_ctrl_ = new IVDJPosTargetCtrl(robot);
dcm_stand_ctrl_ = new DCMStandCtrl(robot);
dcm_balance_ctrl_ = new DCMBalanceCtrl(robot);
dcm_ctrl_ = new DCMWalkCtrl(robot);
state_list_.push_back(jpos_target_ctrl_);
state_list_.push_back(dcm_stand_ctrl_);
state_list_.push_back(dcm_ctrl_);
state_list_.push_back(dcm_balance_ctrl_);
repeat_counter_ = 1;
repeat_times_ = 1;
sp_ = DracoStateProvider::getStateProvider(robot_);
_SettingParameter();
}
DCMWalkTest::~DCMWalkTest() {
for(int i(0); i<state_list_.size(); ++i){
delete state_list_[i];
}
}
void DCMWalkTest::TestInitialization() {
jpos_target_ctrl_->ctrlInitialization(cfg_["control_configuration"]["joint_position_ctrl"]);
dcm_ctrl_->ctrlInitialization(cfg_["control_configuration"]["dcm_ctrl"]);
dcm_stand_ctrl_->ctrlInitialization(cfg_["control_configuration"]["dcm_ctrl"]);
dcm_balance_ctrl_->ctrlInitialization(cfg_["control_configuration"]["dcm_ctrl"]);
}
int DCMWalkTest::_NextPhase(const int & phase) {
int next_phase = phase + 1;
printf("next phase: %i\n", next_phase);
if ((next_phase == DCMWalkTestPhase_balance_ctrl) && (repeat_counter_ < repeat_times_)) {
repeat_counter_++;
return DCMWalkTestPhase::DCMWalkTestPhase_walk_ctrl;
}
if (next_phase == NUM_DCMWalkTestPhase) {
return DCMWalkTestPhase::DCMWalkTestPhase_balance_ctrl;
}
else return next_phase;
}
void DCMWalkTest::_SettingParameter() {
try {
YAML::Node test_cfg = cfg_["test_configuration"];
Eigen::VectorXd tmp_vec;
double tmp_val;
myUtils::readParameter(test_cfg, "initial_jpos", tmp_vec);
((IVDJPosTargetCtrl*)jpos_target_ctrl_)->setTargetPosition(tmp_vec);
myUtils::readParameter(test_cfg, "jpos_initialization_time", tmp_val);
((IVDJPosTargetCtrl*)jpos_target_ctrl_)->setMovingTime(tmp_val);
myUtils::readParameter(test_cfg, "jpos_ctrl_time", tmp_val);
((IVDJPosTargetCtrl*)jpos_target_ctrl_)->setTotalCtrlTime(tmp_val);
myUtils::readParameter(test_cfg, "com_height", tmp_val);
((DCMWalkCtrl*)dcm_ctrl_)->setCoMHeight(tmp_val);
((DCMStandCtrl*)dcm_stand_ctrl_)->setCoMHeight(tmp_val);
((DCMBalanceCtrl*)dcm_balance_ctrl_)->setCoMHeight(tmp_val);
sp_-> omega = sqrt(9.81/tmp_val);
myUtils::readParameter(test_cfg, "contact_transition_duration", tmp_val);
((DCMWalkCtrl*)dcm_ctrl_)->setContactTransitionTime(tmp_val);
((DCMStandCtrl*)dcm_stand_ctrl_)->setContactTransitionTime(tmp_val);
((DCMBalanceCtrl*)dcm_balance_ctrl_)->setContactTransitionTime(tmp_val);
myUtils::readParameter(test_cfg, "stabilization_duration", tmp_val);
((DCMWalkCtrl*)dcm_ctrl_)->SetStabilizationDuration(tmp_val);
((DCMStandCtrl*)dcm_stand_ctrl_)->SetStabilizationDuration(tmp_val);
((DCMBalanceCtrl*)dcm_balance_ctrl_)->SetStabilizationDuration(tmp_val);
myUtils::readParameter(test_cfg, "com_ctrl_time", tmp_val);
((DCMWalkCtrl*)dcm_ctrl_)->setStanceTime(tmp_val);
((DCMStandCtrl*)dcm_stand_ctrl_)->setStanceTime(tmp_val);
((DCMBalanceCtrl*)dcm_balance_ctrl_)->setStanceTime(tmp_val);
myUtils::readParameter(test_cfg, "walk_start_time", tmp_val);
((DCMWalkCtrl*)dcm_ctrl_)->setWalkStartTime(tmp_val);
((DCMStandCtrl*)dcm_stand_ctrl_)->setWalkStartTime(tmp_val);
((DCMBalanceCtrl*)dcm_balance_ctrl_)->setWalkStartTime(tmp_val);
} catch(std::runtime_error& e) {
std::cout << "Error reading parameter ["<< e.what() << "] at file: [" << __FILE__ << "]" << std::endl << std::endl;
exit(0);
}
}
|
// Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP__CLOCK_HPP_
#define RCLCPP__CLOCK_HPP_
#include <functional>
#include <memory>
#include <mutex>
#include "rclcpp/contexts/default_context.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp/visibility_control.hpp"
#include "rcl/time.h"
#include "rcutils/time.h"
#include "rcutils/types/rcutils_ret.h"
namespace rclcpp
{
class TimeSource;
class JumpHandler
{
public:
RCLCPP_SMART_PTR_DEFINITIONS(JumpHandler)
using pre_callback_t = std::function<void ()>;
using post_callback_t = std::function<void (const rcl_time_jump_t &)>;
JumpHandler(
pre_callback_t pre_callback,
post_callback_t post_callback,
const rcl_jump_threshold_t & threshold);
pre_callback_t pre_callback;
post_callback_t post_callback;
rcl_jump_threshold_t notice_threshold;
};
class Clock
{
public:
RCLCPP_SMART_PTR_DEFINITIONS(Clock)
/// Default c'tor
/**
* Initializes the clock instance with the given clock_type.
*
* \param clock_type type of the clock.
* \throws anything rclcpp::exceptions::throw_from_rcl_error can throw.
*/
RCLCPP_PUBLIC
explicit Clock(rcl_clock_type_t clock_type = RCL_SYSTEM_TIME);
RCLCPP_PUBLIC
~Clock();
/**
* Returns current time from the time source specified by clock_type.
*
* \return current time.
* \throws anything rclcpp::exceptions::throw_from_rcl_error can throw.
*/
RCLCPP_PUBLIC
Time
now();
/**
* Sleep until a specified Time, according to clock type.
*
* Notes for RCL_ROS_TIME clock type:
* - Can sleep forever if ros time is active and received clock never reaches `until`
* - If ROS time enabled state changes during the sleep, this method will immediately return
* false. There is not a consistent choice of sleeping time when the time source changes,
* so this is up to the caller to call again if needed.
*
* \param until absolute time according to current clock type to sleep until.
* \param context the rclcpp context the clock should use to check that ROS is still initialized.
* \return true immediately if `until` is in the past
* \return true when the time `until` is reached
* \return false if time cannot be reached reliably, for example from shutdown or a change
* of time source.
* \throws std::runtime_error if the context is invalid
* \throws std::runtime_error if `until` has a different clock type from this clock
*/
RCLCPP_PUBLIC
bool
sleep_until(
Time until,
Context::SharedPtr context = contexts::get_global_default_context());
/**
* Returns the clock of the type `RCL_ROS_TIME` is active.
*
* \return true if the clock is active
* \throws anything rclcpp::exceptions::throw_from_rcl_error can throw if
* the current clock does not have the clock_type `RCL_ROS_TIME`.
*/
RCLCPP_PUBLIC
bool
ros_time_is_active();
/// Return the rcl_clock_t clock handle
RCLCPP_PUBLIC
rcl_clock_t *
get_clock_handle() noexcept;
RCLCPP_PUBLIC
rcl_clock_type_t
get_clock_type() const noexcept;
/// Get the clock's mutex
RCLCPP_PUBLIC
std::mutex &
get_clock_mutex() noexcept;
// Add a callback to invoke if the jump threshold is exceeded.
/**
* These callback functions must remain valid as long as the
* returned shared pointer is valid.
*
* Function will register callbacks to the callback queue. On time jump all
* callbacks will be executed whose threshold is greater then the time jump;
* The logic will first call selected pre_callbacks and then all selected
* post_callbacks.
*
* Function is only applicable if the clock_type is `RCL_ROS_TIME`
*
* \param pre_callback Must be non-throwing
* \param post_callback Must be non-throwing.
* \param threshold Callbacks will be triggered if the time jump is greater
* then the threshold.
* \throws anything rclcpp::exceptions::throw_from_rcl_error can throw.
* \throws std::bad_alloc if the allocation of the JumpHandler fails.
* \warning the instance of the clock must remain valid as long as any created
* JumpHandler.
*/
RCLCPP_PUBLIC
JumpHandler::SharedPtr
create_jump_callback(
JumpHandler::pre_callback_t pre_callback,
JumpHandler::post_callback_t post_callback,
const rcl_jump_threshold_t & threshold);
private:
// Invoke time jump callback
RCLCPP_PUBLIC
static void
on_time_jump(
const rcl_time_jump_t * time_jump,
bool before_jump,
void * user_data);
/// Private internal storage
class Impl;
std::shared_ptr<Impl> impl_;
};
} // namespace rclcpp
#endif // RCLCPP__CLOCK_HPP_
|
/**
* @file oivs_init.hpp
* @author Marcus Edel
*
* Definition and implementation of the Optimal Initial Value Setting method
* (OIVS). This initialization rule is based on geometrical considerations as
* described by H. Shimodaira.
*
* For more information, see the following paper.
*
* @code
* @inproceedings{ShimodairaICTAI1994,
* title={A weight value initialization method for improving learning
* performance of the backpropagation algorithm in neural networks},
* author={Shimodaira, H.},
* booktitle={Tools with Artificial Intelligence, 1994. Proceedings.,
* Sixth International Conference on},
* year={1994}
* }
* @endcode
*/
#ifndef __MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP
#define __MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>
#include "random_init.hpp"
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* This class is used to initialize the weight matrix with the oivs method. The
* method is based on the equations representing the characteristics of the
* information transformation mechanism of a node. The method is defined by
*
* @f{eqnarray*}{
* b &=& |F^{-1}(1 - \epsilon) - f^{-1}(\epsilon)| \\
* \hat{w} &=& \frac{b}{k \cdot n} \\
* \gamma &\le& a_i \le \gamma \\
* w_i &=& \hat{w} \cdot \sqrt{a_i + 1}
* @f}
*
* Where f is the transfer function epsilon, k custom parameters, n the number of
* neurons in the outgoing layer and gamma a parameter that defines the random
* interval.
*
* @tparam ActivationFunction The activation function used for the oivs method.
*/
template<
class ActivationFunction = LogisticFunction
>
class OivsInitialization
{
public:
/**
* Initialize the random initialization rule with the given values.
*
* @param epsilon Parameter to control the activation region.
* @param k Parameter to control the activation region width.
* @param gamma Parameter to define the uniform random range.
*/
OivsInitialization(const double epsilon = 0.1,
const int k = 5,
const double gamma = 0.9) :
epsilon(epsilon), k(k), gamma(gamma)
{
double b = std::abs(ActivationFunction::inv(1 - epsilon) -
ActivationFunction::inv(epsilon));
}
/**
* Initialize the elements of the specified weight matrix with the oivs method.
*
* @param W Weight matrix to initialize.
* @param rows Number of rows.
* @param cols Number of columns.
*/
template<typename eT>
void Initialize(arma::Mat<eT>& W, const size_t rows, const size_t cols)
{
RandomInitialization randomInit(-gamma, gamma);
randomInit.Initialize(W, rows, cols);
W = (b / (k * rows)) * arma::sqrt(W + 1);
}
/**
* Initialize the elements of the specified weight 3rd order tensor with the
* oivs method.
*
* @param W 3rd order tensor to initialize.
* @param rows Number of rows.
* @param cols Number of columns.
* @param slices Number of slices.
*/
template<typename eT>
void Initialize(arma::Cube<eT>& W,
const size_t rows,
const size_t cols,
const size_t slices)
{
W = arma::Cube<eT>(rows, cols, slices);
for (size_t i = 0; i < slices; i++)
Initialize(W.slice(i), rows, cols);
}
private:
//! Parameter to control the activation region.
const double b;
//! Parameter to control the activation region width.
const int k;
//! Parameter to define the uniform random range.
const double gamma;
}; // class OivsInitialization
}; // namespace ann
}; // namespace mlpack
#endif
|
#include "Tweener.h"
#define LOCTEXT_NAMESPACE "FTweenerModule"
void FTweenerModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
}
void FTweenerModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FTweenerModule, Tweener)
|
#include <assert.h>
#include <stdexcept>
#include <string>
#include <vector>
#include <llvm-abi/ABI.hpp>
#include <llvm-abi/ABITypeInfo.hpp>
#include <llvm-abi/Type.hpp>
#include <llvm-abi/TypeBuilder.hpp>
#include <locic/CodeGen/ArgInfo.hpp>
#include <locic/CodeGen/ConstantGenerator.hpp>
#include <locic/CodeGen/Debug.hpp>
#include <locic/CodeGen/Function.hpp>
#include <locic/CodeGen/FunctionCallInfo.hpp>
#include <locic/CodeGen/GenABIType.hpp>
#include <locic/CodeGen/GenVTable.hpp>
#include <locic/CodeGen/Interface.hpp>
#include <locic/CodeGen/InternalContext.hpp>
#include <locic/CodeGen/IREmitter.hpp>
#include <locic/CodeGen/Module.hpp>
#include <locic/CodeGen/Primitive.hpp>
#include <locic/CodeGen/Primitives.hpp>
#include <locic/CodeGen/Primitives/PtrPrimitive.hpp>
#include <locic/CodeGen/Routines.hpp>
#include <locic/CodeGen/SizeOf.hpp>
#include <locic/CodeGen/Support.hpp>
#include <locic/CodeGen/Template.hpp>
#include <locic/CodeGen/TypeGenerator.hpp>
#include <locic/CodeGen/TypeInfo.hpp>
#include <locic/CodeGen/UnwindAction.hpp>
#include <locic/CodeGen/VTable.hpp>
#include <locic/Support/MethodID.hpp>
namespace locic {
namespace CodeGen {
PtrPrimitive::PtrPrimitive(const AST::TypeInstance& typeInstance)
: typeInstance_(typeInstance) {
(void) typeInstance_;
}
bool PtrPrimitive::isSizeAlwaysKnown(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return true;
}
bool PtrPrimitive::isSizeKnownInThisModule(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return true;
}
bool PtrPrimitive::hasCustomDestructor(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return false;
}
bool PtrPrimitive::hasCustomMove(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return false;
}
llvm_abi::Type PtrPrimitive::getABIType(Module& /*module*/,
const llvm_abi::TypeBuilder& /*abiTypeBuilder*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return llvm_abi::PointerTy;
}
llvm::Value* PtrPrimitive::emitMethod(IREmitter& irEmitter,
const MethodID methodID,
llvm::ArrayRef<AST::Value> typeTemplateArguments,
llvm::ArrayRef<AST::Value> /*functionTemplateArguments*/,
PendingResultArray args,
llvm::Value* /*resultPtr*/) const {
auto& builder = irEmitter.builder();
auto& function = irEmitter.function();
auto& module = irEmitter.module();
const auto targetType = typeTemplateArguments.front().typeRefType();
const auto methodOwnerPointer = methodID.isConstructor() ? nullptr : args[0].resolve(function);
const auto methodOwner = methodOwnerPointer != nullptr ?
irEmitter.emitRawLoad(methodOwnerPointer, llvm_abi::PointerTy) :
nullptr;
switch (methodID) {
case METHOD_NULL: {
return ConstantGenerator(module).getNullPointer();
}
case METHOD_ALIGNMASK: {
const auto abiType = this->getABIType(module,
module.abiTypeBuilder(),
typeTemplateArguments);
return ConstantGenerator(module).getSizeTValue(module.abi().typeInfo().getTypeRequiredAlign(abiType).asBytes() - 1);
}
case METHOD_SIZEOF: {
const auto abiType = this->getABIType(module,
module.abiTypeBuilder(),
typeTemplateArguments);
return ConstantGenerator(module).getSizeTValue(module.abi().typeInfo().getTypeAllocSize(abiType).asBytes());
}
case METHOD_COPY:
case METHOD_IMPLICITCOPY:
case METHOD_MOVE:
case METHOD_DEREF:
return methodOwner;
case METHOD_DESTROY:
case METHOD_SETDEAD: {
// Do nothing.
return ConstantGenerator(module).getVoidUndef();
}
case METHOD_INCREMENT: {
TypeInfo typeInfo(module);
if (typeInfo.isSizeKnownInThisModule(targetType)) {
const auto one = ConstantGenerator(module).getI32(1);
const auto newPointer = irEmitter.emitInBoundsGEP(genABIType(module, targetType),
methodOwner,
one);
irEmitter.emitRawStore(newPointer, methodOwnerPointer);
} else {
const auto targetSize = genSizeOf(function, targetType);
const auto newPointer = irEmitter.emitInBoundsGEP(llvm_abi::Int8Ty,
methodOwner,
targetSize);
irEmitter.emitRawStore(newPointer, methodOwnerPointer);
}
return ConstantGenerator(module).getVoidUndef();
}
case METHOD_DECREMENT: {
TypeInfo typeInfo(module);
if (typeInfo.isSizeKnownInThisModule(targetType)) {
const auto minusOne = ConstantGenerator(module).getI32(-1);
const auto newPointer = irEmitter.emitInBoundsGEP(genABIType(module, targetType),
methodOwner,
minusOne);
irEmitter.emitRawStore(newPointer, methodOwnerPointer);
} else {
const auto targetSize = genSizeOf(function, targetType);
const auto minusTargetSize = builder.CreateNeg(targetSize);
const auto newPointer = irEmitter.emitInBoundsGEP(llvm_abi::Int8Ty,
methodOwner,
minusTargetSize);
irEmitter.emitRawStore(newPointer, methodOwnerPointer);
}
return ConstantGenerator(module).getVoidUndef();
}
case METHOD_ADD: {
const auto operand = args[1].resolveWithoutBind(function);
TypeInfo typeInfo(module);
if (typeInfo.isSizeKnownInThisModule(targetType)) {
return irEmitter.emitInBoundsGEP(genABIType(module, targetType),
methodOwner,
operand);
} else {
const auto targetSize = genSizeOf(function, targetType);
const auto adjustedOffset = builder.CreateMul(operand, targetSize);
return irEmitter.emitInBoundsGEP(llvm_abi::Int8Ty,
methodOwner,
adjustedOffset);
}
}
case METHOD_SUBTRACT: {
// TODO: should be intptr_t!
const auto ptrDiffTType = module.getLLVMType(llvm_abi::PtrDiffTy);
const auto operand = args[1].resolveWithoutBind(function);
const auto firstPtrInt = builder.CreatePtrToInt(methodOwner, ptrDiffTType);
const auto secondPtrInt = builder.CreatePtrToInt(operand, ptrDiffTType);
return builder.CreateSub(firstPtrInt, secondPtrInt);
}
case METHOD_INDEX: {
const auto sizeTType = module.getLLVMType(llvm_abi::SizeTy);
const auto operand = args[1].resolve(function);
TypeInfo typeInfo(module);
if (typeInfo.isSizeKnownInThisModule(targetType)) {
return irEmitter.emitInBoundsGEP(genABIType(module, targetType),
methodOwner,
operand);
} else {
const auto targetSize = genSizeOf(function, targetType);
const auto offset = builder.CreateIntCast(operand, sizeTType, true);
const auto adjustedOffset = builder.CreateMul(offset, targetSize);
return irEmitter.emitInBoundsGEP(llvm_abi::Int8Ty,
methodOwner,
adjustedOffset);
}
}
case METHOD_EQUAL: {
const auto operand = args[1].resolveWithoutBind(function);
return irEmitter.emitI1ToBool(builder.CreateICmpEQ(methodOwner, operand));
}
case METHOD_NOTEQUAL: {
const auto operand = args[1].resolveWithoutBind(function);
return irEmitter.emitI1ToBool(builder.CreateICmpNE(methodOwner, operand));
}
case METHOD_LESSTHAN: {
const auto operand = args[1].resolveWithoutBind(function);
return irEmitter.emitI1ToBool(builder.CreateICmpULT(methodOwner, operand));
}
case METHOD_LESSTHANOREQUAL: {
const auto operand = args[1].resolveWithoutBind(function);
return irEmitter.emitI1ToBool(builder.CreateICmpULE(methodOwner, operand));
}
case METHOD_GREATERTHAN: {
const auto operand = args[1].resolveWithoutBind(function);
return irEmitter.emitI1ToBool(builder.CreateICmpUGT(methodOwner, operand));
}
case METHOD_GREATERTHANOREQUAL: {
const auto operand = args[1].resolveWithoutBind(function);
return irEmitter.emitI1ToBool(builder.CreateICmpUGE(methodOwner, operand));
}
case METHOD_COMPARE: {
const auto operand = args[1].resolveWithoutBind(function);
const auto isLessThan = builder.CreateICmpULT(methodOwner, operand);
const auto isGreaterThan = builder.CreateICmpUGT(methodOwner, operand);
const auto minusOneResult = ConstantGenerator(module).getI8(-1);
const auto zeroResult = ConstantGenerator(module).getI8(0);
const auto plusOneResult = ConstantGenerator(module).getI8(1);
return builder.CreateSelect(isLessThan, minusOneResult,
builder.CreateSelect(isGreaterThan, plusOneResult, zeroResult));
}
default:
llvm_unreachable("Unknown ptr primitive method.");
}
}
}
}
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* 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 itkLineCell_hxx
#define itkLineCell_hxx
namespace itk
{
/**
* Standard CellInterface:
*/
template <typename TCellInterface>
void
LineCell<TCellInterface>::MakeCopy(CellAutoPointer & cellPointer) const
{
cellPointer.TakeOwnership(new Self);
cellPointer->SetPointIds(this->GetPointIds());
}
/**
* Standard CellInterface:
* Get the topological dimension of this cell.
*/
template <typename TCellInterface>
unsigned int
LineCell<TCellInterface>::GetDimension() const
{
return Self::CellDimension;
}
/**
* Standard CellInterface:
* Get the number of points required to define the cell.
*/
template <typename TCellInterface>
unsigned int
LineCell<TCellInterface>::GetNumberOfPoints() const
{
return Self::NumberOfPoints;
}
/**
* Standard CellInterface:
* Get the number of boundary entities of the given dimension.
*/
template <typename TCellInterface>
auto
LineCell<TCellInterface>::GetNumberOfBoundaryFeatures(int dimension) const -> CellFeatureCount
{
switch (dimension)
{
case 0:
return GetNumberOfVertices();
default:
return 0;
}
}
/**
* Standard CellInterface:
* Get the boundary feature of the given dimension specified by the given
* cell feature Id.
* The Id can range from 0 to GetNumberOfBoundaryFeatures(dimension)-1.
*/
template <typename TCellInterface>
bool
LineCell<TCellInterface>::GetBoundaryFeature(int dimension,
CellFeatureIdentifier featureId,
CellAutoPointer & cellPointer)
{
VertexAutoPointer vertexPointer;
if ((dimension == 0) && this->GetVertex(featureId, vertexPointer))
{
TransferAutoPointer(cellPointer, vertexPointer);
return true;
}
/* else */
cellPointer.Reset();
return false;
}
/**
* Standard CellInterface:
* Set the point id list used by the cell. It is assumed that the given
* iterator can be incremented and safely de-referenced enough times to
* get all the point ids needed by the cell.
*/
template <typename TCellInterface>
void
LineCell<TCellInterface>::SetPointIds(PointIdConstIterator first)
{
PointIdConstIterator ii(first);
for (unsigned int i = 0; i < Self::NumberOfPoints; ++i)
{
m_PointIds[i] = *ii++;
}
}
/**
* Standard CellInterface:
* Set the point id list used by the cell. It is assumed that the range
* of iterators [first, last) contains the correct number of points needed to
* define the cell. The position *last is NOT referenced, so it can safely
* be one beyond the end of an array or other container.
*/
template <typename TCellInterface>
void
LineCell<TCellInterface>::SetPointIds(PointIdConstIterator first, PointIdConstIterator last)
{
int localId = 0;
PointIdConstIterator ii(first);
while (ii != last)
{
m_PointIds[localId++] = *ii++;
}
}
/**
* Standard CellInterface:
* Set an individual point identifier in the cell.
*/
template <typename TCellInterface>
void
LineCell<TCellInterface>::SetPointId(int localId, PointIdentifier ptId)
{
m_PointIds[localId] = ptId;
}
/**
* Standard CellInterface:
* Get a begin iterator to the list of point identifiers used by the cell.
*/
template <typename TCellInterface>
auto
LineCell<TCellInterface>::PointIdsBegin() -> PointIdIterator
{
return &m_PointIds[0];
}
/**
* Standard CellInterface:
* Get a const begin iterator to the list of point identifiers used
* by the cell.
*/
template <typename TCellInterface>
auto
LineCell<TCellInterface>::PointIdsBegin() const -> PointIdConstIterator
{
return &m_PointIds[0];
}
/**
* Standard CellInterface:
* Get an end iterator to the list of point identifiers used by the cell.
*/
template <typename TCellInterface>
auto
LineCell<TCellInterface>::PointIdsEnd() -> PointIdIterator
{
return &m_PointIds[Self::NumberOfPoints - 1] + 1;
}
/**
* Standard CellInterface:
* Get a const end iterator to the list of point identifiers used
* by the cell.
*/
template <typename TCellInterface>
auto
LineCell<TCellInterface>::PointIdsEnd() const -> PointIdConstIterator
{
return &m_PointIds[Self::NumberOfPoints - 1] + 1;
}
/**
* Line-specific:
* Get the number of vertices for this line.
*/
template <typename TCellInterface>
auto
LineCell<TCellInterface>::GetNumberOfVertices() const -> CellFeatureCount
{
return Self::NumberOfPoints;
}
/**
* Line-specific:
* Get the vertex specified by the given cell feature Id.
* The Id can range from 0 to GetNumberOfVertices()-1.
*/
template <typename TCellInterface>
bool
LineCell<TCellInterface>::GetVertex(CellFeatureIdentifier vertexId, VertexAutoPointer & vertexPointer)
{
auto * vert = new VertexType;
vert->SetPointId(0, m_PointIds[vertexId]);
vertexPointer.TakeOwnership(vert);
return true;
}
} // end namespace itk
#endif
|
/*
* Test.cpp
*
* Created by Martin on 13 October 2012.
* Copyright 2012 Universiteit Leiden. All rights reserved.
*
* 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)
*/
/*
* These tests use the Catch test framework by Phil Nash.
* - https://github.com/philsquared/Catch - MSVC8, 9, 2010, GCC 4.2, LLVM 4.0
* - https://github.com/martinmoene/Catch - MSVC6 in addition to the above
*/
// Tell CATCH to provide a main():
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
/*
* end of file
*/
|
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <pybind11/functional.h>
#include <boost/filesystem.hpp>
#include <fast_gicp/gicp/fast_gicp.hpp>
#include <fast_gicp/gicp/fast_vgicp.hpp>
#ifdef USE_VGICP_CUDA
#include <fast_gicp/ndt/ndt_cuda.hpp>
#include <fast_gicp/gicp/fast_vgicp_cuda.hpp>
#endif
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/filters/approximate_voxel_grid.h>
namespace py = pybind11;
fast_gicp::NeighborSearchMethod search_method(const std::string& neighbor_search_method) {
if(neighbor_search_method == "DIRECT1") {
return fast_gicp::NeighborSearchMethod::DIRECT1;
} else if (neighbor_search_method == "DIRECT7") {
return fast_gicp::NeighborSearchMethod::DIRECT7;
} else if (neighbor_search_method == "DIRECT27") {
return fast_gicp::NeighborSearchMethod::DIRECT27;
} else if (neighbor_search_method == "DIRECT_RADIUS") {
return fast_gicp::NeighborSearchMethod::DIRECT_RADIUS;
}
std::cerr << "error: unknown neighbor search method " << neighbor_search_method << std::endl;
return fast_gicp::NeighborSearchMethod::DIRECT1;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr eigen2pcl(const Eigen::Matrix<double, -1, 3>& points) {
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
cloud->resize(points.rows());
for(int i=0; i<points.rows(); i++) {
cloud->at(i).getVector3fMap() = points.row(i).cast<float>();
}
return cloud;
}
Eigen::Matrix<double, -1, 3> downsample(const Eigen::Matrix<double, -1, 3>& points, double downsample_resolution) {
auto cloud = eigen2pcl(points);
pcl::ApproximateVoxelGrid<pcl::PointXYZ> voxelgrid;
voxelgrid.setLeafSize(downsample_resolution, downsample_resolution, downsample_resolution);
voxelgrid.setInputCloud(cloud);
pcl::PointCloud<pcl::PointXYZ>::Ptr filtered(new pcl::PointCloud<pcl::PointXYZ>);
voxelgrid.filter(*filtered);
Eigen::Matrix<float, -1, 3> filtered_points(filtered->size(), 3);
for(int i=0; i<filtered->size(); i++) {
filtered_points.row(i) = filtered->at(i).getVector3fMap();
}
return filtered_points.cast<double>();
}
Eigen::Matrix4d align_points(
const Eigen::Matrix<double, -1, 3>& target,
const Eigen::Matrix<double, -1, 3>& source,
const std::string& method,
double downsample_resolution,
int k_correspondences,
double max_correspondence_distance,
double voxel_resolution,
int num_threads,
const std::string& neighbor_search_method,
double neighbor_search_radius,
const Eigen::Matrix4f& initial_guess
) {
pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud = eigen2pcl(target);
pcl::PointCloud<pcl::PointXYZ>::Ptr source_cloud = eigen2pcl(source);
if(downsample_resolution > 0.0) {
pcl::ApproximateVoxelGrid<pcl::PointXYZ> voxelgrid;
voxelgrid.setLeafSize(downsample_resolution, downsample_resolution, downsample_resolution);
pcl::PointCloud<pcl::PointXYZ>::Ptr filtered(new pcl::PointCloud<pcl::PointXYZ>);
voxelgrid.setInputCloud(target_cloud);
voxelgrid.filter(*filtered);
target_cloud.swap(filtered);
voxelgrid.setInputCloud(source_cloud);
voxelgrid.filter(*filtered);
source_cloud.swap(filtered);
}
std::shared_ptr<fast_gicp::LsqRegistration<pcl::PointXYZ, pcl::PointXYZ>> reg;
if(method == "GICP") {
std::shared_ptr<fast_gicp::FastGICP<pcl::PointXYZ, pcl::PointXYZ>> gicp(new fast_gicp::FastGICP<pcl::PointXYZ, pcl::PointXYZ>);
gicp->setMaxCorrespondenceDistance(max_correspondence_distance);
gicp->setCorrespondenceRandomness(k_correspondences);
gicp->setNumThreads(num_threads);
reg = gicp;
} else if (method == "VGICP") {
std::shared_ptr<fast_gicp::FastVGICP<pcl::PointXYZ, pcl::PointXYZ>> vgicp(new fast_gicp::FastVGICP<pcl::PointXYZ, pcl::PointXYZ>);
vgicp->setCorrespondenceRandomness(k_correspondences);
vgicp->setResolution(voxel_resolution);
vgicp->setNeighborSearchMethod(search_method(neighbor_search_method));
vgicp->setNumThreads(num_threads);
reg = vgicp;
} else if (method == "VGICP_CUDA") {
#ifdef USE_VGICP_CUDA
std::shared_ptr<fast_gicp::FastVGICPCuda<pcl::PointXYZ, pcl::PointXYZ>> vgicp(new fast_gicp::FastVGICPCuda<pcl::PointXYZ, pcl::PointXYZ>);
vgicp->setCorrespondenceRandomness(k_correspondences);
vgicp->setNeighborSearchMethod(search_method(neighbor_search_method), neighbor_search_radius);
vgicp->setResolution(voxel_resolution);
reg = vgicp;
#else
std::cerr << "error: you need to build fast_gicp with BUILD_VGICP_CUDA=ON" << std::endl;
return Eigen::Matrix4d::Identity();
#endif
} else if (method == "NDT_CUDA") {
#ifdef USE_VGICP_CUDA
std::shared_ptr<fast_gicp::NDTCuda<pcl::PointXYZ, pcl::PointXYZ>> ndt(new fast_gicp::NDTCuda<pcl::PointXYZ, pcl::PointXYZ>);
ndt->setResolution(voxel_resolution);
ndt->setNeighborSearchMethod(search_method(neighbor_search_method), neighbor_search_radius);
reg = ndt;
#else
std::cerr << "error: you need to build fast_gicp with BUILD_VGICP_CUDA=ON" << std::endl;
return Eigen::Matrix4d::Identity();
#endif
} else {
std::cerr << "error: unknown registration method " << method << std::endl;
return Eigen::Matrix4d::Identity();
}
reg->setInputTarget(target_cloud);
reg->setInputSource(source_cloud);
pcl::PointCloud<pcl::PointXYZ>::Ptr aligned(new pcl::PointCloud<pcl::PointXYZ>);
reg->align(*aligned, initial_guess);
return reg->getFinalTransformation().cast<double>();
}
using LsqRegistration = fast_gicp::LsqRegistration<pcl::PointXYZ, pcl::PointXYZ>;
using FastGICP = fast_gicp::FastGICP<pcl::PointXYZ, pcl::PointXYZ>;
using FastVGICP = fast_gicp::FastVGICP<pcl::PointXYZ, pcl::PointXYZ>;
#ifdef USE_VGICP_CUDA
using FastVGICPCuda = fast_gicp::FastVGICPCuda<pcl::PointXYZ, pcl::PointXYZ>;
using NDTCuda = fast_gicp::NDTCuda<pcl::PointXYZ, pcl::PointXYZ>;
#endif
PYBIND11_MODULE(pygicp, m) {
m.def("downsample", &downsample, "downsample points");
m.def("align_points", &align_points, "align two point sets",
py::arg("target"),
py::arg("source"),
py::arg("method") = "GICP",
py::arg("downsample_resolution") = -1.0,
py::arg("k_correspondences") = 15,
py::arg("max_correspondence_distance") = std::numeric_limits<double>::max(),
py::arg("voxel_resolution") = 1.0,
py::arg("num_threads") = 0,
py::arg("neighbor_search_method") = "DIRECT1",
py::arg("neighbor_search_radius") = 1.5,
py::arg("initial_guess") = Eigen::Matrix4f::Identity()
);
py::class_<LsqRegistration, std::shared_ptr<LsqRegistration>>(m, "LsqRegistration")
.def("set_input_target", [] (LsqRegistration& reg, const Eigen::Matrix<double, -1, 3>& points) { reg.setInputTarget(eigen2pcl(points)); })
.def("set_input_source", [] (LsqRegistration& reg, const Eigen::Matrix<double, -1, 3>& points) { reg.setInputSource(eigen2pcl(points)); })
.def("swap_source_and_target", &LsqRegistration::swapSourceAndTarget)
.def("get_final_hessian", &LsqRegistration::getFinalHessian)
.def("get_final_transformation", &LsqRegistration::getFinalTransformation)
.def("align",
[] (LsqRegistration& reg, const Eigen::Matrix4f& initial_guess) {
pcl::PointCloud<pcl::PointXYZ> aligned;
reg.align(aligned, initial_guess);
return reg.getFinalTransformation();
}, py::arg("initial_guess") = Eigen::Matrix4f::Identity()
)
;
py::class_<FastGICP, LsqRegistration, std::shared_ptr<FastGICP>>(m, "FastGICP")
.def(py::init())
.def("set_num_threads", &FastGICP::setNumThreads)
.def("set_correspondence_randomness", &FastGICP::setCorrespondenceRandomness)
.def("set_max_correspondence_distance", &FastGICP::setMaxCorrespondenceDistance)
;
py::class_<FastVGICP, FastGICP, std::shared_ptr<FastVGICP>>(m, "FastVGICP")
.def(py::init())
.def("set_resolution", &FastVGICP::setResolution)
.def("set_neighbor_search_method", [](FastVGICP& vgicp, const std::string& method) { vgicp.setNeighborSearchMethod(search_method(method)); })
;
#ifdef USE_VGICP_CUDA
py::class_<FastVGICPCuda, LsqRegistration, std::shared_ptr<FastVGICPCuda>>(m, "FastVGICPCuda")
.def(py::init())
.def("set_resolution", &FastVGICPCuda::setResolution)
.def("set_neighbor_search_method",
[](FastVGICPCuda& vgicp, const std::string& method, double radius) { vgicp.setNeighborSearchMethod(search_method(method), radius); }
, py::arg("method") = "DIRECT1", py::arg("radius") = 1.5
)
.def("set_correspondence_randomness", &FastVGICPCuda::setCorrespondenceRandomness)
;
py::class_<NDTCuda, LsqRegistration, std::shared_ptr<NDTCuda>>(m, "NDTCuda")
.def(py::init())
.def("set_neighbor_search_method",
[](NDTCuda& ndt, const std::string& method, double radius) { ndt.setNeighborSearchMethod(search_method(method), radius); }
, py::arg("method") = "DIRECT1", py::arg("radius") = 1.5
)
.def("set_resolution", &NDTCuda::setResolution)
;
#endif
#ifdef VERSION_INFO
m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO);
#else
m.attr("__version__") = "dev";
#endif
}
|
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "storage/lake/tablet.h"
#include "storage/lake/metadata_iterator.h"
#include "storage/lake/tablet_manager.h"
#include "storage/lake/txn_log.h"
namespace starrocks::lake {
Status Tablet::put_metadata(const TabletMetadata& metadata) {
return _mgr->put_tablet_metadata(_group, metadata);
}
Status Tablet::put_metadata(TabletMetadataPtr metadata) {
return _mgr->put_tablet_metadata(_group, std::move(metadata));
}
StatusOr<TabletMetadataPtr> Tablet::get_metadata(int64_t version) {
return _mgr->get_tablet_metadata(_group, _id, version);
}
StatusOr<MetadataIterator> Tablet::list_metadata() {
return _mgr->list_tablet_metadata(_group, _id);
}
Status Tablet::delete_metadata(int64_t version) {
return _mgr->delete_tablet_metadata(_group, _id, version);
}
Status Tablet::delete_metadata() {
return Status::NotSupported("Tablet::delete_metadata");
}
Status Tablet::put_txn_log(const TxnLog& log) {
// TODO: Check log.tablet_id() == _id
return _mgr->put_txn_log(_group, log);
}
Status Tablet::put_txn_log(TxnLogPtr log) {
// TODO: Check log.tablet_id() == _id
return _mgr->put_txn_log(_group, std::move(log));
}
StatusOr<TxnLogPtr> Tablet::get_txn_log(int64_t txn_id) {
return _mgr->get_txn_log(_group, _id, txn_id);
}
Status Tablet::delete_txn_log(int64_t txn_id) {
return _mgr->delete_txn_log(_group, _id, txn_id);
}
} // namespace starrocks::lake
|
// Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 "unittest.h"
#include "rapidjson/allocators.h"
using namespace rapidjson;
template <typename Allocator>
void TestAllocator(Allocator& a) {
EXPECT_TRUE(a.Malloc(0) == 0);
uint8_t* p = static_cast<uint8_t*>(a.Malloc(100));
EXPECT_TRUE(p != 0);
for (size_t i = 0; i < 100; i++)
p[i] = static_cast<uint8_t>(i);
// Expand
uint8_t* q = static_cast<uint8_t*>(a.Realloc(p, 100, 200));
EXPECT_TRUE(q != 0);
for (size_t i = 0; i < 100; i++)
EXPECT_EQ(i, q[i]);
for (size_t i = 100; i < 200; i++)
q[i] = static_cast<uint8_t>(i);
// Shrink
uint8_t *r = static_cast<uint8_t*>(a.Realloc(q, 200, 150));
EXPECT_TRUE(r != 0);
for (size_t i = 0; i < 150; i++)
EXPECT_EQ(i, r[i]);
Allocator::Free(r);
// Realloc to zero size
EXPECT_TRUE(a.Realloc(a.Malloc(1), 1, 0) == 0);
}
TEST(Allocator, CrtAllocator) {
CrtAllocator a;
TestAllocator(a);
}
TEST(Allocator, MemoryPoolAllocator) {
MemoryPoolAllocator<> a;
TestAllocator(a);
for (size_t i = 1; i < 1000; i++) {
EXPECT_TRUE(a.Malloc(i) != 0);
EXPECT_LE(a.Size(), a.Capacity());
}
}
TEST(Allocator, Alignment) {
#if RAPIDJSON_64BIT == 1
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000000), RAPIDJSON_ALIGN(0));
for (uint64_t i = 1; i < 8; i++) {
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008), RAPIDJSON_ALIGN(i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000010), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008) + i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000001, 0x00000000), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0xFFFFFFF8) + i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF8), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF0) + i));
}
#else
EXPECT_EQ(0u, RAPIDJSON_ALIGN(0u));
for (uint32_t i = 1; i < 4; i++) {
EXPECT_EQ(4u, RAPIDJSON_ALIGN(i));
EXPECT_EQ(8u, RAPIDJSON_ALIGN(4u + i));
EXPECT_EQ(0xFFFFFFF8u, RAPIDJSON_ALIGN(0xFFFFFFF4u + i));
EXPECT_EQ(0xFFFFFFFCu, RAPIDJSON_ALIGN(0xFFFFFFF8u + i));
}
#endif
}
|
#include <iostream>
#include "matrix.h"
#define check(cond) do { if (!(cond)) std::cout << "line " << __LINE__ << ": " << #cond << '\n'; } while(0)
// void do_testing() {
// Matrix A(3, 4);
// A[0][0] = 1; A[0][1] = 2; A[0][2] = 3; A[0][3] = 4;
// A[1][0] = 5; A[1][1] = 6; A[1][2] = 7; A[1][3] = 8;
// A[2][0] = 9; A[2][1] = 10; A[2][2] = 11; A[2][3] = 12;
// Matrix B(3, 4);
// B[0][0] = 1; B[0][1] = 2; B[0][2] = 3; B[0][3] = 4;
// B[1][0] = 5; B[1][1] = 6; B[1][2] = 7; B[1][3] = 8;
// B[2][0] = 9; B[2][1] = 10; B[2][2] = 11; B[2][3] = 12;
// check(A == B);
// check(A.nrows() == 3);
// check(A.ncols() == 4);
// check(A[0][0] == 1 && A[0][1] == 2 && A[0][2] == 3 && A[0][3] == 4);
// check(A[1][0] == 5 && A[1][1] == 6 && A[1][2] == 7 && A[1][3] == 8);
// check(A[2][0] == 9 && A[2][1] == 10 && A[2][2] == 11 && A[2][3] == 12);
// A[1][2] = -23;
// check(A[1][2] == -23);
// B[2][1] *= 2;
// check(B[2][1] == 20);
// std::vector<double> v = {1, 2, 3, 4};
// A *= v;
// check(A.nrows() == 3);
// check(A.ncols() == 1);
// check(A[0][0] == 30);
// check(A[1][0] == -20);
// check(A[2][0] == 110);
// }
int main() {
// do_testing();
return 0;
}
|
#include "programfiletab.h"
#include "ui_programfiletab.h"
#include "parser.h"
#include "pipeline.h"
ProgramfileTab::ProgramfileTab(QWidget* parent) : QWidget(parent), m_ui(new Ui::ProgramfileTab) {
m_ui->setupUi(this);
// Only add syntax highlighter for code edit view - not for translated code. This is assumed to be correct after a
// translation is complete
m_ui->assemblyedit->setupSyntaxHighlighter();
m_ui->assemblyedit->setupAssembler();
m_ui->binaryedit->setReadOnly(true);
// enable breakpoint area for the translated code only
m_ui->binaryedit->enableBreakpointArea();
// Link scrollbars together for pleasant navigation
connect(m_ui->assemblyedit->verticalScrollBar(), &QScrollBar::valueChanged, m_ui->binaryedit->verticalScrollBar(),
&QScrollBar::setValue);
connect(m_ui->binaryedit->verticalScrollBar(), &QScrollBar::valueChanged, m_ui->assemblyedit->verticalScrollBar(),
&QScrollBar::setValue);
// Connect data parsing signals from the assembler to this
connect(m_ui->assemblyedit, &CodeEditor::assembledSuccessfully, this, &ProgramfileTab::assemblingComplete);
}
QString ProgramfileTab::getAssemblyText() {
return m_ui->assemblyedit->toPlainText();
}
const QByteArray& ProgramfileTab::getBinaryData() {
return m_ui->assemblyedit->getCurrentOutputArray();
}
void ProgramfileTab::clearOutputArray() {
m_ui->assemblyedit->clearOutputArray();
}
ProgramfileTab::~ProgramfileTab() {
delete m_ui;
}
void ProgramfileTab::setTimerEnabled(bool state) {
m_ui->assemblyedit->setTimerEnabled(state);
}
void ProgramfileTab::newProgram() {
m_ui->assemblyfile->toggle();
m_ui->assemblyedit->reset();
m_ui->assemblyedit->clear();
}
void ProgramfileTab::on_pushButton_clicked() {
// load file based on current file type selection
if (m_ui->binaryfile->isChecked()) {
emit loadBinaryFile();
} else {
loadAssemblyFile();
}
}
void ProgramfileTab::setAssemblyText(const QString& text) {
m_ui->assemblyedit->reset();
m_ui->assemblyedit->setPlainText(text);
}
void ProgramfileTab::setDisassemblerText() {
const QString& text = m_ui->disassembledViewButton->isChecked() ? Parser::getParser()->getDisassembledRepr()
: Parser::getParser()->getBinaryRepr();
m_ui->binaryedit->setPlainText(text);
m_ui->binaryedit->updateBreakpoints();
}
void ProgramfileTab::assemblingComplete(const QByteArray& arr, bool clear, uint32_t baseAddress) {
if (clear)
Parser::getParser()->clear();
// Pretty hacky way to discern between the text and data segments
if (baseAddress > 0) {
Parser::getParser()->loadFromByteArrayIntoData(arr);
} else {
Parser::getParser()->loadFromByteArray(arr, m_ui->disassembledViewButton->isChecked(), baseAddress);
setDisassemblerText();
}
emit updateSimulator();
}
void ProgramfileTab::on_assemblyfile_toggled(bool checked) {
// Since we are removing the input text/binary info, we need to reset the pipeline
Pipeline::getPipeline()->reset();
// handles toggling between assembly input and binary input
if (checked) {
m_ui->assemblyedit->setEnabled(true);
m_ui->assemblyedit->setTimerEnabled(true);
} else {
// Disable when loading binary files
m_ui->assemblyedit->setTimerEnabled(false);
m_ui->assemblyedit->setEnabled(false);
}
// clear both editors when switching input mode and reset the highlighter for the assembly editor
m_ui->assemblyedit->clear();
m_ui->assemblyedit->reset();
m_ui->binaryedit->clear();
}
void ProgramfileTab::setInputMode(bool isAssembly) {
if (isAssembly) {
m_ui->assemblyfile->setChecked(true);
} else {
m_ui->binaryfile->setChecked(true);
}
}
void ProgramfileTab::on_disassembledViewButton_toggled(bool checked) {
Q_UNUSED(checked)
if (m_ui->binaryfile->isChecked()) {
assemblingComplete(Parser::getParser()->getFileByteArray());
} else {
assemblingComplete(m_ui->assemblyedit->getCurrentOutputArray());
}
}
|
/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
namespace paddle {
namespace operators {
enum MiningType { kNone = 0, kMaxNegative, kHardExample };
template <typename T>
bool SortScoreDescend(const std::pair<float, T>& pair1,
const std::pair<float, T>& pair2) {
return pair1.first > pair2.first;
}
inline bool IsEligibleMining(const MiningType mining_type, const int match_idx,
const float match_dist,
const float neg_dist_threshold) {
if (mining_type == MiningType::kMaxNegative) {
return match_idx == -1 && match_dist < neg_dist_threshold;
} else if (mining_type == MiningType::kHardExample) {
return true;
} else {
return false;
}
}
inline MiningType GetMiningType(std::string str) {
if (str == "max_negative") {
return MiningType::kMaxNegative;
} else if (str == "hard_example") {
return MiningType::kHardExample;
} else {
return MiningType::kNone;
}
}
template <typename DeviceContext, typename T>
class MineHardExamplesKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* in_cls_loss = ctx.Input<framework::Tensor>("ClsLoss");
auto* in_loc_loss = ctx.Input<framework::Tensor>("LocLoss");
auto* in_matched_indices = ctx.Input<framework::Tensor>("MatchIndices");
auto* in_match_dist = ctx.Input<framework::Tensor>("MatchDist");
float neg_pos_ratio = ctx.Attr<float>("neg_pos_ratio");
T neg_dist_threshold =
static_cast<T>(ctx.Attr<float>("neg_dist_threshold"));
int sample_size = ctx.Attr<int>("sample_size");
MiningType mining_type =
GetMiningType(ctx.Attr<std::string>("mining_type"));
auto out_neg_indices = ctx.Output<framework::LoDTensor>("NegIndices");
auto out_match_indices =
ctx.Output<framework::Tensor>("UpdatedMatchIndices");
framework::TensorCopy(*in_matched_indices, ctx.GetPlace(),
out_match_indices);
int batch_size = in_matched_indices->dims()[0];
int prior_num = in_matched_indices->dims()[1];
auto match_indices = framework::EigenMatrix<int>::From(*in_matched_indices);
auto match_indices_et =
framework::EigenMatrix<int>::From(*out_match_indices);
auto match_dist = framework::EigenMatrix<T>::From(*in_match_dist);
const T* cls_loss = in_cls_loss->data<T>();
const T* loc_loss = nullptr;
if (in_loc_loss) {
loc_loss = in_loc_loss->data<T>();
}
std::vector<std::vector<int>> all_neg_indices;
std::vector<size_t> batch_starts = {0};
for (int n = 0; n < batch_size; ++n) {
std::vector<std::pair<T, size_t>> loss_idx;
int neg_sel = 0;
for (int m = 0; m < prior_num; ++m) {
if (IsEligibleMining(mining_type, match_indices(n, m), match_dist(n, m),
neg_dist_threshold)) {
T loss = cls_loss[n * prior_num + m];
if (mining_type == MiningType::kHardExample && loc_loss != nullptr) {
loss = cls_loss[n * prior_num + m] + loc_loss[n * prior_num + m];
}
loss_idx.push_back(std::make_pair(loss, m));
++neg_sel;
}
}
if (mining_type == MiningType::kMaxNegative) {
int num_pos = 0;
for (int m = 0; m < prior_num; ++m) {
if (match_indices(n, m) != -1) ++num_pos;
}
neg_sel = std::min(static_cast<int>(num_pos * neg_pos_ratio), neg_sel);
} else if (mining_type == MiningType::kHardExample) {
neg_sel = std::min(sample_size, neg_sel);
}
std::sort(loss_idx.begin(), loss_idx.end(), SortScoreDescend<size_t>);
std::set<int> sel_indices;
std::vector<int> neg_indices;
std::transform(loss_idx.begin(), loss_idx.begin() + neg_sel,
std::inserter(sel_indices, sel_indices.begin()),
[](std::pair<T, size_t>& l) -> int {
return static_cast<int>(l.second);
});
if (mining_type == MiningType::kHardExample) {
for (int m = 0; m < prior_num; ++m) {
if (match_indices(n, m) > -1) {
if (sel_indices.find(m) == sel_indices.end()) {
match_indices_et(n, m) = -1;
}
} else {
if (sel_indices.find(m) != sel_indices.end()) {
neg_indices.push_back(m);
}
}
}
} else {
neg_indices.resize(sel_indices.size());
std::copy(sel_indices.begin(), sel_indices.end(), neg_indices.begin());
}
all_neg_indices.push_back(neg_indices);
batch_starts.push_back(batch_starts.back() + neg_indices.size());
}
framework::LoD out_neg_indices_lod;
out_neg_indices_lod.emplace_back(batch_starts);
int neg_offset = 0;
auto neg_data = out_neg_indices->mutable_data<int>(
framework::make_ddim({static_cast<int>(batch_starts.back()), 1}),
ctx.GetPlace());
for (auto neg_indices : all_neg_indices) {
std::copy(neg_indices.begin(), neg_indices.end(), neg_data + neg_offset);
neg_offset += neg_indices.size();
}
out_neg_indices->set_lod(out_neg_indices_lod);
return;
}
};
class MineHardExamplesOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
protected:
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("ClsLoss"),
"Input(ClsLoss) of MineHardExamplesOp should not be null.");
PADDLE_ENFORCE(
ctx->HasInput("MatchIndices"),
"Input(MatchIndices) of MineHardExamplesOp should not be null.");
PADDLE_ENFORCE(
ctx->HasInput("MatchDist"),
"Input(MatchDist) of MineHardExamplesOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("NegIndices"),
"Output(NegIndices) of MineHardExamplesOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("UpdatedMatchIndices"),
"Output(UpdatedMatchIndices) of MineHardExamplesOp should "
"not be null.");
auto cls_loss_dims = ctx->GetInputDim("ClsLoss");
auto idx_dims = ctx->GetInputDim("MatchIndices");
auto dis_dims = ctx->GetInputDim("MatchDist");
PADDLE_ENFORCE_EQ(cls_loss_dims.size(), 2UL,
"The shape of ClsLoss is [N, Np].");
PADDLE_ENFORCE_EQ(idx_dims.size(), 2UL,
"The shape of MatchIndices is [N, Np].");
PADDLE_ENFORCE_EQ(dis_dims.size(), 2UL,
"The shape of MatchDist is [N, Np].");
if (ctx->HasInput("LocLoss")) {
auto loc_loss_dims = ctx->GetInputDim("LocLoss");
PADDLE_ENFORCE_EQ(loc_loss_dims.size(), 2UL,
"The shape of LocLoss is [N, Np].");
PADDLE_ENFORCE_EQ(cls_loss_dims[0], loc_loss_dims[0],
"Batch size of ClsLoss and LocLoss must be the same.");
PADDLE_ENFORCE_EQ(
cls_loss_dims[1], loc_loss_dims[1],
"Prior box number of ClsLoss and LocLoss must be the same.");
}
PADDLE_ENFORCE_EQ(
cls_loss_dims[0], idx_dims[0],
"Batch size of ClsLoss and MatchIndices must be the same.");
PADDLE_ENFORCE_EQ(
cls_loss_dims[1], idx_dims[1],
"Prior box number of ClsLoss and MatchIndices must be the same.");
PADDLE_ENFORCE_EQ(cls_loss_dims[0], dis_dims[0],
"Batch size of ClsLoss and MatchDist must be the same.");
PADDLE_ENFORCE_EQ(
cls_loss_dims[1], idx_dims[1],
"Prior box number of ClsLoss and MatchDist must be the same.");
auto mining_type =
GetMiningType(ctx->Attrs().Get<std::string>("mining_type"));
PADDLE_ENFORCE_NE(mining_type, MiningType::kNone,
"mining_type must be hard_example or max_negative");
if (mining_type == MiningType::kMaxNegative) {
auto neg_pos_ratio = ctx->Attrs().Get<float>("neg_pos_ratio");
auto neg_dist_threshold = ctx->Attrs().Get<float>("neg_dist_threshold");
PADDLE_ENFORCE_GT(
neg_pos_ratio, 0.0f,
"neg_pos_ratio must greater than zero in max_negative mode");
PADDLE_ENFORCE_LT(
neg_dist_threshold, 1.0f,
"neg_dist_threshold must less than one in max_negative mode");
PADDLE_ENFORCE_GT(
neg_dist_threshold, 0.0f,
"neg_dist_threshold must greater than zero in max_negative mode");
} else if (mining_type == MiningType::kHardExample) {
auto sample_size = ctx->Attrs().Get<int>("sample_size");
PADDLE_ENFORCE_GT(
sample_size, 0,
"sample_size must greater than zero in hard_example mode");
}
ctx->SetOutputDim("UpdatedMatchIndices", idx_dims);
// The first dimension of NegIndices will be set correcttly in Compute.
ctx->SetOutputDim("NegIndices", {-1, 1});
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
ctx.Input<framework::Tensor>("ClsLoss")->type(), platform::CPUPlace());
}
};
class MineHardExamplesOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput(
"ClsLoss",
"(Tensor, default Tensor<float>), The classification loss with shape "
"[N, Np], N is the batch size and Np is the number of prior box.");
AddInput("LocLoss",
"(Tensor, optional, default Tensor<float>), The localization loss "
"with shape [N, Np], N is the batch size and Np is the number of "
"prior box.")
.AsDispensable();
AddInput("MatchIndices",
"(Tensor, Tensor<int>), Matched indices with shape [N, Np], N is "
"the batch size and Np is the number of prior box. "
"MatchIndices[i][j] equal -1 means the j-th prior box in i-th "
"instance does not match any entity, otherwise means it is "
"matched to row.");
AddInput("MatchDist",
"(Tensor, default Tensor<float>) Matched indices with shape [N, "
"Np], N is the batch size and Np is the number of prior box.");
AddAttr<float>("neg_pos_ratio",
"(float) The ratio of the negative box to the positive "
"box. Use only when mining_type is max_negative.")
.SetDefault(1.0);
AddAttr<float>("neg_dist_threshold",
"(float) The negative overlap upper bound for the unmatched "
"predictions. Use only when mining_type is max_negative.")
.SetDefault(0.5);
AddAttr<int>("sample_size",
"(float) The max sample size of negative box. Use only when "
"mining_type is hard_example.")
.SetDefault(0);
AddAttr<std::string>("mining_type",
"(float) The mining algorithm name, the value is "
"hard_example or max_negative.")
.SetDefault("max_negative")
.InEnum({"hard_example", "max_negative"});
AddOutput(
"NegIndices",
"(LoDTensor<int>) The output of negative example indices. a LoDTensor "
"with shape [Neg, 1]. The size of lod[0] minus 1 is batch size, "
"and each element is the prior box index. "
"For example, the batch size is 2, the lod is [[0, 1, 2]], "
"the sample 0's box 1(MatchIndices[0][1]) is selected, "
"and sample 1's box 0 is selected. The output NegIndices is "
"[[1], [0]].");
AddOutput("UpdatedMatchIndices",
"(Tensor<int>) The output of updated MatchIndices, a tensor with "
"shape [N, Np]. Only update when mining_type is "
"hard_example. The input MatchIndices elements will be update to "
"-1 when it is not in the candidate high loss list of negative "
"examples.");
AddComment(R"DOC(
Mine hard examples Operator.
This operator implements hard example mining to select a subset of negative box indices.
For each image, selects the box with highest losses. subject to the condition that the
box cannot have an Matcht > neg_dist_threshold when mining_type is max_negative.
The selected number is min(sample_size, max_negative_box_number) when mining_type is
hard_example, or min(neg_pos_ratio * positive_box_number, max_negative_box_number)
when mining_type is max_negative, where the max_negative_box_number is the count of
MatchIndices elements with value -1.
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(mine_hard_examples, ops::MineHardExamplesOp,
ops::MineHardExamplesOpMaker,
paddle::framework::EmptyGradOpMaker);
REGISTER_OP_CPU_KERNEL(
mine_hard_examples,
ops::MineHardExamplesKernel<paddle::platform::CPUDeviceContext, float>,
ops::MineHardExamplesKernel<paddle::platform::CPUDeviceContext, double>);
|
/*
* Copyright (c) 2008, Willow Garage, Inc.
* Copyright (c) 2017, Open Source Robotics Foundation, 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, 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 "rviz_rendering/objects/arrow.hpp"
#include <sstream>
#include <OgreQuaternion.h>
#include <OgreSceneManager.h>
#include <OgreSceneNode.h>
#include <OgreVector3.h>
#include "rviz_rendering/objects/shape.hpp"
namespace rviz_rendering
{
Arrow::Arrow(
Ogre::SceneManager * scene_manager, Ogre::SceneNode * parent_node, float shaft_length,
float shaft_diameter,
float head_length, float head_diameter)
: Object(scene_manager)
{
if (!parent_node) {
parent_node = scene_manager_->getRootSceneNode();
}
scene_node_ = parent_node->createChildSceneNode();
shaft_ = new Shape(Shape::Cylinder, scene_manager_, scene_node_);
head_ = new Shape(Shape::Cone, scene_manager_, scene_node_);
head_->setOffset(Ogre::Vector3(0.0f, 0.5f, 0.0f));
set(shaft_length, shaft_diameter, head_length, head_diameter);
setOrientation(Ogre::Quaternion::IDENTITY);
}
Arrow::~Arrow()
{
delete shaft_;
delete head_;
scene_manager_->destroySceneNode(scene_node_);
}
void Arrow::set(float shaft_length, float shaft_diameter, float head_length, float head_diameter)
{
shaft_->setScale(Ogre::Vector3(shaft_diameter, shaft_length, shaft_diameter));
shaft_->setPosition(Ogre::Vector3(0.0f, shaft_length / 2.0f, 0.0f) );
head_->setScale(Ogre::Vector3(head_diameter, head_length, head_diameter) );
head_->setPosition(Ogre::Vector3(0.0f, shaft_length, 0.0f) );
}
void Arrow::setColor(const Ogre::ColourValue & c)
{
setShaftColor(c);
setHeadColor(c);
}
void Arrow::setColor(float r, float g, float b, float a)
{
setColor(Ogre::ColourValue(r, g, b, a));
}
void Arrow::setShaftColor(const Ogre::ColourValue & c)
{
shaft_->setColor(c);
}
void Arrow::setHeadColor(const Ogre::ColourValue & c)
{
head_->setColor(c);
}
void Arrow::setShaftColor(float r, float g, float b, float a)
{
setShaftColor(Ogre::ColourValue(r, g, b, a));
}
void Arrow::setHeadColor(float r, float g, float b, float a)
{
setHeadColor(Ogre::ColourValue(r, g, b, a));
}
void Arrow::setPosition(const Ogre::Vector3 & position)
{
scene_node_->setPosition(position);
}
void Arrow::setOrientation(const Ogre::Quaternion & orientation)
{
// "forward" (negative z) should always be our identity orientation
// ... wouldn't need to mangle the orientation if we just fix the cylinders!
scene_node_->setOrientation(
orientation * Ogre::Quaternion(Ogre::Degree(-90), Ogre::Vector3::UNIT_X) );
}
void Arrow::setDirection(const Ogre::Vector3 & direction)
{
if (!direction.isZeroLength() ) {
setOrientation(Ogre::Vector3::NEGATIVE_UNIT_Z.getRotationTo(direction));
}
}
void Arrow::setScale(const Ogre::Vector3 & scale)
{
// Have to mangle the scale because of the default orientation of the cylinders :(
scene_node_->setScale(Ogre::Vector3(scale.z, scale.x, scale.y) );
}
const Ogre::Vector3 & Arrow::getPosition()
{
return scene_node_->getPosition();
}
const Ogre::Quaternion & Arrow::getOrientation()
{
return scene_node_->getOrientation();
}
void Arrow::setUserData(const Ogre::Any & data)
{
head_->setUserData(data);
shaft_->setUserData(data);
}
} // namespace rviz_rendering
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/datasync/model/ListLocationsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::DataSync::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
ListLocationsRequest::ListLocationsRequest() :
m_maxResults(0),
m_maxResultsHasBeenSet(false),
m_nextTokenHasBeenSet(false)
{
}
Aws::String ListLocationsRequest::SerializePayload() const
{
JsonValue payload;
if(m_maxResultsHasBeenSet)
{
payload.WithInteger("MaxResults", m_maxResults);
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection ListLocationsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "FmrsService.ListLocations"));
return headers;
}
|
// Copyright 2017 The Ray 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 "ray/raylet/node_manager.h"
#include <cctype>
#include <csignal>
#include <fstream>
#include <memory>
#include "boost/filesystem.hpp"
#include "boost/system/error_code.hpp"
#include "ray/common/asio/asio_util.h"
#include "ray/common/asio/instrumented_io_context.h"
#include "ray/common/buffer.h"
#include "ray/common/common_protocol.h"
#include "ray/common/constants.h"
#include "ray/common/status.h"
#include "ray/gcs/pb_util.h"
#include "ray/raylet/format/node_manager_generated.h"
#include "ray/stats/stats.h"
#include "ray/util/event.h"
#include "ray/util/event_label.h"
#include "ray/util/sample.h"
#include "ray/util/util.h"
namespace {
#define RAY_CHECK_ENUM(x, y) \
static_assert(static_cast<int>(x) == static_cast<int>(y), "protocol mismatch")
struct ActorStats {
int live_actors = 0;
int dead_actors = 0;
int restarting_actors = 0;
};
inline ray::rpc::ObjectReference FlatbufferToSingleObjectReference(
const flatbuffers::String &object_id, const ray::protocol::Address &address) {
ray::rpc::ObjectReference ref;
ref.set_object_id(object_id.str());
ref.mutable_owner_address()->set_raylet_id(address.raylet_id()->str());
ref.mutable_owner_address()->set_ip_address(address.ip_address()->str());
ref.mutable_owner_address()->set_port(address.port());
ref.mutable_owner_address()->set_worker_id(address.worker_id()->str());
return ref;
}
std::vector<ray::rpc::ObjectReference> FlatbufferToObjectReference(
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> &object_ids,
const flatbuffers::Vector<flatbuffers::Offset<ray::protocol::Address>>
&owner_addresses) {
RAY_CHECK(object_ids.size() == owner_addresses.size());
std::vector<ray::rpc::ObjectReference> refs;
for (int64_t i = 0; i < object_ids.size(); i++) {
ray::rpc::ObjectReference ref;
ref.set_object_id(object_ids.Get(i)->str());
const auto &addr = owner_addresses.Get(i);
ref.mutable_owner_address()->set_raylet_id(addr->raylet_id()->str());
ref.mutable_owner_address()->set_ip_address(addr->ip_address()->str());
ref.mutable_owner_address()->set_port(addr->port());
ref.mutable_owner_address()->set_worker_id(addr->worker_id()->str());
refs.emplace_back(std::move(ref));
}
return refs;
}
} // namespace
namespace ray {
namespace raylet {
// A helper function to print the leased workers.
std::string LeasedWorkersSring(
const absl::flat_hash_map<WorkerID, std::shared_ptr<WorkerInterface>>
&leased_workers) {
std::stringstream buffer;
buffer << " @leased_workers: (";
for (const auto &pair : leased_workers) {
auto &worker = pair.second;
buffer << worker->WorkerId() << ", ";
}
buffer << ")";
return buffer.str();
}
// A helper function to print the workers in worker_pool_.
std::string WorkerPoolString(
const std::vector<std::shared_ptr<WorkerInterface>> &worker_pool) {
std::stringstream buffer;
buffer << " @worker_pool: (";
for (const auto &worker : worker_pool) {
buffer << worker->WorkerId() << ", ";
}
buffer << ")";
return buffer.str();
}
// Helper function to print the worker's owner worker and and node owner.
std::string WorkerOwnerString(std::shared_ptr<WorkerInterface> &worker) {
std::stringstream buffer;
const auto owner_worker_id =
WorkerID::FromBinary(worker->GetOwnerAddress().worker_id());
const auto owner_node_id = NodeID::FromBinary(worker->GetOwnerAddress().raylet_id());
buffer << "leased_worker Lease " << worker->WorkerId() << " owned by "
<< owner_worker_id << " / " << owner_node_id;
return buffer.str();
}
HeartbeatSender::HeartbeatSender(NodeID self_node_id,
std::shared_ptr<gcs::GcsClient> gcs_client)
: self_node_id_(self_node_id), gcs_client_(gcs_client) {
// Init heartbeat thread and run its io service.
heartbeat_thread_.reset(new std::thread([this] {
SetThreadName("heartbeat");
/// The asio work to keep io_service_ alive.
boost::asio::io_service::work io_service_work_(heartbeat_io_service_);
heartbeat_io_service_.run();
}));
heartbeat_runner_.reset(new PeriodicalRunner(heartbeat_io_service_));
// Start sending heartbeats to the GCS.
last_heartbeat_at_ms_ = current_time_ms();
heartbeat_runner_->RunFnPeriodically(
[this] { Heartbeat(); },
RayConfig::instance().raylet_heartbeat_period_milliseconds(),
"NodeManager.deadline_timer.heartbeat");
}
HeartbeatSender::~HeartbeatSender() {
heartbeat_runner_.reset();
heartbeat_io_service_.stop();
if (heartbeat_thread_->joinable()) {
heartbeat_thread_->join();
}
heartbeat_thread_.reset();
}
void HeartbeatSender::Heartbeat() {
uint64_t now_ms = current_time_ms();
uint64_t interval = now_ms - last_heartbeat_at_ms_;
if (interval > RayConfig::instance().num_heartbeats_warning() *
RayConfig::instance().raylet_heartbeat_period_milliseconds()) {
RAY_LOG(WARNING)
<< "Last heartbeat was sent " << interval
<< " ms ago. There might be resource pressure on this node. If heartbeat keeps "
"lagging, this node can be marked as dead mistakenly.";
}
last_heartbeat_at_ms_ = now_ms;
stats::HeartbeatReportMs.Record(interval);
auto heartbeat_data = std::make_shared<HeartbeatTableData>();
heartbeat_data->set_node_id(self_node_id_.Binary());
RAY_CHECK_OK(
gcs_client_->Nodes().AsyncReportHeartbeat(heartbeat_data, [](Status status) {
if (status.IsDisconnected()) {
RAY_LOG(FATAL) << "This node has beem marked as dead.";
}
}));
}
NodeManager::NodeManager(instrumented_io_context &io_service, const NodeID &self_node_id,
const NodeManagerConfig &config,
const ObjectManagerConfig &object_manager_config,
std::shared_ptr<gcs::GcsClient> gcs_client)
: self_node_id_(self_node_id),
io_service_(io_service),
gcs_client_(gcs_client),
worker_pool_(
io_service, self_node_id_, config.node_manager_address,
config.num_workers_soft_limit, config.num_initial_python_workers_for_first_job,
config.maximum_startup_concurrency, config.min_worker_port,
config.max_worker_port, config.worker_ports, gcs_client_,
config.worker_commands, config.native_library_path,
/*starting_worker_timeout_callback=*/
[this] { cluster_task_manager_->ScheduleAndDispatchTasks(); },
config.ray_debugger_external,
/*get_time=*/[]() { return absl::GetCurrentTimeNanos() / 1e6; }),
client_call_manager_(io_service),
worker_rpc_pool_(client_call_manager_),
core_worker_subscriber_(std::make_unique<pubsub::Subscriber>(
self_node_id_,
/*channels=*/
std::vector<rpc::ChannelType>{
rpc::ChannelType::WORKER_OBJECT_EVICTION,
rpc::ChannelType::WORKER_REF_REMOVED_CHANNEL,
rpc::ChannelType::WORKER_OBJECT_LOCATIONS_CHANNEL},
RayConfig::instance().max_command_batch_size(),
/*get_client=*/
[this](const rpc::Address &address) {
return worker_rpc_pool_.GetOrConnect(address);
},
&io_service_)),
object_directory_(std::make_unique<OwnershipBasedObjectDirectory>(
io_service_, gcs_client_, core_worker_subscriber_.get(),
/*owner_client_pool=*/&worker_rpc_pool_,
/*max_object_report_batch_size=*/
RayConfig::instance().max_object_report_batch_size(),
[this](const ObjectID &obj_id, const ErrorType &error_type) {
rpc::ObjectReference ref;
ref.set_object_id(obj_id.Binary());
MarkObjectsAsFailed(error_type, {ref}, JobID::Nil());
})),
object_manager_(
io_service, self_node_id, object_manager_config, object_directory_.get(),
[this](const ObjectID &object_id, const std::string &object_url,
std::function<void(const ray::Status &)> callback) {
GetLocalObjectManager().AsyncRestoreSpilledObject(object_id, object_url,
callback);
},
/*get_spilled_object_url=*/
[this](const ObjectID &object_id) {
return GetLocalObjectManager().GetLocalSpilledObjectURL(object_id);
},
/*spill_objects_callback=*/
[this]() {
// This callback is called from the plasma store thread.
// NOTE: It means the local object manager should be thread-safe.
io_service_.post(
[this]() { GetLocalObjectManager().SpillObjectUptoMaxThroughput(); },
"NodeManager.SpillObjects");
return GetLocalObjectManager().IsSpillingInProgress();
},
/*object_store_full_callback=*/
[this]() {
// Post on the node manager's event loop since this
// callback is called from the plasma store thread.
// This will help keep node manager lock-less.
io_service_.post([this]() { TriggerGlobalGC(); }, "NodeManager.GlobalGC");
},
/*add_object_callback=*/
[this](const ObjectInfo &object_info) { HandleObjectLocal(object_info); },
/*delete_object_callback=*/
[this](const ObjectID &object_id) { HandleObjectMissing(object_id); },
/*pin_object=*/
[this](const ObjectID &object_id) {
std::vector<ObjectID> object_ids = {object_id};
std::vector<std::unique_ptr<RayObject>> results;
std::unique_ptr<RayObject> result;
if (GetObjectsFromPlasma(object_ids, &results) && results.size() > 0) {
result = std::move(results[0]);
}
return result;
},
/*fail_pull_request=*/
[this](const ObjectID &object_id) {
rpc::ObjectReference ref;
ref.set_object_id(object_id.Binary());
MarkObjectsAsFailed(rpc::ErrorType::OBJECT_FETCH_TIMED_OUT, {ref},
JobID::Nil());
}),
periodical_runner_(io_service),
report_resources_period_ms_(config.report_resources_period_ms),
temp_dir_(config.temp_dir),
initial_config_(config),
dependency_manager_(object_manager_),
node_manager_server_("NodeManager", config.node_manager_port,
config.node_manager_address == "127.0.0.1"),
node_manager_service_(io_service, *this),
agent_manager_service_handler_(
new DefaultAgentManagerServiceHandler(agent_manager_)),
agent_manager_service_(io_service, *agent_manager_service_handler_),
local_object_manager_(
self_node_id_, config.node_manager_address, config.node_manager_port,
RayConfig::instance().free_objects_batch_size(),
RayConfig::instance().free_objects_period_milliseconds(), worker_pool_,
worker_rpc_pool_,
/*max_io_workers*/ config.max_io_workers,
/*min_spilling_size*/ config.min_spilling_size,
/*is_external_storage_type_fs*/
RayConfig::instance().is_external_storage_type_fs(),
/*max_fused_object_count*/ RayConfig::instance().max_fused_object_count(),
/*on_objects_freed*/
[this](const std::vector<ObjectID> &object_ids) {
object_manager_.FreeObjects(object_ids,
/*local_only=*/false);
},
/*is_plasma_object_spillable*/
[this](const ObjectID &object_id) {
return object_manager_.IsPlasmaObjectSpillable(object_id);
},
/*core_worker_subscriber_=*/core_worker_subscriber_.get()),
high_plasma_storage_usage_(RayConfig::instance().high_plasma_storage_usage()),
local_gc_run_time_ns_(absl::GetCurrentTimeNanos()),
local_gc_throttler_(RayConfig::instance().local_gc_min_interval_s() * 1e9),
global_gc_throttler_(RayConfig::instance().global_gc_min_interval_s() * 1e9),
local_gc_interval_ns_(RayConfig::instance().local_gc_interval_s() * 1e9),
record_metrics_period_ms_(config.record_metrics_period_ms),
runtime_env_manager_(
/*deleter=*/[this](const std::string &uri, std::function<void(bool)> cb) {
if (RayConfig::instance().runtime_env_skip_local_gc()) {
return cb(true);
}
return agent_manager_->DeleteURIs({uri}, cb);
}),
next_resource_seq_no_(0) {
RAY_LOG(INFO) << "Initializing NodeManager with ID " << self_node_id_;
RAY_CHECK(RayConfig::instance().raylet_heartbeat_period_milliseconds() > 0);
SchedulingResources local_resources(config.resource_config);
cluster_resource_scheduler_ =
std::shared_ptr<ClusterResourceScheduler>(new ClusterResourceScheduler(
self_node_id_.Binary(), local_resources.GetTotalResources().GetResourceMap(),
*gcs_client_, [this]() { return object_manager_.GetUsedMemory(); },
[this]() { return object_manager_.PullManagerHasPullsQueued(); }));
auto get_node_info_func = [this](const NodeID &node_id) {
return gcs_client_->Nodes().Get(node_id);
};
auto announce_infeasible_task = [this](const RayTask &task) {
PublishInfeasibleTaskError(task);
};
RAY_CHECK(RayConfig::instance().max_task_args_memory_fraction() > 0 &&
RayConfig::instance().max_task_args_memory_fraction() <= 1)
<< "max_task_args_memory_fraction must be a nonzero fraction.";
int64_t max_task_args_memory = object_manager_.GetMemoryCapacity() *
RayConfig::instance().max_task_args_memory_fraction();
if (max_task_args_memory <= 0) {
RAY_LOG(WARNING)
<< "Max task args should be a fraction of the object store capacity, but object "
"store capacity is zero or negative. Allowing task args to use 100% of the "
"local object store. This can cause ObjectStoreFullErrors if the tasks' "
"return values are greater than the remaining capacity.";
max_task_args_memory = 0;
}
auto is_owner_alive = [this](const WorkerID &owner_worker_id,
const NodeID &owner_node_id) {
return !(failed_workers_cache_.count(owner_worker_id) > 0 ||
failed_nodes_cache_.count(owner_node_id) > 0);
};
cluster_task_manager_ = std::make_shared<ClusterTaskManager>(
self_node_id_,
std::dynamic_pointer_cast<ClusterResourceScheduler>(cluster_resource_scheduler_),
dependency_manager_, is_owner_alive, get_node_info_func, announce_infeasible_task,
worker_pool_, leased_workers_,
[this](const std::vector<ObjectID> &object_ids,
std::vector<std::unique_ptr<RayObject>> *results) {
return GetObjectsFromPlasma(object_ids, results);
},
max_task_args_memory);
placement_group_resource_manager_ = std::make_shared<NewPlacementGroupResourceManager>(
std::dynamic_pointer_cast<ClusterResourceScheduler>(cluster_resource_scheduler_),
// TODO (Alex): Ideally we could do these in a more robust way (retry
// them, do them with the lightweight heartbeat, etc).
[this](const ray::gcs::NodeResourceInfoAccessor::ResourceMap &resources) {
RAY_CHECK_OK(gcs_client_->NodeResources().AsyncUpdateResources(
self_node_id_, resources, nullptr));
},
[this](const std::vector<std::string> &resource_names) {
RAY_CHECK_OK(gcs_client_->NodeResources().AsyncDeleteResources(
self_node_id_, resource_names, nullptr));
});
periodical_runner_.RunFnPeriodically(
[this]() { cluster_task_manager_->ScheduleAndDispatchTasks(); },
RayConfig::instance().worker_cap_initial_backoff_delay_ms());
RAY_CHECK_OK(store_client_.Connect(config.store_socket_name.c_str()));
// Run the node manger rpc server.
node_manager_server_.RegisterService(node_manager_service_);
node_manager_server_.RegisterService(agent_manager_service_);
node_manager_server_.Run();
worker_pool_.SetNodeManagerPort(GetServerPort());
auto agent_command_line = ParseCommandLine(config.agent_command);
for (auto &arg : agent_command_line) {
auto node_manager_port_position = arg.find(kNodeManagerPortPlaceholder);
if (node_manager_port_position != std::string::npos) {
arg.replace(node_manager_port_position, strlen(kNodeManagerPortPlaceholder),
std::to_string(GetServerPort()));
}
}
auto options = AgentManager::Options({self_node_id, agent_command_line});
agent_manager_ = std::make_shared<AgentManager>(
std::move(options),
/*delay_executor=*/
[this](std::function<void()> task, uint32_t delay_ms) {
return execute_after(io_service_, task, delay_ms);
},
/*runtime_env_agent_factory=*/
[this](const std::string &ip_address, int port) {
RAY_CHECK(!ip_address.empty() && port != 0)
<< "ip_address: " << ip_address << " port: " << port;
return std::shared_ptr<rpc::RuntimeEnvAgentClientInterface>(
new rpc::RuntimeEnvAgentClient(ip_address, port, client_call_manager_));
});
worker_pool_.SetAgentManager(agent_manager_);
}
ray::Status NodeManager::RegisterGcs() {
// Start sending heartbeat here to ensure it happening after raylet being registered.
heartbeat_sender_.reset(new HeartbeatSender(self_node_id_, gcs_client_));
auto on_node_change = [this](const NodeID &node_id, const GcsNodeInfo &data) {
if (data.state() == GcsNodeInfo::ALIVE) {
NodeAdded(data);
} else {
RAY_CHECK(data.state() == GcsNodeInfo::DEAD);
NodeRemoved(node_id);
}
};
// If the node resource message is received first and then the node message is received,
// ForwardTask will throw exception, because it can't get node info.
auto on_done = [this](Status status) {
RAY_CHECK_OK(status);
// Subscribe to resource changes.
const auto &resources_changed =
[this](const rpc::NodeResourceChange &resource_notification) {
auto id = NodeID::FromBinary(resource_notification.node_id());
if (id == self_node_id_) {
return;
}
if (resource_notification.updated_resources_size() != 0) {
ResourceSet resource_set(
MapFromProtobuf(resource_notification.updated_resources()));
ResourceCreateUpdated(id, resource_set);
}
if (resource_notification.deleted_resources_size() != 0) {
ResourceDeleted(
id, VectorFromProtobuf(resource_notification.deleted_resources()));
}
};
RAY_CHECK_OK(gcs_client_->NodeResources().AsyncSubscribeToResources(
/*subscribe_callback=*/resources_changed,
/*done_callback=*/nullptr));
};
// Register a callback to monitor new nodes and a callback to monitor removed nodes.
RAY_RETURN_NOT_OK(
gcs_client_->Nodes().AsyncSubscribeToNodeChange(on_node_change, on_done));
// Subscribe to resource usage batches from the monitor.
const auto &resource_usage_batch_added =
[this](const ResourceUsageBatchData &resource_usage_batch) {
ResourceUsageBatchReceived(resource_usage_batch);
};
RAY_RETURN_NOT_OK(gcs_client_->NodeResources().AsyncSubscribeBatchedResourceUsage(
resource_usage_batch_added, /*done*/ nullptr));
// Subscribe to all unexpected failure notifications from the local and
// remote raylets. Note that this does not include workers that failed due to
// node failure. These workers can be identified by comparing the raylet_id
// in their rpc::Address to the ID of a failed raylet.
const auto &worker_failure_handler =
[this](const rpc::WorkerDeltaData &worker_failure_data) {
HandleUnexpectedWorkerFailure(worker_failure_data);
};
RAY_CHECK_OK(gcs_client_->Workers().AsyncSubscribeToWorkerFailures(
worker_failure_handler, /*done_callback=*/nullptr));
// Subscribe to job updates.
const auto job_subscribe_handler = [this](const JobID &job_id,
const JobTableData &job_data) {
// HandleJobStarted is idempotent so it's ok to call it again when the job
// finishes. We always need to call `HandleJobStarted` even when a job has
// finished, because we may have missed the started event (for example,
// because the node wasn't up when the job started). JobStarted +
// JobFinished events both need to be processed because we need to persist
// the job config of dead jobs in order for detached actors to function
// properly.
HandleJobStarted(job_id, job_data);
if (job_data.is_dead()) {
HandleJobFinished(job_id, job_data);
}
};
RAY_RETURN_NOT_OK(
gcs_client_->Jobs().AsyncSubscribeAll(job_subscribe_handler, nullptr));
periodical_runner_.RunFnPeriodically(
[this] {
DumpDebugState();
WarnResourceDeadlock();
},
RayConfig::instance().debug_dump_period_milliseconds(),
"NodeManager.deadline_timer.debug_state_dump");
uint64_t now_ms = current_time_ms();
last_metrics_recorded_at_ms_ = now_ms;
periodical_runner_.RunFnPeriodically([this] { RecordMetrics(); },
record_metrics_period_ms_,
"NodeManager.deadline_timer.record_metrics");
if (RayConfig::instance().free_objects_period_milliseconds() > 0) {
periodical_runner_.RunFnPeriodically(
[this] { local_object_manager_.FlushFreeObjects(); },
RayConfig::instance().free_objects_period_milliseconds(),
"NodeManager.deadline_timer.flush_free_objects");
}
last_resource_report_at_ms_ = now_ms;
/// If periodic asio stats print is enabled, it will print it.
const auto event_stats_print_interval_ms =
RayConfig::instance().event_stats_print_interval_ms();
if (event_stats_print_interval_ms != -1 && RayConfig::instance().event_stats()) {
periodical_runner_.RunFnPeriodically(
[this] {
std::stringstream debug_msg;
debug_msg << "Event stats:\n\n"
<< io_service_.StatsString() << "\n\n"
<< DebugString() << "\n\n";
RAY_LOG(INFO) << AppendToEachLine(debug_msg.str(), "[state-dump] ");
},
event_stats_print_interval_ms,
"NodeManager.deadline_timer.print_event_loop_stats");
}
return ray::Status::OK();
}
void NodeManager::KillWorker(std::shared_ptr<WorkerInterface> worker) {
#ifdef _WIN32
// TODO(mehrdadn): implement graceful process termination mechanism
#else
// If we're just cleaning up a single worker, allow it some time to clean
// up its state before force killing. The client socket will be closed
// and the worker struct will be freed after the timeout.
kill(worker->GetProcess().GetId(), SIGTERM);
#endif
auto retry_timer = std::make_shared<boost::asio::deadline_timer>(io_service_);
auto retry_duration = boost::posix_time::milliseconds(
RayConfig::instance().kill_worker_timeout_milliseconds());
retry_timer->expires_from_now(retry_duration);
retry_timer->async_wait([retry_timer, worker](const boost::system::error_code &error) {
RAY_LOG(DEBUG) << "Send SIGKILL to worker, pid=" << worker->GetProcess().GetId();
// Force kill worker
worker->GetProcess().Kill();
});
}
void NodeManager::DestroyWorker(std::shared_ptr<WorkerInterface> worker,
rpc::WorkerExitType disconnect_type) {
// We should disconnect the client first. Otherwise, we'll remove bundle resources
// before actual resources are returned. Subsequent disconnect request that comes
// due to worker dead will be ignored.
DisconnectClient(worker->Connection(), disconnect_type);
worker->MarkDead();
KillWorker(worker);
}
void NodeManager::HandleJobStarted(const JobID &job_id, const JobTableData &job_data) {
RAY_LOG(INFO) << "New job has started. Job id " << job_id << " Driver pid "
<< job_data.driver_pid() << " is dead: " << job_data.is_dead()
<< " driver address: " << job_data.driver_ip_address();
worker_pool_.HandleJobStarted(job_id, job_data.config());
// NOTE: Technically `HandleJobStarted` isn't idempotent because we'll
// increment the ref count multiple times. This is fine because
// `HandleJobFinisehd` will also decrement the ref count multiple times.
runtime_env_manager_.AddURIReference(job_id.Hex(),
job_data.config().runtime_env_info());
// Tasks of this job may already arrived but failed to pop a worker because the job
// config is not local yet. So we trigger dispatching again here to try to
// reschedule these tasks.
cluster_task_manager_->ScheduleAndDispatchTasks();
}
void NodeManager::HandleJobFinished(const JobID &job_id, const JobTableData &job_data) {
RAY_LOG(DEBUG) << "HandleJobFinished " << job_id;
RAY_CHECK(job_data.is_dead());
worker_pool_.HandleJobFinished(job_id);
runtime_env_manager_.RemoveURIReference(job_id.Hex());
}
void NodeManager::FillNormalTaskResourceUsage(rpc::ResourcesData &resources_data) {
auto last_heartbeat_resources = gcs_client_->NodeResources().GetLastResourceUsage();
ResourceSet normal_task_resources = cluster_task_manager_->CalcNormalTaskResources();
if (!last_heartbeat_resources->GetNormalTaskResources().IsEqual(
normal_task_resources)) {
RAY_LOG(DEBUG) << "normal_task_resources = " << normal_task_resources.ToString();
resources_data.set_resources_normal_task_changed(true);
auto &normal_task_map = *(resources_data.mutable_resources_normal_task());
normal_task_map = {normal_task_resources.GetResourceMap().begin(),
normal_task_resources.GetResourceMap().end()};
resources_data.set_resources_normal_task_timestamp(absl::GetCurrentTimeNanos());
last_heartbeat_resources->SetNormalTaskResources(normal_task_resources);
}
}
void NodeManager::FillResourceReport(rpc::ResourcesData &resources_data) {
resources_data.set_node_id(self_node_id_.Binary());
resources_data.set_node_manager_address(initial_config_.node_manager_address);
// Update local cache from gcs remote cache, this is needed when gcs restart.
// We should always keep the cache view consistent.
cluster_resource_scheduler_->UpdateLastResourceUsage(
gcs_client_->NodeResources().GetLastResourceUsage());
cluster_resource_scheduler_->FillResourceUsage(resources_data);
cluster_task_manager_->FillResourceUsage(
resources_data, gcs_client_->NodeResources().GetLastResourceUsage());
if (RayConfig::instance().gcs_actor_scheduling_enabled()) {
FillNormalTaskResourceUsage(resources_data);
}
// If plasma store is under high pressure, we should try to schedule a global gc.
bool plasma_high_pressure =
object_manager_.GetUsedMemoryPercentage() > high_plasma_storage_usage_;
if (plasma_high_pressure && global_gc_throttler_.AbleToRun()) {
TriggerGlobalGC();
}
// Set the global gc bit on the outgoing heartbeat message.
if (should_global_gc_) {
resources_data.set_should_global_gc(true);
should_global_gc_ = false;
global_gc_throttler_.RunNow();
}
// Trigger local GC if needed. This throttles the frequency of local GC calls
// to at most once per heartbeat interval.
if ((should_local_gc_ ||
(absl::GetCurrentTimeNanos() - local_gc_run_time_ns_ > local_gc_interval_ns_)) &&
local_gc_throttler_.AbleToRun()) {
DoLocalGC();
should_local_gc_ = false;
}
}
void NodeManager::DoLocalGC() {
auto all_workers = worker_pool_.GetAllRegisteredWorkers();
for (const auto &driver : worker_pool_.GetAllRegisteredDrivers()) {
all_workers.push_back(driver);
}
RAY_LOG(INFO) << "Sending Python GC request to " << all_workers.size()
<< " local workers to clean up Python cyclic references.";
for (const auto &worker : all_workers) {
rpc::LocalGCRequest request;
worker->rpc_client()->LocalGC(
request, [](const ray::Status &status, const rpc::LocalGCReply &r) {
if (!status.ok()) {
RAY_LOG(DEBUG) << "Failed to send local GC request: " << status.ToString();
}
});
}
local_gc_run_time_ns_ = absl::GetCurrentTimeNanos();
}
void NodeManager::HandleRequestObjectSpillage(
const rpc::RequestObjectSpillageRequest &request,
rpc::RequestObjectSpillageReply *reply, rpc::SendReplyCallback send_reply_callback) {
const auto &object_id = ObjectID::FromBinary(request.object_id());
RAY_LOG(DEBUG) << "Received RequestObjectSpillage for object " << object_id;
local_object_manager_.SpillObjects(
{object_id}, [object_id, reply, send_reply_callback](const ray::Status &status) {
if (status.ok()) {
RAY_LOG(DEBUG) << "Object " << object_id
<< " has been spilled, replying to owner";
reply->set_success(true);
// TODO(Clark): Add spilled URLs and spilled node ID to owner RPC reply here
// if OBOD is enabled, instead of relying on automatic raylet spilling path to
// send an extra RPC to the owner.
}
send_reply_callback(Status::OK(), nullptr, nullptr);
});
}
void NodeManager::HandleReleaseUnusedBundles(
const rpc::ReleaseUnusedBundlesRequest &request,
rpc::ReleaseUnusedBundlesReply *reply, rpc::SendReplyCallback send_reply_callback) {
RAY_LOG(DEBUG) << "Releasing unused bundles.";
std::unordered_set<BundleID, pair_hash> in_use_bundles;
for (int index = 0; index < request.bundles_in_use_size(); ++index) {
const auto &bundle_id = request.bundles_in_use(index).bundle_id();
in_use_bundles.emplace(
std::make_pair(PlacementGroupID::FromBinary(bundle_id.placement_group_id()),
bundle_id.bundle_index()));
}
// Kill all workers that are currently associated with the unused bundles.
// NOTE: We can't traverse directly with `leased_workers_`, because `DestroyWorker` will
// delete the element of `leased_workers_`. So we need to filter out
// `workers_associated_with_unused_bundles` separately.
std::vector<std::shared_ptr<WorkerInterface>> workers_associated_with_unused_bundles;
for (const auto &worker_it : leased_workers_) {
auto &worker = worker_it.second;
const auto &bundle_id = worker->GetBundleId();
// We need to filter out the workers used by placement group.
if (!bundle_id.first.IsNil() && 0 == in_use_bundles.count(bundle_id)) {
workers_associated_with_unused_bundles.emplace_back(worker);
}
}
for (const auto &worker : workers_associated_with_unused_bundles) {
RAY_LOG(DEBUG)
<< "Destroying worker since its bundle was unused. Placement group id: "
<< worker->GetBundleId().first
<< ", bundle index: " << worker->GetBundleId().second
<< ", task id: " << worker->GetAssignedTaskId()
<< ", actor id: " << worker->GetActorId()
<< ", worker id: " << worker->WorkerId();
DestroyWorker(worker, rpc::WorkerExitType::UNUSED_RESOURCE_RELEASED);
}
// Return unused bundle resources.
placement_group_resource_manager_->ReturnUnusedBundle(in_use_bundles);
send_reply_callback(Status::OK(), nullptr, nullptr);
}
// This warns users that there could be the resource deadlock. It works this way;
// - If there's no available workers for scheduling
// - But if there are still pending tasks waiting for resource acquisition
// It means the cluster might not have enough resources to be in progress.
// Note that this can print the false negative messages
// e.g., there are many actors taking up resources for a long time.
void NodeManager::WarnResourceDeadlock() {
ray::RayTask exemplar;
bool any_pending = false;
int pending_actor_creations = 0;
int pending_tasks = 0;
std::string available_resources;
// Check if any progress is being made on this raylet.
for (const auto &worker : worker_pool_.GetAllRegisteredWorkers()) {
if (worker->IsAvailableForScheduling()) {
// Progress is being made in a task, don't warn.
resource_deadlock_warned_ = 0;
return;
}
}
// Check if any tasks are blocked on resource acquisition.
if (!cluster_task_manager_->AnyPendingTasksForResourceAcquisition(
&exemplar, &any_pending, &pending_actor_creations, &pending_tasks)) {
// No pending tasks, no need to warn.
resource_deadlock_warned_ = 0;
return;
}
// Push an warning to the driver that a task is blocked trying to acquire resources.
// To avoid spurious triggers, only take action starting with the second time.
// case resource_deadlock_warned_: 0 => first time, don't do anything yet
// case resource_deadlock_warned_: 1 => second time, print a warning
// case resource_deadlock_warned_: >1 => global gc but don't print any warnings
if (any_pending && resource_deadlock_warned_++ > 0) {
// Actor references may be caught in cycles, preventing them from being deleted.
// Trigger global GC to hopefully free up resource slots.
TriggerGlobalGC();
// Suppress duplicates warning messages.
if (resource_deadlock_warned_ > 2) {
return;
}
std::ostringstream error_message;
error_message
<< "The actor or task with ID " << exemplar.GetTaskSpecification().TaskId()
<< " cannot be scheduled right now. You can ignore this message if this "
<< "Ray cluster is expected to auto-scale or if you specified a "
<< "runtime_env for this actor or task, which may take time to install. "
<< "Otherwise, this is likely due to all cluster resources being claimed "
<< "by actors. To resolve the issue, consider creating fewer actors or "
<< "increasing the resources available to this Ray cluster.\n"
<< "Required resources for this actor or task: "
<< exemplar.GetTaskSpecification().GetRequiredPlacementResources().ToString()
<< "\n"
<< "Available resources on this node: "
<< cluster_resource_scheduler_->GetLocalResourceViewString()
<< " In total there are " << pending_tasks << " pending tasks and "
<< pending_actor_creations << " pending actors on this node.";
std::string error_message_str = error_message.str();
RAY_LOG(WARNING) << error_message_str;
RAY_LOG_EVERY_MS(WARNING, 10 * 1000) << cluster_task_manager_->DebugStr();
if (RayConfig::instance().legacy_scheduler_warnings()) {
auto error_data_ptr = gcs::CreateErrorTableData(
"resource_deadlock", error_message_str, current_time_ms(),
exemplar.GetTaskSpecification().JobId());
RAY_CHECK_OK(gcs_client_->Errors().AsyncReportJobError(error_data_ptr, nullptr));
}
}
// Try scheduling tasks. Without this, if there's no more tasks coming in, deadlocked
// tasks are never be scheduled.
cluster_task_manager_->ScheduleAndDispatchTasks();
}
void NodeManager::NodeAdded(const GcsNodeInfo &node_info) {
const NodeID node_id = NodeID::FromBinary(node_info.node_id());
RAY_LOG(DEBUG) << "[NodeAdded] Received callback from node id " << node_id;
if (node_id == self_node_id_) {
return;
}
// Store address of the new node manager for rpc requests.
remote_node_manager_addresses_[node_id] =
std::make_pair(node_info.node_manager_address(), node_info.node_manager_port());
// Fetch resource info for the remote node and update cluster resource map.
RAY_CHECK_OK(gcs_client_->NodeResources().AsyncGetResources(
node_id,
[this, node_id](
Status status,
const boost::optional<gcs::NodeResourceInfoAccessor::ResourceMap> &data) {
if (data) {
ResourceSet resource_set;
for (auto &resource_entry : *data) {
resource_set.AddOrUpdateResource(resource_entry.first,
resource_entry.second->resource_capacity());
}
ResourceCreateUpdated(node_id, resource_set);
}
}));
}
void NodeManager::NodeRemoved(const NodeID &node_id) {
// TODO(swang): If we receive a notification for our own death, clean up and
// exit immediately.
RAY_LOG(DEBUG) << "[NodeRemoved] Received callback from node id " << node_id;
if (node_id == self_node_id_) {
if (!is_node_drained_) {
RAY_LOG(FATAL)
<< "[Timeout] Exiting because this node manager has mistakenly been marked as "
"dead by the "
<< "GCS: GCS didn't receive heartbeats from this node for "
<< RayConfig::instance().num_heartbeats_timeout() *
RayConfig::instance().raylet_heartbeat_period_milliseconds()
<< " ms. This is likely because the machine or raylet has become overloaded.";
} else {
// No-op since this node already starts to be drained, and GCS already knows about
// it.
RAY_LOG(INFO) << "Node is marked as dead by GCS because the node is drained.";
return;
}
}
// Below, when we remove node_id from all of these data structures, we could
// check that it is actually removed, or log a warning otherwise, but that may
// not be necessary.
// Remove the node from the resource map.
if (!cluster_resource_scheduler_->RemoveNode(node_id.Binary())) {
RAY_LOG(DEBUG) << "Received NodeRemoved callback for an unknown node: " << node_id
<< ".";
return;
}
// Remove the node manager address.
const auto node_entry = remote_node_manager_addresses_.find(node_id);
if (node_entry != remote_node_manager_addresses_.end()) {
remote_node_manager_addresses_.erase(node_entry);
}
// Notify the object directory that the node has been removed so that it
// can remove it from any cached locations.
object_directory_->HandleNodeRemoved(node_id);
// Clean up workers that were owned by processes that were on the failed
// node.
rpc::WorkerDeltaData data;
data.set_raylet_id(node_id.Binary());
HandleUnexpectedWorkerFailure(data);
}
void NodeManager::HandleUnexpectedWorkerFailure(const rpc::WorkerDeltaData &data) {
const WorkerID worker_id = WorkerID::FromBinary(data.worker_id());
const NodeID node_id = NodeID::FromBinary(data.raylet_id());
if (!worker_id.IsNil()) {
RAY_LOG(DEBUG) << "Worker " << worker_id << " failed";
failed_workers_cache_.insert(worker_id);
} else {
RAY_CHECK(!node_id.IsNil());
failed_nodes_cache_.insert(node_id);
}
// TODO(swang): Also clean up any lease requests owned by the failed worker
// from the task queues. This is only necessary for lease requests that are
// infeasible, since requests that are fulfilled will get canceled during
// dispatch.
for (const auto &pair : leased_workers_) {
auto &worker = pair.second;
const auto owner_worker_id =
WorkerID::FromBinary(worker->GetOwnerAddress().worker_id());
const auto owner_node_id = NodeID::FromBinary(worker->GetOwnerAddress().raylet_id());
RAY_LOG(DEBUG) << "Lease " << worker->WorkerId() << " owned by " << owner_worker_id;
RAY_CHECK(!owner_worker_id.IsNil() && !owner_node_id.IsNil());
if (!worker->IsDetachedActor()) {
// TODO (Alex): Cancel all pending child tasks of the tasks whose owners have failed
// because the owner could've submitted lease requests before failing.
if (!worker_id.IsNil()) {
// If the failed worker was a leased worker's owner, then kill the leased worker.
if (owner_worker_id == worker_id) {
RAY_LOG(INFO) << "Owner process " << owner_worker_id
<< " died, killing leased worker " << worker->WorkerId();
KillWorker(worker);
}
} else if (owner_node_id == node_id) {
// If the leased worker's owner was on the failed node, then kill the leased
// worker.
RAY_LOG(INFO) << "Owner node " << owner_node_id << " died, killing leased worker "
<< worker->WorkerId();
KillWorker(worker);
}
}
}
}
void NodeManager::ResourceCreateUpdated(const NodeID &node_id,
const ResourceSet &createUpdatedResources) {
RAY_LOG(DEBUG) << "[ResourceCreateUpdated] received callback from node id " << node_id
<< " with created or updated resources: "
<< createUpdatedResources.ToString() << ". Updating resource map."
<< " skip=" << (node_id == self_node_id_);
// Skip updating local node since local node always has the latest information.
// Updating local node could result in a inconsistence view in cluster resource
// scheduler which could make task hang.
if (node_id == self_node_id_) {
cluster_task_manager_->ScheduleAndDispatchTasks();
return;
}
// Update local_available_resources_ and SchedulingResources
for (const auto &resource_pair : createUpdatedResources.GetResourceMap()) {
const std::string &resource_label = resource_pair.first;
const double &new_resource_capacity = resource_pair.second;
cluster_resource_scheduler_->UpdateResourceCapacity(node_id.Binary(), resource_label,
new_resource_capacity);
}
RAY_LOG(DEBUG) << "[ResourceCreateUpdated] Updated cluster_resource_map.";
cluster_task_manager_->ScheduleAndDispatchTasks();
}
void NodeManager::ResourceDeleted(const NodeID &node_id,
const std::vector<std::string> &resource_names) {
if (RAY_LOG_ENABLED(DEBUG)) {
std::ostringstream oss;
for (auto &resource_name : resource_names) {
oss << resource_name << ", ";
}
RAY_LOG(DEBUG) << "[ResourceDeleted] received callback from node id " << node_id
<< " with deleted resources: " << oss.str()
<< ". Updating resource map. skip=" << (node_id == self_node_id_);
}
// Skip updating local node since local node always has the latest information.
// Updating local node could result in a inconsistence view in cluster resource
// scheduler which could make task hang.
if (node_id == self_node_id_) {
return;
}
// Update local_available_resources_ and SchedulingResources
for (const auto &resource_label : resource_names) {
cluster_resource_scheduler_->DeleteResource(node_id.Binary(), resource_label);
}
return;
}
void NodeManager::UpdateResourceUsage(const NodeID &node_id,
const rpc::ResourcesData &resource_data) {
if (!cluster_resource_scheduler_->UpdateNode(node_id.Binary(), resource_data)) {
RAY_LOG(INFO)
<< "[UpdateResourceUsage]: received resource usage from unknown node id "
<< node_id;
return;
}
// Trigger local GC at the next heartbeat interval.
if (resource_data.should_global_gc()) {
should_local_gc_ = true;
}
// If light resource usage report enabled, we update remote resources only when related
// resources map in heartbeat is not empty.
cluster_task_manager_->ScheduleAndDispatchTasks();
}
void NodeManager::ResourceUsageBatchReceived(
const ResourceUsageBatchData &resource_usage_batch) {
// Update load information provided by each message.
for (const auto &resource_usage : resource_usage_batch.batch()) {
const NodeID &node_id = NodeID::FromBinary(resource_usage.node_id());
if (node_id == self_node_id_) {
// Skip messages from self.
continue;
}
UpdateResourceUsage(node_id, resource_usage);
}
}
void NodeManager::ProcessNewClient(ClientConnection &client) {
// The new client is a worker, so begin listening for messages.
client.ProcessMessages();
}
void NodeManager::ProcessClientMessage(const std::shared_ptr<ClientConnection> &client,
int64_t message_type,
const uint8_t *message_data) {
auto registered_worker = worker_pool_.GetRegisteredWorker(client);
auto message_type_value = static_cast<protocol::MessageType>(message_type);
RAY_LOG(DEBUG) << "[Worker] Message "
<< protocol::EnumNameMessageType(message_type_value) << "("
<< message_type << ") from worker with PID "
<< (registered_worker
? std::to_string(registered_worker->GetProcess().GetId())
: "nil");
if (registered_worker && registered_worker->IsDead()) {
// For a worker that is marked as dead (because the job has died already),
// all the messages are ignored except DisconnectClient.
if (message_type_value != protocol::MessageType::DisconnectClient) {
// Listen for more messages.
client->ProcessMessages();
return;
}
}
switch (message_type_value) {
case protocol::MessageType::RegisterClientRequest: {
ProcessRegisterClientRequestMessage(client, message_data);
} break;
case protocol::MessageType::AnnounceWorkerPort: {
ProcessAnnounceWorkerPortMessage(client, message_data);
} break;
case protocol::MessageType::TaskDone: {
HandleWorkerAvailable(client);
} break;
case protocol::MessageType::DisconnectClient: {
ProcessDisconnectClientMessage(client, message_data);
// We don't need to receive future messages from this client,
// because it's already disconnected.
return;
} break;
case protocol::MessageType::FetchOrReconstruct: {
ProcessFetchOrReconstructMessage(client, message_data);
} break;
case protocol::MessageType::NotifyDirectCallTaskBlocked: {
ProcessDirectCallTaskBlocked(client, message_data);
} break;
case protocol::MessageType::NotifyDirectCallTaskUnblocked: {
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
HandleDirectCallTaskUnblocked(worker);
} break;
case protocol::MessageType::NotifyUnblocked: {
// TODO(ekl) this is still used from core worker even in direct call mode to
// finish up get requests.
auto message = flatbuffers::GetRoot<protocol::NotifyUnblocked>(message_data);
AsyncResolveObjectsFinish(client, from_flatbuf<TaskID>(*message->task_id()),
/*was_blocked*/ true);
} break;
case protocol::MessageType::WaitRequest: {
ProcessWaitRequestMessage(client, message_data);
} break;
case protocol::MessageType::WaitForDirectActorCallArgsRequest: {
ProcessWaitForDirectActorCallArgsRequestMessage(client, message_data);
} break;
case protocol::MessageType::PushErrorRequest: {
ProcessPushErrorRequestMessage(message_data);
} break;
case protocol::MessageType::FreeObjectsInObjectStoreRequest: {
auto message = flatbuffers::GetRoot<protocol::FreeObjectsRequest>(message_data);
std::vector<ObjectID> object_ids = from_flatbuf<ObjectID>(*message->object_ids());
// Clean up objects from the object store.
object_manager_.FreeObjects(object_ids, message->local_only());
} break;
case protocol::MessageType::SubscribePlasmaReady: {
ProcessSubscribePlasmaReady(client, message_data);
} break;
default:
RAY_LOG(FATAL) << "Received unexpected message type " << message_type;
}
// Listen for more messages.
client->ProcessMessages();
}
void NodeManager::ProcessRegisterClientRequestMessage(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
client->Register();
auto message = flatbuffers::GetRoot<protocol::RegisterClientRequest>(message_data);
Language language = static_cast<Language>(message->language());
const JobID job_id = from_flatbuf<JobID>(*message->job_id());
const int runtime_env_hash = static_cast<int>(message->runtime_env_hash());
WorkerID worker_id = from_flatbuf<WorkerID>(*message->worker_id());
pid_t pid = message->worker_pid();
pid_t worker_shim_pid = message->worker_shim_pid();
StartupToken worker_startup_token = message->startup_token();
std::string worker_ip_address = string_from_flatbuf(*message->ip_address());
// TODO(suquark): Use `WorkerType` in `common.proto` without type converting.
rpc::WorkerType worker_type = static_cast<rpc::WorkerType>(message->worker_type());
if (((worker_type != rpc::WorkerType::SPILL_WORKER &&
worker_type != rpc::WorkerType::RESTORE_WORKER)) ||
worker_type == rpc::WorkerType::DRIVER) {
RAY_CHECK(!job_id.IsNil());
} else {
RAY_CHECK(job_id.IsNil());
}
auto worker = std::dynamic_pointer_cast<WorkerInterface>(std::make_shared<Worker>(
job_id, runtime_env_hash, worker_id, language, worker_type, worker_ip_address,
client, client_call_manager_, worker_startup_token));
auto send_reply_callback = [this, client, job_id](Status status, int assigned_port) {
flatbuffers::FlatBufferBuilder fbb;
std::string serialized_job_config;
auto job_config = worker_pool_.GetJobConfig(job_id);
if (job_config != boost::none) {
serialized_job_config = (*job_config).SerializeAsString();
}
auto reply = ray::protocol::CreateRegisterClientReply(
fbb, status.ok(), fbb.CreateString(status.ToString()),
to_flatbuf(fbb, self_node_id_), assigned_port,
fbb.CreateString(serialized_job_config));
fbb.Finish(reply);
client->WriteMessageAsync(
static_cast<int64_t>(protocol::MessageType::RegisterClientReply), fbb.GetSize(),
fbb.GetBufferPointer(), [this, client](const ray::Status &status) {
if (!status.ok()) {
DisconnectClient(client);
}
});
};
if (worker_type == rpc::WorkerType::WORKER ||
worker_type == rpc::WorkerType::SPILL_WORKER ||
worker_type == rpc::WorkerType::RESTORE_WORKER) {
// Register the new worker.
auto status = worker_pool_.RegisterWorker(worker, pid, worker_shim_pid,
worker_startup_token, send_reply_callback);
if (!status.ok()) {
// If the worker failed to register to Raylet, trigger task dispatching here to
// allow new worker processes to be started (if capped by
// maximum_startup_concurrency).
cluster_task_manager_->ScheduleAndDispatchTasks();
}
} else {
// Register the new driver.
RAY_CHECK(pid >= 0);
// Don't need to set shim pid for driver
worker->SetProcess(Process::FromPid(pid));
// Compute a dummy driver task id from a given driver.
const TaskID driver_task_id = TaskID::ComputeDriverTaskId(worker_id);
worker->AssignTaskId(driver_task_id);
rpc::JobConfig job_config;
job_config.ParseFromString(message->serialized_job_config()->str());
// Send the reply callback only after registration fully completes at the GCS.
auto cb = [this, worker_ip_address, pid, job_id, job_config,
send_reply_callback = std::move(send_reply_callback)](const Status &status,
int assigned_port) {
if (status.ok()) {
auto job_data_ptr = gcs::CreateJobTableData(job_id, /*is_dead*/ false,
worker_ip_address, pid, job_config);
RAY_CHECK_OK(gcs_client_->Jobs().AsyncAdd(
job_data_ptr,
[send_reply_callback = std::move(send_reply_callback), assigned_port](
Status status) { send_reply_callback(status, assigned_port); }));
}
};
RAY_UNUSED(worker_pool_.RegisterDriver(worker, job_config, std::move(cb)));
}
}
void NodeManager::ProcessAnnounceWorkerPortMessage(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
bool is_worker = true;
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
if (worker == nullptr) {
is_worker = false;
worker = worker_pool_.GetRegisteredDriver(client);
}
RAY_CHECK(worker != nullptr) << "No worker exists for CoreWorker with client: "
<< client->DebugString();
auto message = flatbuffers::GetRoot<protocol::AnnounceWorkerPort>(message_data);
int port = message->port();
worker->Connect(port);
if (is_worker) {
worker_pool_.OnWorkerStarted(worker);
HandleWorkerAvailable(worker->Connection());
}
}
void NodeManager::HandleWorkerAvailable(const std::shared_ptr<ClientConnection> &client) {
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
HandleWorkerAvailable(worker);
}
void NodeManager::HandleWorkerAvailable(const std::shared_ptr<WorkerInterface> &worker) {
RAY_CHECK(worker);
if (worker->GetWorkerType() == rpc::WorkerType::SPILL_WORKER) {
// Return the worker to the idle pool.
worker_pool_.PushSpillWorker(worker);
return;
}
if (worker->GetWorkerType() == rpc::WorkerType::RESTORE_WORKER) {
// Return the worker to the idle pool.
worker_pool_.PushRestoreWorker(worker);
return;
}
bool worker_idle = true;
// If the worker was assigned a task, mark it as finished.
if (!worker->GetAssignedTaskId().IsNil()) {
worker_idle = FinishAssignedTask(worker);
}
if (worker_idle) {
// Return the worker to the idle pool.
worker_pool_.PushWorker(worker);
}
cluster_task_manager_->ScheduleAndDispatchTasks();
}
void NodeManager::DisconnectClient(const std::shared_ptr<ClientConnection> &client,
rpc::WorkerExitType disconnect_type,
const rpc::RayException *creation_task_exception) {
RAY_LOG(INFO) << "NodeManager::DisconnectClient, disconnect_type=" << disconnect_type
<< ", has creation task exception = "
<< (creation_task_exception != nullptr);
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
bool is_worker = false, is_driver = false;
if (worker) {
// The client is a worker.
is_worker = true;
} else {
worker = worker_pool_.GetRegisteredDriver(client);
if (worker) {
// The client is a driver.
is_driver = true;
} else {
RAY_LOG(INFO) << "Ignoring client disconnect because the client has already "
<< "been disconnected.";
return;
}
}
RAY_CHECK(!(is_worker && is_driver));
// Clean up any open ray.get or ray.wait calls that the worker made.
dependency_manager_.CancelGetRequest(worker->WorkerId());
dependency_manager_.CancelWaitRequest(worker->WorkerId());
// Erase any lease metadata.
leased_workers_.erase(worker->WorkerId());
if (creation_task_exception != nullptr) {
RAY_LOG(INFO) << "Formatted creation task exception: "
<< creation_task_exception->formatted_exception_string()
<< ", worker_id: " << worker->WorkerId();
}
// Publish the worker failure.
auto worker_failure_data_ptr = gcs::CreateWorkerFailureData(
self_node_id_, worker->WorkerId(), worker->IpAddress(), worker->Port(),
time(nullptr), disconnect_type, creation_task_exception);
RAY_CHECK_OK(
gcs_client_->Workers().AsyncReportWorkerFailure(worker_failure_data_ptr, nullptr));
if (is_worker) {
const ActorID &actor_id = worker->GetActorId();
const TaskID &task_id = worker->GetAssignedTaskId();
// If the worker was running a task or actor, clean up the task and push an
// error to the driver, unless the worker is already dead.
if ((!task_id.IsNil() || !actor_id.IsNil()) && !worker->IsDead()) {
// If the worker was an actor, it'll be cleaned by GCS.
if (actor_id.IsNil()) {
// Return the resources that were being used by this worker.
RayTask task;
cluster_task_manager_->TaskFinished(worker, &task);
}
if (worker->IsDetachedActor()) {
runtime_env_manager_.RemoveURIReference(actor_id.Hex());
}
if (disconnect_type == rpc::WorkerExitType::SYSTEM_ERROR_EXIT) {
// Push the error to driver.
const JobID &job_id = worker->GetAssignedJobId();
// TODO(rkn): Define this constant somewhere else.
std::string type = "worker_died";
std::ostringstream error_message;
error_message << "A worker died or was killed while executing a task by an "
"unexpected system "
"error. To troubleshoot the problem, check the logs for the "
"dead worker. RayTask ID: "
<< task_id << " Worker ID: " << worker->WorkerId()
<< " Node ID: " << self_node_id_
<< " Worker IP address: " << worker->IpAddress()
<< " Worker port: " << worker->Port()
<< " Worker PID: " << worker->GetProcess().GetId();
std::string error_message_str = error_message.str();
RAY_EVENT(ERROR, EL_RAY_WORKER_FAILURE)
.WithField("worker_id", worker->WorkerId().Hex())
.WithField("node_id", self_node_id_.Hex())
.WithField("job_id", worker->GetAssignedJobId().Hex())
<< error_message_str;
auto error_data_ptr =
gcs::CreateErrorTableData(type, error_message_str, current_time_ms(), job_id);
RAY_CHECK_OK(gcs_client_->Errors().AsyncReportJobError(error_data_ptr, nullptr));
}
}
// Remove the dead client from the pool and stop listening for messages.
worker_pool_.DisconnectWorker(worker, disconnect_type);
// Return the resources that were being used by this worker.
cluster_task_manager_->ReleaseWorkerResources(worker);
cluster_task_manager_->ClearWorkerBacklog(worker->WorkerId());
// Since some resources may have been released, we can try to dispatch more tasks.
cluster_task_manager_->ScheduleAndDispatchTasks();
} else if (is_driver) {
// The client is a driver.
const auto job_id = worker->GetAssignedJobId();
RAY_CHECK(!job_id.IsNil());
RAY_CHECK_OK(gcs_client_->Jobs().AsyncMarkFinished(job_id, nullptr));
worker_pool_.DisconnectDriver(worker);
RAY_LOG(INFO) << "Driver (pid=" << worker->GetProcess().GetId()
<< ") is disconnected. "
<< "job_id: " << worker->GetAssignedJobId();
if (disconnect_type == rpc::WorkerExitType::SYSTEM_ERROR_EXIT) {
RAY_EVENT(ERROR, EL_RAY_DRIVER_FAILURE)
.WithField("node_id", self_node_id_.Hex())
.WithField("job_id", worker->GetAssignedJobId().Hex())
<< "Driver " << worker->WorkerId() << " died. Address: " << worker->IpAddress()
<< ":" << worker->Port() << ", Pid: " << worker->GetProcess().GetId()
<< ", JobId: " << worker->GetAssignedJobId();
}
}
client->Close();
// TODO(rkn): Tell the object manager that this client has disconnected so
// that it can clean up the wait requests for this client. Currently I think
// these can be leaked.
}
void NodeManager::ProcessDisconnectClientMessage(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
auto message = flatbuffers::GetRoot<protocol::DisconnectClient>(message_data);
auto disconnect_type = static_cast<rpc::WorkerExitType>(message->disconnect_type());
const flatbuffers::Vector<uint8_t> *exception_pb =
message->creation_task_exception_pb();
std::unique_ptr<rpc::RayException> creation_task_exception = nullptr;
if (exception_pb != nullptr) {
creation_task_exception = std::make_unique<rpc::RayException>();
creation_task_exception->ParseFromString(std::string(
reinterpret_cast<const char *>(exception_pb->data()), exception_pb->size()));
}
DisconnectClient(client, disconnect_type, creation_task_exception.get());
}
void NodeManager::ProcessFetchOrReconstructMessage(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
auto message = flatbuffers::GetRoot<protocol::FetchOrReconstruct>(message_data);
const auto refs =
FlatbufferToObjectReference(*message->object_ids(), *message->owner_addresses());
// TODO(ekl) we should be able to remove the fetch only flag along with the legacy
// non-direct call support.
if (message->fetch_only()) {
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
if (!worker) {
worker = worker_pool_.GetRegisteredDriver(client);
}
// Fetch requests can get re-ordered after the worker finishes, so make sure to
// check the worker is still assigned a task to avoid leaks.
if (worker && !worker->GetAssignedTaskId().IsNil()) {
// This will start a fetch for the objects that gets canceled once the
// objects are local, or if the worker dies.
dependency_manager_.StartOrUpdateGetRequest(worker->WorkerId(), refs);
}
} else {
// The values are needed. Add all requested objects to the list to
// subscribe to in the task dependency manager. These objects will be
// pulled from remote node managers. If an object's owner dies, an error
// will be stored as the object's value.
const TaskID task_id = from_flatbuf<TaskID>(*message->task_id());
AsyncResolveObjects(client, refs, task_id, /*ray_get=*/true,
/*mark_worker_blocked*/ message->mark_worker_blocked());
}
}
void NodeManager::ProcessDirectCallTaskBlocked(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
auto message =
flatbuffers::GetRoot<protocol::NotifyDirectCallTaskBlocked>(message_data);
bool release_resources = message->release_resources();
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
HandleDirectCallTaskBlocked(worker, release_resources);
}
void NodeManager::ProcessWaitRequestMessage(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
// Read the data.
auto message = flatbuffers::GetRoot<protocol::WaitRequest>(message_data);
std::vector<ObjectID> object_ids = from_flatbuf<ObjectID>(*message->object_ids());
const auto refs =
FlatbufferToObjectReference(*message->object_ids(), *message->owner_addresses());
std::unordered_map<ObjectID, rpc::Address> owner_addresses;
for (const auto &ref : refs) {
owner_addresses.emplace(ObjectID::FromBinary(ref.object_id()), ref.owner_address());
}
bool resolve_objects = false;
for (auto const &object_id : object_ids) {
if (!dependency_manager_.CheckObjectLocal(object_id)) {
// At least one object requires resolution.
resolve_objects = true;
}
}
const TaskID ¤t_task_id = from_flatbuf<TaskID>(*message->task_id());
bool was_blocked = message->mark_worker_blocked();
if (resolve_objects) {
// Resolve any missing objects. This is a no-op for any objects that are
// already local. Missing objects will be pulled from remote node managers.
// If an object's owner dies, an error will be stored as the object's
// value.
AsyncResolveObjects(client, refs, current_task_id, /*ray_get=*/false,
/*mark_worker_blocked*/ was_blocked);
}
int64_t wait_ms = message->timeout();
uint64_t num_required_objects = static_cast<uint64_t>(message->num_ready_objects());
// TODO Remove in the future since it should have already be done in other place
ray::Status status = object_manager_.Wait(
object_ids, owner_addresses, wait_ms, num_required_objects,
[this, resolve_objects, was_blocked, client, current_task_id](
std::vector<ObjectID> found, std::vector<ObjectID> remaining) {
// Write the data.
flatbuffers::FlatBufferBuilder fbb;
flatbuffers::Offset<protocol::WaitReply> wait_reply = protocol::CreateWaitReply(
fbb, to_flatbuf(fbb, found), to_flatbuf(fbb, remaining));
fbb.Finish(wait_reply);
auto status =
client->WriteMessage(static_cast<int64_t>(protocol::MessageType::WaitReply),
fbb.GetSize(), fbb.GetBufferPointer());
if (status.ok()) {
// The client is unblocked now because the wait call has returned.
if (resolve_objects) {
AsyncResolveObjectsFinish(client, current_task_id, was_blocked);
}
} else {
// We failed to write to the client, so disconnect the client.
DisconnectClient(client);
}
});
RAY_CHECK_OK(status);
}
void NodeManager::ProcessWaitForDirectActorCallArgsRequestMessage(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
// Read the data.
auto message =
flatbuffers::GetRoot<protocol::WaitForDirectActorCallArgsRequest>(message_data);
std::vector<ObjectID> object_ids = from_flatbuf<ObjectID>(*message->object_ids());
int64_t tag = message->tag();
// Resolve any missing objects. This will pull the objects from remote node
// managers or store an error if the objects have failed.
const auto refs =
FlatbufferToObjectReference(*message->object_ids(), *message->owner_addresses());
std::unordered_map<ObjectID, rpc::Address> owner_addresses;
for (const auto &ref : refs) {
owner_addresses.emplace(ObjectID::FromBinary(ref.object_id()), ref.owner_address());
}
AsyncResolveObjects(client, refs, TaskID::Nil(), /*ray_get=*/false,
/*mark_worker_blocked*/ false);
// Reply to the client once a location has been found for all arguments.
// NOTE(swang): ObjectManager::Wait currently returns as soon as any location
// has been found, so the object may still be on a remote node when the
// client receives the reply.
ray::Status status = object_manager_.Wait(
object_ids, owner_addresses, -1, object_ids.size(),
[this, client, tag](std::vector<ObjectID> found, std::vector<ObjectID> remaining) {
RAY_CHECK(remaining.empty());
std::shared_ptr<WorkerInterface> worker =
worker_pool_.GetRegisteredWorker(client);
if (!worker) {
RAY_LOG(ERROR) << "Lost worker for wait request " << client;
} else {
worker->DirectActorCallArgWaitComplete(tag);
}
});
RAY_CHECK_OK(status);
}
void NodeManager::ProcessPushErrorRequestMessage(const uint8_t *message_data) {
auto message = flatbuffers::GetRoot<protocol::PushErrorRequest>(message_data);
auto const &type = string_from_flatbuf(*message->type());
auto const &error_message = string_from_flatbuf(*message->error_message());
double timestamp = message->timestamp();
JobID job_id = from_flatbuf<JobID>(*message->job_id());
auto error_data_ptr = gcs::CreateErrorTableData(type, error_message, timestamp, job_id);
RAY_CHECK_OK(gcs_client_->Errors().AsyncReportJobError(error_data_ptr, nullptr));
}
void NodeManager::HandleUpdateResourceUsage(
const rpc::UpdateResourceUsageRequest &request, rpc::UpdateResourceUsageReply *reply,
rpc::SendReplyCallback send_reply_callback) {
rpc::ResourceUsageBroadcastData resource_usage_batch;
resource_usage_batch.ParseFromString(request.serialized_resource_usage_batch());
// When next_resource_seq_no_ == 0 it means it just started.
// TODO: Fetch a snapshot from gcs for lightweight resource broadcasting
if (next_resource_seq_no_ != 0 &&
resource_usage_batch.seq_no() != next_resource_seq_no_) {
// TODO (Alex): Ideally we would be really robust, and potentially eagerly
// pull a full resource "snapshot" from gcs to make sure our state doesn't
// diverge from GCS.
RAY_LOG(WARNING)
<< "Raylet may have missed a resource broadcast. This either means that GCS has "
"restarted, the network is heavily congested and is dropping, reordering, or "
"duplicating packets. Expected seq#: "
<< next_resource_seq_no_ << ", but got: " << resource_usage_batch.seq_no() << ".";
if (resource_usage_batch.seq_no() < next_resource_seq_no_) {
RAY_LOG(WARNING) << "Discard the the resource update since local version is newer";
return;
}
}
next_resource_seq_no_ = resource_usage_batch.seq_no() + 1;
for (const auto &resource_change_or_data : resource_usage_batch.batch()) {
if (resource_change_or_data.has_data()) {
const auto &resource_usage = resource_change_or_data.data();
auto node_id = NodeID::FromBinary(resource_usage.node_id());
// Skip messages from self.
if (node_id != self_node_id_) {
UpdateResourceUsage(node_id, resource_usage);
}
} else if (resource_change_or_data.has_change()) {
const auto &resource_notification = resource_change_or_data.change();
auto node_id = NodeID::FromBinary(resource_notification.node_id());
if (resource_notification.updated_resources_size() != 0) {
ResourceSet resource_set(
MapFromProtobuf(resource_notification.updated_resources()));
ResourceCreateUpdated(node_id, resource_set);
}
if (resource_notification.deleted_resources_size() != 0) {
ResourceDeleted(node_id,
VectorFromProtobuf(resource_notification.deleted_resources()));
}
}
}
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleRequestResourceReport(
const rpc::RequestResourceReportRequest &request,
rpc::RequestResourceReportReply *reply, rpc::SendReplyCallback send_reply_callback) {
auto resources_data = reply->mutable_resources();
FillResourceReport(*resources_data);
resources_data->set_cluster_full_of_actors_detected(resource_deadlock_warned_ >= 1);
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleReportWorkerBacklog(
const rpc::ReportWorkerBacklogRequest &request, rpc::ReportWorkerBacklogReply *reply,
rpc::SendReplyCallback send_reply_callback) {
const WorkerID worker_id = WorkerID::FromBinary(request.worker_id());
cluster_task_manager_->ClearWorkerBacklog(worker_id);
std::unordered_set<SchedulingClass> seen;
for (const auto &backlog_report : request.backlog_reports()) {
const TaskSpecification resource_spec(backlog_report.resource_spec());
const SchedulingClass scheduling_class = resource_spec.GetSchedulingClass();
RAY_CHECK(seen.find(scheduling_class) == seen.end());
cluster_task_manager_->SetWorkerBacklog(scheduling_class, worker_id,
backlog_report.backlog_size());
}
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleRequestWorkerLease(const rpc::RequestWorkerLeaseRequest &request,
rpc::RequestWorkerLeaseReply *reply,
rpc::SendReplyCallback send_reply_callback) {
rpc::Task task_message;
task_message.mutable_task_spec()->CopyFrom(request.resource_spec());
RayTask task(task_message);
const bool is_actor_creation_task = task.GetTaskSpecification().IsActorCreationTask();
ActorID actor_id = ActorID::Nil();
metrics_num_task_scheduled_ += 1;
if (is_actor_creation_task) {
actor_id = task.GetTaskSpecification().ActorCreationId();
}
if (RayConfig::instance().enable_worker_prestart()) {
auto task_spec = task.GetTaskSpecification();
// We floor the available CPUs to the nearest integer to avoid starting too
// many workers when there is less than 1 CPU left. Otherwise, we could end
// up repeatedly starting the worker, then killing it because it idles for
// too long. The downside is that we will be slower to schedule tasks that
// could use a fraction of a CPU.
int64_t available_cpus =
static_cast<int64_t>(cluster_resource_scheduler_->GetLocalAvailableCpus());
worker_pool_.PrestartWorkers(task_spec, request.backlog_size(), available_cpus);
}
auto send_reply_callback_wrapper = [this, is_actor_creation_task, actor_id, reply,
send_reply_callback](
Status status, std::function<void()> success,
std::function<void()> failure) {
// If resources are not enough due to normal tasks' preemption
// for GCS based actor scheduling, return a rejection
// with normal task resource usages so GCS can update
// its resource view of this raylet.
if (reply->rejected() && is_actor_creation_task) {
ResourceSet normal_task_resources =
cluster_task_manager_->CalcNormalTaskResources();
RAY_LOG(DEBUG) << "Reject leasing as the raylet has no enough resources."
<< " actor_id = " << actor_id
<< ", normal_task_resources = " << normal_task_resources.ToString()
<< ", local_resoruce_view = "
<< cluster_resource_scheduler_->GetLocalResourceViewString();
auto resources_data = reply->mutable_resources_data();
resources_data->set_node_id(self_node_id_.Binary());
resources_data->set_resources_normal_task_changed(true);
auto &normal_task_map = *(resources_data->mutable_resources_normal_task());
normal_task_map = {normal_task_resources.GetResourceMap().begin(),
normal_task_resources.GetResourceMap().end()};
resources_data->set_resources_normal_task_timestamp(absl::GetCurrentTimeNanos());
}
send_reply_callback(status, success, failure);
};
cluster_task_manager_->QueueAndScheduleTask(task, request.grant_or_reject(), reply,
send_reply_callback_wrapper);
}
void NodeManager::HandlePrepareBundleResources(
const rpc::PrepareBundleResourcesRequest &request,
rpc::PrepareBundleResourcesReply *reply, rpc::SendReplyCallback send_reply_callback) {
auto bundle_spec = BundleSpecification(request.bundle_spec());
RAY_LOG(DEBUG) << "Request to prepare bundle resources is received, "
<< bundle_spec.DebugString();
auto prepared = placement_group_resource_manager_->PrepareBundle(bundle_spec);
reply->set_success(prepared);
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleCommitBundleResources(
const rpc::CommitBundleResourcesRequest &request,
rpc::CommitBundleResourcesReply *reply, rpc::SendReplyCallback send_reply_callback) {
auto bundle_spec = BundleSpecification(request.bundle_spec());
RAY_LOG(DEBUG) << "Request to commit bundle resources is received, "
<< bundle_spec.DebugString();
placement_group_resource_manager_->CommitBundle(bundle_spec);
send_reply_callback(Status::OK(), nullptr, nullptr);
cluster_task_manager_->ScheduleAndDispatchTasks();
}
void NodeManager::HandleCancelResourceReserve(
const rpc::CancelResourceReserveRequest &request,
rpc::CancelResourceReserveReply *reply, rpc::SendReplyCallback send_reply_callback) {
auto bundle_spec = BundleSpecification(request.bundle_spec());
RAY_LOG(DEBUG) << "Request to cancel reserved resource is received, "
<< bundle_spec.DebugString();
// Kill all workers that are currently associated with the placement group.
// NOTE: We can't traverse directly with `leased_workers_`, because `DestroyWorker` will
// delete the element of `leased_workers_`. So we need to filter out
// `workers_associated_with_pg` separately.
std::vector<std::shared_ptr<WorkerInterface>> workers_associated_with_pg;
for (const auto &worker_it : leased_workers_) {
auto &worker = worker_it.second;
if (worker->GetBundleId().first == bundle_spec.PlacementGroupId()) {
workers_associated_with_pg.emplace_back(worker);
}
}
for (const auto &worker : workers_associated_with_pg) {
RAY_LOG(DEBUG)
<< "Destroying worker since its placement group was removed. Placement group id: "
<< worker->GetBundleId().first
<< ", bundle index: " << bundle_spec.BundleId().second
<< ", task id: " << worker->GetAssignedTaskId()
<< ", actor id: " << worker->GetActorId()
<< ", worker id: " << worker->WorkerId();
DestroyWorker(worker, rpc::WorkerExitType::PLACEMENT_GROUP_REMOVED);
}
// Return bundle resources.
placement_group_resource_manager_->ReturnBundle(bundle_spec);
cluster_task_manager_->ScheduleAndDispatchTasks();
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleReturnWorker(const rpc::ReturnWorkerRequest &request,
rpc::ReturnWorkerReply *reply,
rpc::SendReplyCallback send_reply_callback) {
// Read the resource spec submitted by the client.
auto worker_id = WorkerID::FromBinary(request.worker_id());
std::shared_ptr<WorkerInterface> worker = leased_workers_[worker_id];
Status status;
leased_workers_.erase(worker_id);
if (worker) {
if (request.disconnect_worker()) {
DisconnectClient(worker->Connection());
} else {
// Handle the edge case where the worker was returned before we got the
// unblock RPC by unblocking it immediately (unblock is idempotent).
if (worker->IsBlocked()) {
HandleDirectCallTaskUnblocked(worker);
}
cluster_task_manager_->ReleaseWorkerResources(worker);
HandleWorkerAvailable(worker);
}
} else {
status = Status::Invalid("Returned worker does not exist any more");
}
send_reply_callback(status, nullptr, nullptr);
}
void NodeManager::HandleShutdownRaylet(const rpc::ShutdownRayletRequest &request,
rpc::ShutdownRayletReply *reply,
rpc::SendReplyCallback send_reply_callback) {
RAY_LOG(INFO)
<< "Shutdown RPC has received. Shutdown will happen after the RPC is replied.";
// Exit right away if it is not graceful.
if (!request.graceful()) {
std::_Exit(EXIT_SUCCESS);
}
if (is_node_drained_) {
RAY_LOG(INFO) << "Node already has received the shutdown request. The shutdown "
"request RPC is ignored.";
return;
}
auto shutdown_after_reply = []() {
// Note that the callback is posted to the io service after the shutdown GRPC request
// is replied. Otherwise, the RPC might not be replied to GCS before it shutsdown
// itself. Implementation note: When raylet is shutdown by ray stop, the CLI sends a
// sigterm. Raylet knows how to gracefully shutdown when it receives a sigterm. Here,
// we raise a sigterm to itself so that it can re-use the same graceful shutdown code
// path. The sigterm is handled in the entry point (raylet/main.cc)'s signal handler.
auto signo = SIGTERM;
RAY_LOG(INFO) << "Sending a signal to itself. shutting down. "
<< ". Signo: " << signo;
// raise return 0 if succeeds. If it fails to gracefully shutdown, it kills itself
// forcefully.
RAY_CHECK(std::raise(signo) == 0)
<< "There was a failure while sending a sigterm to itself. The process will not "
"gracefully shutdown.";
};
is_node_drained_ = true;
send_reply_callback(Status::OK(), shutdown_after_reply, shutdown_after_reply);
}
void NodeManager::HandleReleaseUnusedWorkers(
const rpc::ReleaseUnusedWorkersRequest &request,
rpc::ReleaseUnusedWorkersReply *reply, rpc::SendReplyCallback send_reply_callback) {
std::unordered_set<WorkerID> in_use_worker_ids;
for (int index = 0; index < request.worker_ids_in_use_size(); ++index) {
auto worker_id = WorkerID::FromBinary(request.worker_ids_in_use(index));
in_use_worker_ids.emplace(worker_id);
}
std::vector<WorkerID> unused_worker_ids;
for (auto &iter : leased_workers_) {
// We need to exclude workers used by common tasks.
// Because they are not used by GCS.
if (!iter.second->GetActorId().IsNil() && !in_use_worker_ids.count(iter.first)) {
unused_worker_ids.emplace_back(iter.first);
}
}
for (auto &iter : unused_worker_ids) {
leased_workers_.erase(iter);
}
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleCancelWorkerLease(const rpc::CancelWorkerLeaseRequest &request,
rpc::CancelWorkerLeaseReply *reply,
rpc::SendReplyCallback send_reply_callback) {
const TaskID task_id = TaskID::FromBinary(request.task_id());
bool canceled = cluster_task_manager_->CancelTask(task_id);
// The task cancellation failed if we did not have the task queued, since
// this means that we may not have received the task request yet. It is
// successful if we did have the task queued, since we have now replied to
// the client that requested the lease.
reply->set_success(canceled);
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::MarkObjectsAsFailed(
const ErrorType &error_type, const std::vector<rpc::ObjectReference> objects_to_fail,
const JobID &job_id) {
// TODO(swang): Ideally we should return the error directly to the client
// that needs this object instead of storing the object in plasma, which is
// not guaranteed to succeed. This avoids hanging the client if plasma is not
// reachable.
const std::string meta = std::to_string(static_cast<int>(error_type));
for (const auto &ref : objects_to_fail) {
ObjectID object_id = ObjectID::FromBinary(ref.object_id());
RAY_LOG(DEBUG) << "Mark the object id " << object_id << " as failed due to "
<< error_type;
std::shared_ptr<Buffer> data;
Status status;
status = store_client_.TryCreateImmediately(
object_id, ref.owner_address(), 0,
reinterpret_cast<const uint8_t *>(meta.c_str()), meta.length(), &data,
plasma::flatbuf::ObjectSource::ErrorStoredByRaylet);
if (status.ok()) {
status = store_client_.Seal(object_id);
}
if (!status.ok() && !status.IsObjectExists()) {
RAY_LOG(DEBUG) << "Marking plasma object failed " << object_id;
// If we failed to save the error code, log a warning and push an error message
// to the driver.
std::ostringstream stream;
stream << "A plasma error (" << status.ToString() << ") occurred while saving"
<< " error code to object " << object_id << ". Anyone who's getting this"
<< " object may hang forever.";
std::string error_message = stream.str();
RAY_LOG(ERROR) << error_message;
auto error_data_ptr =
gcs::CreateErrorTableData("task", error_message, current_time_ms(), job_id);
RAY_CHECK_OK(gcs_client_->Errors().AsyncReportJobError(error_data_ptr, nullptr));
}
}
}
void NodeManager::HandleDirectCallTaskBlocked(
const std::shared_ptr<WorkerInterface> &worker, bool release_resources) {
if (!worker || worker->IsBlocked() || worker->GetAssignedTaskId().IsNil() ||
!release_resources) {
return; // The worker may have died or is no longer processing the task.
}
cluster_task_manager_->ReleaseCpuResourcesFromUnblockedWorker(worker);
cluster_task_manager_->ScheduleAndDispatchTasks();
}
void NodeManager::HandleDirectCallTaskUnblocked(
const std::shared_ptr<WorkerInterface> &worker) {
if (!worker || worker->GetAssignedTaskId().IsNil()) {
return; // The worker may have died or is no longer processing the task.
}
// First, always release task dependencies. This ensures we don't leak resources even
// if we don't need to unblock the worker below.
dependency_manager_.CancelGetRequest(worker->WorkerId());
if (worker->IsBlocked()) {
cluster_task_manager_->ReturnCpuResourcesToBlockedWorker(worker);
cluster_task_manager_->ScheduleAndDispatchTasks();
}
}
void NodeManager::AsyncResolveObjects(
const std::shared_ptr<ClientConnection> &client,
const std::vector<rpc::ObjectReference> &required_object_refs,
const TaskID ¤t_task_id, bool ray_get, bool mark_worker_blocked) {
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
if (!worker) {
// The client is a driver. Drivers do not hold resources, so we simply mark
// the task as blocked.
worker = worker_pool_.GetRegisteredDriver(client);
}
RAY_CHECK(worker);
// Subscribe to the objects required by the task. These objects will be
// fetched and/or restarted as necessary, until the objects become local
// or are unsubscribed.
if (ray_get) {
dependency_manager_.StartOrUpdateGetRequest(worker->WorkerId(), required_object_refs);
} else {
dependency_manager_.StartOrUpdateWaitRequest(worker->WorkerId(),
required_object_refs);
}
}
void NodeManager::AsyncResolveObjectsFinish(
const std::shared_ptr<ClientConnection> &client, const TaskID ¤t_task_id,
bool was_blocked) {
std::shared_ptr<WorkerInterface> worker = worker_pool_.GetRegisteredWorker(client);
if (!worker) {
// The client is a driver. Drivers do not hold resources, so we simply
// mark the driver as unblocked.
worker = worker_pool_.GetRegisteredDriver(client);
}
RAY_CHECK(worker);
// Unsubscribe from any `ray.get` objects that the task was blocked on. Any
// fetch or reconstruction operations to make the objects local are canceled.
// `ray.wait` calls will stay active until the objects become local, or the
// task/actor that called `ray.wait` exits.
dependency_manager_.CancelGetRequest(worker->WorkerId());
// Mark the task as unblocked.
if (was_blocked) {
worker->RemoveBlockedTaskId(current_task_id);
}
}
bool NodeManager::FinishAssignedTask(const std::shared_ptr<WorkerInterface> &worker_ptr) {
// TODO (Alex): We should standardize to pass
// std::shared_ptr<WorkerInterface> instead of refs.
auto &worker = *worker_ptr;
TaskID task_id = worker.GetAssignedTaskId();
RAY_LOG(DEBUG) << "Finished task " << task_id;
RayTask task;
cluster_task_manager_->TaskFinished(worker_ptr, &task);
const auto &spec = task.GetTaskSpecification(); //
if ((spec.IsActorCreationTask())) {
// If this was an actor or actor creation task, handle the actor's new
// state.
FinishAssignedActorCreationTask(worker, task);
} else {
// If this was a non-actor task, then cancel any ray.wait calls that were
// made during the task execution.
dependency_manager_.CancelWaitRequest(worker.WorkerId());
}
// Notify the task dependency manager that this task has finished execution.
dependency_manager_.CancelGetRequest(worker.WorkerId());
if (!spec.IsActorCreationTask()) {
// Unset the worker's assigned task. We keep the assigned task ID for
// direct actor creation calls because this ID is used later if the actor
// requires objects from plasma.
worker.AssignTaskId(TaskID::Nil());
worker.SetOwnerAddress(rpc::Address());
}
// Direct actors will be assigned tasks via the core worker and therefore are
// not idle.
return !spec.IsActorCreationTask();
}
void NodeManager::FinishAssignedActorCreationTask(WorkerInterface &worker,
const RayTask &task) {
RAY_LOG(DEBUG) << "Finishing assigned actor creation task";
const TaskSpecification task_spec = task.GetTaskSpecification();
ActorID actor_id = task_spec.ActorCreationId();
// This was an actor creation task. Convert the worker to an actor.
worker.AssignActorId(actor_id);
if (task_spec.IsDetachedActor()) {
worker.MarkDetachedActor();
auto job_id = task.GetTaskSpecification().JobId();
auto job_config = worker_pool_.GetJobConfig(job_id);
RAY_CHECK(job_config);
runtime_env_manager_.AddURIReference(actor_id.Hex(),
task.GetTaskSpecification().RuntimeEnvInfo());
}
}
void NodeManager::HandleObjectLocal(const ObjectInfo &object_info) {
const ObjectID &object_id = object_info.object_id;
// Notify the task dependency manager that this object is local.
const auto ready_task_ids = dependency_manager_.HandleObjectLocal(object_id);
RAY_LOG(DEBUG) << "Object local " << object_id << ", "
<< " on " << self_node_id_ << ", " << ready_task_ids.size()
<< " tasks ready";
cluster_task_manager_->TasksUnblocked(ready_task_ids);
auto waiting_workers = absl::flat_hash_set<std::shared_ptr<WorkerInterface>>();
{
absl::MutexLock guard(&plasma_object_notification_lock_);
auto waiting = this->async_plasma_objects_notification_.extract(object_id);
if (!waiting.empty()) {
waiting_workers.swap(waiting.mapped());
}
}
rpc::PlasmaObjectReadyRequest request;
request.set_object_id(object_id.Binary());
for (auto worker : waiting_workers) {
worker->rpc_client()->PlasmaObjectReady(
request, [](Status status, const rpc::PlasmaObjectReadyReply &reply) {
if (!status.ok()) {
RAY_LOG(INFO) << "Problem with telling worker that plasma object is ready"
<< status.ToString();
}
});
}
}
bool NodeManager::IsActorCreationTask(const TaskID &task_id) {
auto actor_id = task_id.ActorId();
if (!actor_id.IsNil() && task_id == TaskID::ForActorCreationTask(actor_id)) {
// This task ID corresponds to an actor creation task.
return true;
}
return false;
}
void NodeManager::HandleObjectMissing(const ObjectID &object_id) {
// Notify the task dependency manager that this object is no longer local.
const auto waiting_task_ids = dependency_manager_.HandleObjectMissing(object_id);
std::stringstream result;
result << "Object missing " << object_id << ", "
<< " on " << self_node_id_ << ", " << waiting_task_ids.size()
<< " tasks waiting";
if (waiting_task_ids.size() > 0) {
result << ", tasks: ";
for (const auto &task_id : waiting_task_ids) {
result << task_id << " ";
}
}
RAY_LOG(DEBUG) << result.str();
}
void NodeManager::ProcessSubscribePlasmaReady(
const std::shared_ptr<ClientConnection> &client, const uint8_t *message_data) {
std::shared_ptr<WorkerInterface> associated_worker =
worker_pool_.GetRegisteredWorker(client);
if (associated_worker == nullptr) {
associated_worker = worker_pool_.GetRegisteredDriver(client);
}
RAY_CHECK(associated_worker != nullptr)
<< "No worker exists for CoreWorker with client: " << client->DebugString();
auto message = flatbuffers::GetRoot<protocol::SubscribePlasmaReady>(message_data);
ObjectID id = from_flatbuf<ObjectID>(*message->object_id());
if (dependency_manager_.CheckObjectLocal(id)) {
// Object is already local, so we directly fire the callback to tell the core worker
// that the plasma object is ready.
rpc::PlasmaObjectReadyRequest request;
request.set_object_id(id.Binary());
RAY_LOG(DEBUG) << "Object " << id << " is already local, firing callback directly.";
associated_worker->rpc_client()->PlasmaObjectReady(
request, [](Status status, const rpc::PlasmaObjectReadyReply &reply) {
if (!status.ok()) {
RAY_LOG(INFO) << "Problem with telling worker that plasma object is ready"
<< status.ToString();
}
});
} else {
// The object is not local, so we are subscribing to pull and wait for the objects.
std::vector<rpc::ObjectReference> refs = {FlatbufferToSingleObjectReference(
*message->object_id(), *message->owner_address())};
// NOTE(simon): This call will issue a pull request to remote workers and make sure
// the object will be local.
// 1. We currently do not allow user to cancel this call. The object will be pulled
// even if the `await object_ref` is cancelled.
// 2. We currently do not handle edge cases with object eviction where the object
// is local at this time but when the core worker was notified, the object is
// is evicted. The core worker should be able to handle evicted object in this
// case.
dependency_manager_.StartOrUpdateWaitRequest(associated_worker->WorkerId(), refs);
// Add this worker to the listeners for the object ID.
{
absl::MutexLock guard(&plasma_object_notification_lock_);
async_plasma_objects_notification_[id].insert(associated_worker);
}
}
}
void NodeManager::DumpDebugState() const {
std::fstream fs;
fs.open(initial_config_.log_dir + "/debug_state.txt",
std::fstream::out | std::fstream::trunc);
fs << DebugString();
fs.close();
}
const NodeManagerConfig &NodeManager::GetInitialConfig() const { return initial_config_; }
std::string NodeManager::DebugString() const {
std::stringstream result;
uint64_t now_ms = current_time_ms();
result << "NodeManager:";
result << "\nInitialConfigResources: " << initial_config_.resource_config.ToString();
if (cluster_task_manager_ != nullptr) {
result << "\nClusterTaskManager:\n";
result << cluster_task_manager_->DebugStr();
}
result << "\nClusterResources:";
result << "\n" << local_object_manager_.DebugString();
result << "\n" << object_manager_.DebugString();
result << "\n" << gcs_client_->DebugString();
result << "\n" << worker_pool_.DebugString();
result << "\n" << dependency_manager_.DebugString();
result << "\n" << core_worker_subscriber_->DebugString();
{
absl::MutexLock guard(&plasma_object_notification_lock_);
result << "\nnum async plasma notifications: "
<< async_plasma_objects_notification_.size();
}
result << "\nRemote node managers: ";
for (const auto &entry : remote_node_manager_addresses_) {
result << "\n" << entry.first;
}
// Event stats.
result << "\nEvent stats:" << io_service_.StatsString();
result << "\nDebugString() time ms: " << (current_time_ms() - now_ms);
return result.str();
}
// Summarizes a Census view and tag values into a compact string, e.g.,
// "Tag1:Value1,Tag2:Value2,Tag3:Value3".
std::string compact_tag_string(const opencensus::stats::ViewDescriptor &view,
const std::vector<std::string> &values) {
std::stringstream result;
const auto &keys = view.columns();
for (size_t i = 0; i < values.size(); i++) {
result << keys[i].name() << ":" << values[i];
if (i < values.size() - 1) {
result << ",";
}
}
return result.str();
}
bool NodeManager::GetObjectsFromPlasma(const std::vector<ObjectID> &object_ids,
std::vector<std::unique_ptr<RayObject>> *results) {
// Pin the objects in plasma by getting them and holding a reference to
// the returned buffer.
// NOTE: the caller must ensure that the objects already exist in plasma before
// sending a PinObjectIDs request.
std::vector<plasma::ObjectBuffer> plasma_results;
// TODO(swang): This `Get` has a timeout of 0, so the plasma store will not
// block when serving the request. However, if the plasma store is under
// heavy load, then this request can still block the NodeManager event loop
// since we must wait for the plasma store's reply. We should consider using
// an `AsyncGet` instead.
if (!store_client_
.Get(object_ids, /*timeout_ms=*/0, &plasma_results, /*is_from_worker=*/false)
.ok()) {
return false;
}
for (const auto &plasma_result : plasma_results) {
if (plasma_result.data == nullptr) {
results->push_back(nullptr);
} else {
results->emplace_back(std::unique_ptr<RayObject>(
new RayObject(plasma_result.data, plasma_result.metadata, {})));
}
}
return true;
}
void NodeManager::HandlePinObjectIDs(const rpc::PinObjectIDsRequest &request,
rpc::PinObjectIDsReply *reply,
rpc::SendReplyCallback send_reply_callback) {
std::vector<ObjectID> object_ids;
object_ids.reserve(request.object_ids_size());
const auto &owner_address = request.owner_address();
for (const auto &object_id_binary : request.object_ids()) {
object_ids.push_back(ObjectID::FromBinary(object_id_binary));
}
std::vector<std::unique_ptr<RayObject>> results;
if (!GetObjectsFromPlasma(object_ids, &results)) {
RAY_LOG(WARNING)
<< "Failed to get objects that should have been in the object store. These "
"objects may have been evicted while there are still references in scope.";
// TODO(suquark): Maybe "Status::ObjectNotFound" is more accurate here.
send_reply_callback(Status::Invalid("Failed to get objects."), nullptr, nullptr);
return;
}
local_object_manager_.PinObjects(object_ids, std::move(results), owner_address);
// Wait for the object to be freed by the owner, which keeps the ref count.
local_object_manager_.WaitForObjectFree(owner_address, object_ids);
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleGetSystemConfig(const rpc::GetSystemConfigRequest &request,
rpc::GetSystemConfigReply *reply,
rpc::SendReplyCallback send_reply_callback) {
reply->set_system_config(initial_config_.raylet_config);
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleGetGcsServerAddress(
const rpc::GetGcsServerAddressRequest &request, rpc::GetGcsServerAddressReply *reply,
rpc::SendReplyCallback send_reply_callback) {
auto address = gcs_client_->GetGcsServerAddress();
reply->set_ip(address.first);
reply->set_port(address.second);
send_reply_callback(Status::OK(), nullptr, nullptr);
}
void NodeManager::HandleGetNodeStats(const rpc::GetNodeStatsRequest &node_stats_request,
rpc::GetNodeStatsReply *reply,
rpc::SendReplyCallback send_reply_callback) {
cluster_task_manager_->FillPendingActorInfo(reply);
// Report object spilling stats.
local_object_manager_.FillObjectSpillingStats(reply);
// Report object store stats.
object_manager_.FillObjectStoreStats(reply);
// Ensure we never report an empty set of metrics.
if (!recorded_metrics_) {
RecordMetrics();
RAY_CHECK(recorded_metrics_);
}
for (const auto &view : opencensus::stats::StatsExporter::GetViewData()) {
auto view_data = reply->add_view_data();
view_data->set_view_name(view.first.name());
if (view.second.type() == opencensus::stats::ViewData::Type::kInt64) {
for (const auto &measure : view.second.int_data()) {
auto measure_data = view_data->add_measures();
measure_data->set_tags(compact_tag_string(view.first, measure.first));
measure_data->set_int_value(measure.second);
}
} else if (view.second.type() == opencensus::stats::ViewData::Type::kDouble) {
for (const auto &measure : view.second.double_data()) {
auto measure_data = view_data->add_measures();
measure_data->set_tags(compact_tag_string(view.first, measure.first));
measure_data->set_double_value(measure.second);
}
} else {
RAY_CHECK(view.second.type() == opencensus::stats::ViewData::Type::kDistribution);
for (const auto &measure : view.second.distribution_data()) {
auto measure_data = view_data->add_measures();
measure_data->set_tags(compact_tag_string(view.first, measure.first));
measure_data->set_distribution_min(measure.second.min());
measure_data->set_distribution_mean(measure.second.mean());
measure_data->set_distribution_max(measure.second.max());
measure_data->set_distribution_count(measure.second.count());
for (const auto &bound : measure.second.bucket_boundaries().lower_boundaries()) {
measure_data->add_distribution_bucket_boundaries(bound);
}
for (const auto &count : measure.second.bucket_counts()) {
measure_data->add_distribution_bucket_counts(count);
}
}
}
}
// As a result of the HandleGetNodeStats, we are collecting information from all
// workers on this node. This is done by calling GetCoreWorkerStats on each worker. In
// order to send up-to-date information back, we wait until all workers have replied,
// and return the information from HandleNodesStatsRequest. The caller of
// HandleGetNodeStats should set a timeout so that the rpc finishes even if not all
// workers have replied.
auto all_workers = worker_pool_.GetAllRegisteredWorkers(/* filter_dead_worker */ true);
absl::flat_hash_set<WorkerID> driver_ids;
for (auto driver :
worker_pool_.GetAllRegisteredDrivers(/* filter_dead_driver */ true)) {
all_workers.push_back(driver);
driver_ids.insert(driver->WorkerId());
}
if (all_workers.empty()) {
send_reply_callback(Status::OK(), nullptr, nullptr);
return;
}
for (const auto &worker : all_workers) {
if (worker->IsDead()) {
continue;
}
rpc::GetCoreWorkerStatsRequest request;
request.set_intended_worker_id(worker->WorkerId().Binary());
request.set_include_memory_info(node_stats_request.include_memory_info());
worker->rpc_client()->GetCoreWorkerStats(
request, [reply, worker, all_workers, driver_ids, send_reply_callback](
const ray::Status &status, const rpc::GetCoreWorkerStatsReply &r) {
reply->add_core_workers_stats()->MergeFrom(r.core_worker_stats());
reply->set_num_workers(reply->num_workers() + 1);
if (reply->num_workers() == all_workers.size()) {
send_reply_callback(Status::OK(), nullptr, nullptr);
}
});
}
}
rpc::ObjectStoreStats AccumulateStoreStats(
std::vector<rpc::GetNodeStatsReply> node_stats) {
rpc::ObjectStoreStats store_stats;
for (const auto &reply : node_stats) {
auto cur_store = reply.store_stats();
// Use max aggregation for time, since the nodes are spilling concurrently.
store_stats.set_spill_time_total_s(
std::max(store_stats.spill_time_total_s(), cur_store.spill_time_total_s()));
store_stats.set_restore_time_total_s(
std::max(store_stats.restore_time_total_s(), cur_store.restore_time_total_s()));
// Use sum aggregation for the rest of the metrics.
store_stats.set_spilled_bytes_total(store_stats.spilled_bytes_total() +
cur_store.spilled_bytes_total());
store_stats.set_spilled_objects_total(store_stats.spilled_objects_total() +
cur_store.spilled_objects_total());
store_stats.set_restored_bytes_total(store_stats.restored_bytes_total() +
cur_store.restored_bytes_total());
store_stats.set_restored_objects_total(store_stats.restored_objects_total() +
cur_store.restored_objects_total());
store_stats.set_object_store_bytes_used(store_stats.object_store_bytes_used() +
cur_store.object_store_bytes_used());
store_stats.set_object_store_bytes_avail(store_stats.object_store_bytes_avail() +
cur_store.object_store_bytes_avail());
store_stats.set_object_store_bytes_primary_copy(
store_stats.object_store_bytes_primary_copy() +
cur_store.object_store_bytes_primary_copy());
store_stats.set_object_store_bytes_fallback(
store_stats.object_store_bytes_fallback() +
cur_store.object_store_bytes_fallback());
store_stats.set_num_local_objects(store_stats.num_local_objects() +
cur_store.num_local_objects());
store_stats.set_consumed_bytes(store_stats.consumed_bytes() +
cur_store.consumed_bytes());
if (cur_store.object_pulls_queued()) {
store_stats.set_object_pulls_queued(true);
}
}
return store_stats;
}
std::string FormatMemoryInfo(std::vector<rpc::GetNodeStatsReply> node_stats) {
// First pass to compute object sizes.
absl::flat_hash_map<ObjectID, int64_t> object_sizes;
for (const auto &reply : node_stats) {
for (const auto &core_worker_stats : reply.core_workers_stats()) {
for (const auto &object_ref : core_worker_stats.object_refs()) {
auto obj_id = ObjectID::FromBinary(object_ref.object_id());
if (object_ref.object_size() > 0) {
object_sizes[obj_id] = object_ref.object_size();
}
}
}
}
std::ostringstream builder;
builder
<< "----------------------------------------------------------------------------"
"-----------------------------------------\n";
builder
<< " Object ID Reference Type "
" Object Size "
" Reference Creation Site\n";
builder
<< "============================================================================"
"=========================================\n";
// Second pass builds the summary string for each node.
for (const auto &reply : node_stats) {
for (const auto &core_worker_stats : reply.core_workers_stats()) {
bool pid_printed = false;
for (const auto &object_ref : core_worker_stats.object_refs()) {
auto obj_id = ObjectID::FromBinary(object_ref.object_id());
if (!object_ref.pinned_in_memory() && object_ref.local_ref_count() == 0 &&
object_ref.submitted_task_ref_count() == 0 &&
object_ref.contained_in_owned_size() == 0) {
continue;
}
if (obj_id.IsNil()) {
continue;
}
if (!pid_printed) {
if (core_worker_stats.worker_type() == rpc::WorkerType::DRIVER) {
builder << "; driver pid=" << core_worker_stats.pid() << "\n";
} else {
builder << "; worker pid=" << core_worker_stats.pid() << "\n";
}
pid_printed = true;
}
builder << obj_id.Hex() << " ";
// TODO(ekl) we could convey more information about the reference status.
if (object_ref.pinned_in_memory()) {
builder << "PINNED_IN_MEMORY ";
} else if (object_ref.submitted_task_ref_count() > 0) {
builder << "USED_BY_PENDING_TASK ";
} else if (object_ref.local_ref_count() > 0) {
builder << "LOCAL_REFERENCE ";
} else if (object_ref.contained_in_owned_size() > 0) {
builder << "CAPTURED_IN_OBJECT ";
} else {
builder << "UNKNOWN_STATUS ";
}
builder << std::right << std::setfill(' ') << std::setw(11);
if (object_sizes.contains(obj_id)) {
builder << object_sizes[obj_id];
} else {
builder << " ?";
}
builder << " " << object_ref.call_site();
builder << "\n";
}
}
}
builder
<< "----------------------------------------------------------------------------"
"-----------------------------------------\n";
return builder.str();
}
void NodeManager::HandleFormatGlobalMemoryInfo(
const rpc::FormatGlobalMemoryInfoRequest &request,
rpc::FormatGlobalMemoryInfoReply *reply, rpc::SendReplyCallback send_reply_callback) {
auto replies = std::make_shared<std::vector<rpc::GetNodeStatsReply>>();
auto local_request = std::make_shared<rpc::GetNodeStatsRequest>();
auto local_reply = std::make_shared<rpc::GetNodeStatsReply>();
bool include_memory_info = request.include_memory_info();
local_request->set_include_memory_info(include_memory_info);
unsigned int num_nodes = remote_node_manager_addresses_.size() + 1;
rpc::GetNodeStatsRequest stats_req;
stats_req.set_include_memory_info(include_memory_info);
auto store_reply = [replies, reply, num_nodes, send_reply_callback,
include_memory_info](const rpc::GetNodeStatsReply &local_reply) {
replies->push_back(local_reply);
if (replies->size() >= num_nodes) {
if (include_memory_info) {
reply->set_memory_summary(FormatMemoryInfo(*replies));
}
reply->mutable_store_stats()->CopyFrom(AccumulateStoreStats(*replies));
send_reply_callback(Status::OK(), nullptr, nullptr);
}
};
// Fetch from remote nodes.
for (const auto &entry : remote_node_manager_addresses_) {
auto client = std::make_unique<rpc::NodeManagerClient>(
entry.second.first, entry.second.second, client_call_manager_);
client->GetNodeStats(
stats_req, [replies, store_reply](const ray::Status &status,
const rpc::GetNodeStatsReply &r) {
if (!status.ok()) {
RAY_LOG(ERROR) << "Failed to get remote node stats: " << status.ToString();
}
store_reply(r);
});
}
// Fetch from the local node.
HandleGetNodeStats(
stats_req, local_reply.get(),
[local_reply, store_reply](Status status, std::function<void()> success,
std::function<void()> failure) mutable {
store_reply(*local_reply);
});
}
void NodeManager::HandleGlobalGC(const rpc::GlobalGCRequest &request,
rpc::GlobalGCReply *reply,
rpc::SendReplyCallback send_reply_callback) {
TriggerGlobalGC();
}
void NodeManager::TriggerGlobalGC() {
should_global_gc_ = true;
// We won't see our own request, so trigger local GC in the next heartbeat.
should_local_gc_ = true;
}
void NodeManager::Stop() {
object_manager_.Stop();
if (heartbeat_sender_) {
heartbeat_sender_.reset();
}
}
void NodeManager::RecordMetrics() {
recorded_metrics_ = true;
if (stats::StatsConfig::instance().IsStatsDisabled()) {
return;
}
cluster_task_manager_->RecordMetrics();
object_manager_.RecordMetrics();
local_object_manager_.RecordObjectSpillingStats();
uint64_t current_time = current_time_ms();
uint64_t duration_ms = current_time - last_metrics_recorded_at_ms_;
last_metrics_recorded_at_ms_ = current_time;
object_directory_->RecordMetrics(duration_ms);
}
void NodeManager::PublishInfeasibleTaskError(const RayTask &task) const {
bool suppress_warning = false;
if (!task.GetTaskSpecification().PlacementGroupBundleId().first.IsNil()) {
// If the task is part of a placement group, do nothing. If necessary, the infeasible
// warning should come from the placement group scheduling, not the task scheduling.
suppress_warning = true;
}
// Push a warning to the task's driver that this task is currently infeasible.
if (!suppress_warning) {
// TODO(rkn): Define this constant somewhere else.
std::string type = "infeasible_task";
std::ostringstream error_message;
error_message
<< "The actor or task with ID " << task.GetTaskSpecification().TaskId()
<< " cannot be scheduled right now. It requires "
<< task.GetTaskSpecification().GetRequiredPlacementResources().ToString()
<< " for placement, however the cluster currently cannot provide the requested "
"resources. The required resources may be added as autoscaling takes place "
"or placement groups are scheduled. Otherwise, consider reducing the "
"resource requirements of the task.";
std::string error_message_str = error_message.str();
RAY_LOG(WARNING) << error_message_str;
if (RayConfig::instance().legacy_scheduler_warnings()) {
auto error_data_ptr =
gcs::CreateErrorTableData(type, error_message_str, current_time_ms(),
task.GetTaskSpecification().JobId());
RAY_CHECK_OK(gcs_client_->Errors().AsyncReportJobError(error_data_ptr, nullptr));
}
}
}
} // namespace raylet
} // namespace ray
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/basegl/processors/shadercomponentprocessorbase.h>
#include <inviwo/core/util/rendercontext.h>
#include <modules/opengl/volume/volumegl.h>
#include <modules/opengl/texture/textureunit.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/shader/shadermanager.h>
#include <modules/basegl/shadercomponents/shadercomponent.h>
namespace inviwo {
ShaderComponentProcessorBase::ShaderComponentProcessorBase(
const std::vector<std::pair<ShaderType, std::shared_ptr<const ShaderResource>>>&
shaderResources,
std::string_view identifier, std::string_view displayName)
: Processor(identifier, displayName)
, outport_("outport")
, shader_{shaderResources, Shader::Build::No}
, components_{} {
shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); });
addPort(outport_, "images");
}
ShaderComponentProcessorBase::~ShaderComponentProcessorBase() = default;
void ShaderComponentProcessorBase::registerComponent(ShaderComponent& component) {
components_.push_back(&component);
for (const auto& [port, group] : component.getInports()) {
addPort(*port, group);
}
for (auto prop : component.getProperties()) {
addProperty(*prop);
}
}
void ShaderComponentProcessorBase::initializeResources() {
for (auto* comp : components_) {
try {
comp->initializeResources(shader_);
} catch (...) {
handleError("initializeResources", comp->getName());
}
}
auto* fso = shader_.getFragmentShaderObject();
fso->clearOutDeclarations();
fso->clearSegments();
for (auto* comp : components_) {
try {
for (auto&& segment : comp->getSegments()) {
fso->addSegment(ShaderSegment{segment.placeholder, std::string(comp->getName()),
segment.snippet, segment.priority});
}
} catch (...) {
handleError("adding shader segments", comp->getName());
}
}
shader_.build();
}
void ShaderComponentProcessorBase::process() {
utilgl::activateAndClearTarget(outport_);
shader_.activate();
TextureUnitContainer units;
utilgl::setUniforms(shader_, outport_);
for (auto& comp : components_) {
try {
comp->process(shader_, units);
} catch (...) {
handleError("processing", comp->getName());
}
}
utilgl::singleDrawImagePlaneRect();
shader_.deactivate();
utilgl::deactivateCurrentTarget();
}
void ShaderComponentProcessorBase::handleError(std::string_view action,
std::string_view componentName) const {
try {
throw;
} catch (Exception& e) {
throw Exception{fmt::format("Error while {} in shader component: {}, message: {}", action,
componentName, e.getMessage()),
e.getContext()};
} catch (fmt::format_error& e) {
throw Exception{fmt::format("Error while {} in shader component: {}, fmt::format_error: {}",
action, componentName, e.what()),
IVW_CONTEXT};
} catch (std::exception& e) {
throw Exception{fmt::format("Error while {} in shader component: {}, message: {}", action,
componentName, e.what()),
IVW_CONTEXT};
}
}
} // namespace inviwo
|
#include <iostream>
#include <vector>
#include <fcntl.h>
#include <io.h>
#include <conio.h>
#include <windows.h>
// headers?
using namespace std;
void gotoxy(int x, int y);
void pushX(int num);
void setLanguage();
void printTitleScreen();
void characterSelect();
void setScreenResolution(int x, int y);
void printLine(int x);
void printCharacter(int n);
void clearEntity();
void clearLine();
// Game config
string language;
bool charUnlocked_1 = true;
bool charUnlocked_2 = true;
struct character {
string name;
string hp;
string mana;
string attack;
string def;
};
int main() {
setScreenResolution(960, 720);
setlocale(LC_ALL, "spanish");
//setLanguage();
//printTitleScreen();
characterSelect();
}
// Utility functions
void gotoxy(int x, int y) {
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
void clearEntity() {
for (int i = 3; i < 25; i++) {
gotoxy(0, i);
cout << " ";
}
}
void clearTextBox() {
}
void pushX(int num) {
for (int i = 0; i < num; i++)
cout << " ";
}
// Game functions
void setScreenResolution(int x, int y) {
HWND hwnd = GetConsoleWindow();
if (hwnd != NULL) { MoveWindow(hwnd, 1000, 500, x, y, TRUE); }
}
void printTitleScreen() {
int option = 0;
bool over = false;
int start = 0;
for (int j = 0; j < 9; j++) {
system("CLS");
pushX(j);
cout << "____ __ ___ ___ ____ __ __ __ __ ___ __ __ ___ __ ___ ____ ___ __ __ __" << endl;
pushX(j);
cout << "|| \\\\ || ||\\\\//|| || ||\\ || (( \\ || // \\\\ ||\\ || // \\\\ || // || \\\\ // \\\\ (( \\ || ||" << endl;
pushX(j);
cout << "|| )) || || \\/ || ||== ||\\\\|| \\\\ || (( )) ||\\\\|| ||=|| || (( ||_// ||=|| \\\\ ||==||" << endl;
pushX(j);
cout << "||_// || || || ||___ || \\|| \\_)) || \\\\_// || \\|| || || ||__| \\\\__ || \\\\ || || \\_)) || ||" << endl;
Sleep(100);
}
}
void setLanguage() {
int option = 0;
int start = 0;
int dash_x = 35;
int dash_y = 12;
bool gameover = false;
language = "English";
gotoxy(37, 10);
cout << " ,- -. .-,--. . . ";
gotoxy(37, 11);
cout << " / , \\ `\\__ ,-. ,-. | . ,-. |-. ";
gotoxy(39, 12);
cout << " | '| | / | | | | | | `-. | | ";
gotoxy(37, 13);
cout << " \\ ` / '`--' ' ' `-| `' ' `-' ' ' ";
gotoxy(37, 14);
cout << " `- -' ,| ";
gotoxy(37, 15);
cout << " `'";
gotoxy(37, 19);
cout << " ,- -. .-,--. ~ . ";
gotoxy(37, 20);
cout << " / ,-, \\ `\\__ ,-. ,-. ,-. ,-. ,-. | ";
gotoxy(39, 21);
cout << " | / | / `-. | | ,-| | | | | | ";
gotoxy(37, 22);
cout << " \\ '-` / '`--' `-' |-' `-^ ' ' `-' `' ";
gotoxy(37, 23);
cout << " `- -' | ";
gotoxy(37, 24);
cout << " '";
while (gameover != true) {
if (start == 0) {
gotoxy(dash_x, dash_y);
cout << "--";
start = 1;
}
if (_kbhit()) {
char tecla = _getch();
if (tecla == 'w') {
gotoxy(dash_x, dash_y);
cout << " ";
dash_y = 12;
gotoxy(dash_x, dash_y);
cout << "--";
language = "English";
}
if (tecla == 's') {
gotoxy(dash_x, dash_y);
cout << " ";
dash_y = 21;
gotoxy(dash_x, dash_y);
cout << "--";
language = "Español";;
}
if (tecla == 'k') {
gameover = true;
}
}
}
}
void clearLine() {
gotoxy(0, 1);
cout << " ";
gotoxy(0, 1);
}
void characterSelect() {
system("cls");
int n = 0;
setScreenResolution(838, 600);
printLine(100);
pushX(45);
cout << "KNIGHT" << endl;
printLine(100);
bool end = false;
printCharacter(n);
gotoxy(0, 24);
printLine(100);
cout << "Knight Lore";
gotoxy(0, 33);
printLine(100);
while (end != true) {
if (_kbhit()) {
char tecla = _getch();
if (tecla == 'd') {
n++;
if (charUnlocked_1 != true && n == 2) {
n = 1;
if (charUnlocked_2 == true) {
n = 3;
}
}
if (n > 3) {
n = 3;
}
cout << n;
}
if (tecla == 'a') {
n--;
if (charUnlocked_1 != true && n == 2) {
n = 1;
}
if (n < 0){
n = 0;
}
cout << n;
}
if (tecla == 'k') {
end = true;
}
clearLine();
pushX(45);
switch (n) {
case 0:
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << "KNIGHT";
break;
case 1:
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
cout << "WIZARD";
break;
case 2:
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
cout << "SAMURAI";
break;
case 3:
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 14);
cout << "HOLD";
break;
default:
cout << "???";
break;
}
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
clearEntity();
printCharacter(n);
gotoxy(0, 24);
printLine(100);
if (n == 0) {
cout << "Knight Lore";
} else if (n == 1) {
cout << "Wizard Lore";
}
else if (n == 2) {
cout << "Samurai Lore";
}
gotoxy(0, 33);
printLine(100);
}
}
}
void printLine(int x) {
x -= 2;
cout << "+";
for (int i = 0; i < x; i++) {
cout << "-";
}
cout << "+" << endl;
}
void printCharacter(int n) {
gotoxy(0, 3);
int x = 0;
if (n == 0) {
x = 37;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
pushX(x);
cout << " _,." << endl;
pushX(x);
cout << " ,` -.)" << endl;
pushX(x);
cout << " ( _/-\\\\-._" << endl;
pushX(x);
cout << " /,|`--._,-^| ," << endl;
pushX(x);
cout << " \\_| |`-._/|| ,'|" << endl;
pushX(x);
cout << " | `-, / | / /" << endl;
pushX(x);
cout << " | || | / /" << endl;
pushX(x);
cout << " `r-._||/ __ / / " << endl;
pushX(x);
cout << " __,-<_ )`-/ `./ / " << endl;
pushX(x);
cout << "' \\ `---' \\ / / " << endl;
pushX(x);
cout << " | |./ / " << endl;
pushX(x);
cout << " / // / " << endl;
pushX(x);
cout << "\\_/' \\ |/ / " << endl;
pushX(x);
cout << " | | _,^-'/ / " << endl;
pushX(x);
cout << " | , `` (\\/ /_" << endl;
pushX(x);
cout << " \\,.->._ \\X-=/^" << endl;
pushX(x);
cout << " ( / `-._//^` " << endl;
pushX(x);
cout << " `Y-.____(__}" << endl;
pushX(x);
cout << " | {__)" << endl;
pushX(x);
cout << " ()" << endl;
}
else if (n == 1) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
x = 26;
pushX(x);
cout << " / |" << endl;
pushX(x);
cout << " / |" << endl;
pushX(x);
cout << " / |" << endl;
pushX(x);
cout << " / |" << endl;
pushX(x);
cout << " ___,' |" << endl;
pushX(x);
cout << " < -' :" << endl;
pushX(x);
cout << " `-.__..--'``-,_\\_" << endl;
pushX(x);
cout << " | / ` :,.)_`>" << endl;
pushX(x);
cout << " :/ ` ||/)" << endl;
pushX(x);
cout << " (_.).__,-` |\\" << endl;
pushX(x);
cout << " /( `.`` `| :" << endl;
pushX(x);
cout << " \\'`-.) ` ; ;" << endl;
pushX(x);
cout << " | ` /-<" << endl;
pushX(x);
cout << " | ` / `." << endl;
pushX(x);
cout << " ,-_-..____ /| ` :__..-'\\" << endl;
pushX(x);
cout << "/,'-.__\\\\ ``-./ :` ; \\" << endl;
pushX(x);
cout << "`\\ `\\ `\\\\ \\ : ( ` / , `. \\" << endl;
pushX(x);
cout << " \\` \\ \\\\ | | ` : : .\\ \\" << endl;
pushX(x);
cout << " \\ `\\_ )) : ; | | ): :" << endl;
pushX(x);
cout << " (`-.-'\\ || |\\ \\ ` ; ; | |" << endl;
pushX(x);
cout << " \\-_ `;;._ ( ` / /_ | |" << endl;
pushX(x);
cout << " `-.-.// ,'`-._\\__/_,' ; |" << endl;
pushX(x);
}
else if (n == 2) {
x = 26;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
pushX(x);
cout << " \\ \\" << endl;
pushX(x);
cout << " \\.\\" << endl;
pushX(x);
cout << " \\.\\" << endl;
pushX(x);
cout << " \\.\\ " << endl;
pushX(x);
cout << " _ \\.\\/)" << endl;
pushX(x);
cout << " _ _-' ')__ (\\.\\/)" << endl;
pushX(x);
cout << " / / \\.'`'-\\/)\\\\" << endl;
pushX(x);
cout << " \\__ ,.-'(_ Y (_\\.\\)" << endl;
pushX(x);
cout << " / < ,\\ \\ ,\\\\.\\\\" << endl;
pushX(x);
cout << " \\_ \\ _. /y(_| : |\\.\\|" << endl;
pushX(x);
cout << " _\\_\\\\ | : | \\.\\" << endl;
pushX(x);
cout << " ( `'-._>/ ) \\| \\.\\" << endl;
pushX(x);
cout << " \\ `:=. (\\ \\.\\" << endl;
pushX(x);
cout << " \\_ ( `--._)`--'\\.\\=7" << endl;
pushX(x);
cout << " _/|\\_ \\-._ `-:_ /```-3 " << endl;
pushX(x);
cout << " / | `- \\ t--._ Y _3 " << endl;
pushX(x);
cout << " ,-' | / | /``'-.\\--T x\\" << endl;
pushX(x);
cout << " _/ _( ,./ / ( \\ x\\" << endl;
pushX(x);
cout << " _.-/ \\ / < \\ \\ x\\" << endl;
pushX(x);
cout << " <`' / |\/ `-. : \\_x\\" << endl;
pushX(x);
cout << " \\ / | `. |" << endl;
pushX(x);
cout << " \\_| / `." << endl;
}
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}
|
#include "StateAnalyzer.hpp"
#include "GameState.hpp"
#include "Board.hpp"
namespace Logic {
StateAnalyzer::StateAnalyzer(const Model::GameState* gameState) : gameState(gameState) {}
Util::Rect StateAnalyzer::getBoundingRect(const Model::PieceColor& color) const {
int maxX = INT_MIN;
int minX = INT_MAX;
int maxY = INT_MIN;
int minY = INT_MAX;
for (const std::optional<Model::DeployedPiece>& piece : gameState->getMoveHistory()) {
if (piece.has_value() && piece.value().color == color) {
for (const Util::Position& pos : piece.value().getOccupiedPositions()) {
maxX = std::max(static_cast<int>(pos.x), maxX);
maxY = std::max(static_cast<int>(pos.y), maxY);
minX = std::min(static_cast<int>(pos.x), minX);
minY = std::min(static_cast<int>(pos.y), minY);
}
}
}
return Util::Rect(minX, maxX, minY, maxY);
}
Util::Rect StateAnalyzer::getPlayerArea(const Model::Player& player) const {
return getBoundingRect(player.getPieceColors()[0]).join(getBoundingRect(player.getPieceColors()[1]));
}
int StateAnalyzer::basicStrategie(const std::array<Model::BoardStatistics, 4>& stats, const std::array<int, 2> colorIdx, const std::array<int, 2> opponentColorIdx) const {
int spread = 0;
int drop = 0;
int block = 0;
//* Drop
drop += stats[colorIdx[0]].dropPositions * 8;
drop += stats[colorIdx[1]].dropPositions * 8;
drop -= stats[opponentColorIdx[0]].dropPositions * 8;
drop -= stats[opponentColorIdx[1]].dropPositions * 8;
for (int i = 0; i < 8; ++i) {
drop += stats[colorIdx[0]].ratedDropPositions[i] * i;
drop += stats[colorIdx[1]].ratedDropPositions[i] * i;
drop -= stats[opponentColorIdx[0]].ratedDropPositions[i] * i;
drop -= stats[opponentColorIdx[1]].ratedDropPositions[i] * i;
}
//* Block
//? Penalty when the team is blocking itself
block -= stats[colorIdx[0]].friendlyBlockedCorners * 4;
block -= stats[colorIdx[1]].friendlyBlockedCorners * 4;
//? Block the colors of the opponent
block += stats[opponentColorIdx[0]].opponentBlockedCorners;
block += stats[opponentColorIdx[1]].opponentBlockedCorners;
//* Spread
spread += stats[colorIdx[0]].teamSpread + stats[colorIdx[1]].teamSpread;
spread -= stats[opponentColorIdx[0]].spread + stats[opponentColorIdx[1]].spread;
spread += stats[colorIdx[0]].advancement + stats[colorIdx[1]].advancement;
spread -= stats[opponentColorIdx[0]].advancement + stats[opponentColorIdx[1]].advancement;
return spread + block + drop;
}
int StateAnalyzer::strategyPoints(const std::array<Model::PieceColor, 2>& colors, const std::array<Model::PieceColor, 2>& opponentColors) const {
//? Prepare information
const Model::Board& board = gameState->getBoard();
const std::array<int, 4> normalizedStart = {
gameState->startPositions[0][0] + 20 * gameState->startPositions[0][1],
gameState->startPositions[1][0] + 20 * gameState->startPositions[1][1],
gameState->startPositions[2][0] + 20 * gameState->startPositions[2][1],
gameState->startPositions[3][0] + 20 * gameState->startPositions[3][1]
};
bool horizontal =
static_cast<uint8_t>(board.at(0, 0)) >= 3 // If top left is team two
? (static_cast<uint8_t>(board.at(0, 19)) >= 3 ? true : false) // YES: If bottom left is team two -> horizontal
: (static_cast<uint8_t>(board.at(0, 19)) >= 3 ? false : true); // NO: If bottom left is team two -> vertical
const std::array<Model::BoardStatistics, 4>& stats = board.getStatistics(horizontal);
const std::array<int, 2> colorIdx = { static_cast<int>(colors[0]) - 1, static_cast<int>(colors[1]) - 1 };
const std::array<int, 2> opponentColorIdx = { static_cast<int>(opponentColors[0]) - 1, static_cast<int>(opponentColors[1]) - 1 };
std::array<int, 4> startIndex {};
std::array<int, 4> opposingNeighbour{};
std::array<int, 4> oppositeCorner{};
std::array<int, 4> startSide{};
for (int i = 0; i < 4; ++i) {
switch (normalizedStart[i]) {
case 0:
// Top left
startIndex[i] = 0;
opposingNeighbour[i] = horizontal ? 1 : 3;
oppositeCorner[i] = 2;
startSide[i] = 0;
break;
case 19:
// Top right
startIndex[i] = 1;
opposingNeighbour[i] = horizontal ? 0 : 2;
oppositeCorner[i] = 3;
startSide[i] = horizontal ? 1 : 0;
break;
case 399:
// Bottom right
startIndex[i] = 2;
opposingNeighbour[i] = horizontal ? 3 : 1;
oppositeCorner[i] = 0;
startSide[i] = 1;
break;
case 380:
// Bottom left
startIndex[i] = 3;
opposingNeighbour[i] = horizontal ? 2 :0;
oppositeCorner[i] = 1;
startSide[i] = horizontal ? 0 : 1;
break;
}
}
if (gameState->getTurn() < 20) {
//? Push each color to the middle
return stats[colorIdx[0]].pullFactor[oppositeCorner[colorIdx[0]]] + stats[colorIdx[1]].pullFactor[oppositeCorner[colorIdx[1]]];
}
return basicStrategie(stats, colorIdx, opponentColorIdx);
}
}
|
#include <math.h>
#include "mex.h"
#include <string.h>
#include "logistic_functions_sparse.h"
#include "logistic_functions_dense.h"
#include "utilities_dense.h"
#include "utilities_sparse.h"
/*
USAGE:
hist = SGD(w, Xt, y, lambda, stepsize, iVals);
==================================================================
INPUT PARAMETERS:
w (d x 1) - initial point; updated in place
Xt (d x n) - data matrix; transposed (data points are columns); real
y (n x 1) - labels; in {-1,1}
lambda - scalar regularization param
stepSize - a step-size
iVals(iters x 1) - sequence of examples to choose, between 0 and (n-1)
==================================================================
OUTPUT PARAMETERS:
hist = array of function values after each outer loop.
Computed ONLY if asked for output in MATALB.
*/
/// SGD_dense runs the SGD algorithm with constant stepsize for
/// solving regularized logistic regression on dense data provided
/// nlhs - number of output parameters requested
/// if set to 1, function values are computed
/// *prhs[] - array of pointers to the input arguments
mxArray* SGD_dense(int nlhs, const mxArray *prhs[])
{
//////////////////////////////////////////////////////////////////
/// Declare variables ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Input variables
double *w, *Xt, *y;
double lambda, stepSize;
long long *iVals;
// Other variables
long k; // Some loop indexes
long n, d; // Dimensions of problem
long iters;
long long idx;
double sigmoid;
double *hist; // Used to store function value at points in history
bool evalf = false; // set to true if function values should be evaluated
mxArray *plhs; // History array to return if needed
//////////////////////////////////////////////////////////////////
/// Process input ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
w = mxGetPr(prhs[0]); // The variable to be learned
Xt = mxGetPr(prhs[1]); // Data matrix (transposed)
y = mxGetPr(prhs[2]); // Labels
lambda = mxGetScalar(prhs[3]); // Regularization parameter
stepSize = mxGetScalar(prhs[4]); // Step-size (constant)
iVals = (long long*)mxGetPr(prhs[5]); // Sampled indexes (sampled in advance)
if (nlhs == 1) {
evalf = true;
}
if (!mxIsClass(prhs[5], "int64"))
mexErrMsgTxt("iVals must be int64");
//////////////////////////////////////////////////////////////////
/// Get problem related constants ////////////////////////////////
//////////////////////////////////////////////////////////////////
d = mxGetM(prhs[1]); // Number of features, or dimension of problem
n = mxGetN(prhs[1]); // Number of samples, or data points
iters = mxGetM(prhs[5]); // Number of outer iterations
//////////////////////////////////////////////////////////////////
/// Initialize some values ///////////////////////////////////////
//////////////////////////////////////////////////////////////////
if (evalf == true) {
plhs = mxCreateDoubleMatrix((long)floor((double)iters / (n)) + 1, 1, mxREAL);
hist = mxGetPr(plhs);
}
//////////////////////////////////////////////////////////////////
/// The SGD algorithm ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
for (k = 0; k < iters; k++) {
// Evaluate function value from time to time if output requested
if (evalf == true && k % (n) == 0) {
hist[(long)floor((double)k / (n))] = compute_function_value(w, Xt, y, n, d, lambda);
}
idx = *(iVals++); // Sample function and move pointer
sigmoid = compute_sigmoid(Xt + d*idx, w, y[idx], d);
update_test_point_dense_SGD(Xt + d*idx, w, d,
sigmoid, stepSize, lambda);
}
// Evaluate the final function value
if (evalf == true) {
hist[(long)floor((double)iters / (n))] = compute_function_value(w, Xt, y, n, d, lambda);
}
//////////////////////////////////////////////////////////////////
/// Free some memory /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/// Return value /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
if (evalf == true) { return plhs; }
else { return 0; }
}
/// SGD_sparse runs the SGD algorithm with constant stepsize for
/// solving regularized logistic regression on sparse data provided
/// nlhs - number of output parameters requested
/// if set to 1, function values are computed
/// *prhs[] - array of pointers to the input arguments
mxArray* SGD_sparse(int nlhs, const mxArray *prhs[])
{
//////////////////////////////////////////////////////////////////
/// Declare variables ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Input variables
double *w, *Xt, *y;
double lambda, stepSize;
long long *iVals;
// Other variables
long k; // Some loop indexes
long n, d; // Dimensions of problem
long iters; // Number of outer loops
long long idx; // For choosing indexes
double sigmoid; // Scalar value of the derivative of sigmoid function
double *hist; // Used to store function value at points in history
bool evalf = false; // set to true if function values should be evaluated
long *last_seen; // used to do lazy "when needed" updates
mwIndex *ir, *jc; // used to access nonzero elements of Xt
mxArray *plhs; // History array to return if needed
//////////////////////////////////////////////////////////////////
/// Process input ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
w = mxGetPr(prhs[0]); // The variable to be learned
Xt = mxGetPr(prhs[1]); // Data matrix (transposed)
y = mxGetPr(prhs[2]); // Labels
lambda = mxGetScalar(prhs[3]); // Regularization parameter
stepSize = mxGetScalar(prhs[4]); // Step-size (constant)
iVals = (long long*)mxGetPr(prhs[5]); // Sampled indexes (sampled in advance)
if (nlhs == 1) {
evalf = true;
}
if (!mxIsClass(prhs[5], "int64"))
mexErrMsgTxt("iVals must be int64");
//////////////////////////////////////////////////////////////////
/// Get problem related constants ////////////////////////////////
//////////////////////////////////////////////////////////////////
d = mxGetM(prhs[1]); // Number of features, or dimension of problem
n = mxGetN(prhs[1]); // Number of samples, or data points
iters = mxGetM(prhs[5]); // Number of outer iterations
jc = mxGetJc(prhs[1]); // pointers to starts of columns of Xt
ir = mxGetIr(prhs[1]); // row indexes of individual elements of Xt
//////////////////////////////////////////////////////////////////
/// Initialize some values ///////////////////////////////////////
//////////////////////////////////////////////////////////////////
last_seen = new long[d];
if (evalf == true) {
plhs = mxCreateDoubleMatrix((long)floor((double)iters / (n)) + 1, 1, mxREAL);
hist = mxGetPr(plhs);
}
//////////////////////////////////////////////////////////////////
/// The SGD algorithm ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
for (long j = 0; j < d; j++) { last_seen[j] = 0; }
for (k = 0; k < iters; k++) {
// Evaluate function value from time to time if output requested
if (evalf == true && k % (n) == 0) {
hist[(long)floor((double)k / (n))] = compute_function_value_sparse(w, Xt, y, n, d, lambda, ir, jc);
}
idx = *(iVals++); // Sample function and move pointer
lazy_update_SGD(w, last_seen, stepSize, lambda, k, ir, jc + idx);
sigmoid = compute_sigmoid_sparse(Xt + jc[idx], w, y[idx],
jc[idx + 1] - jc[idx], ir + jc[idx]);
update_test_point_sparse_SGD(Xt + jc[idx], w, jc[idx + 1] - jc[idx],
sigmoid, stepSize, lambda, ir + jc[idx]);
}
// Evaluate the final function value
if (evalf == true) {
hist[(long)floor((double)iters / (n))] = compute_function_value_sparse(w, Xt, y, n, d, lambda, ir, jc);
}
//////////////////////////////////////////////////////////////////
/// Free some memory /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
delete[] last_seen;
//////////////////////////////////////////////////////////////////
/// Return value /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
if (evalf == true) { return plhs; }
else { return 0; }
}
/// Entry function of MATLAB
/// nlhs - number of output parameters
/// *plhs[] - array poiters to the outputs
/// nrhs - number of input parameters
/// *prhs[] - array of pointers to inputs
/// For more info about this syntax see
/// http://www.mathworks.co.uk/help/matlab/matlab_external/gateway-routine.html
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
// First determine, whether the data matrix is stored in sparse format.
// If it is, use more efficient algorithm
if (mxIsSparse(prhs[1])) {
plhs[0] = SGD_sparse(nlhs, prhs);
}
else {
plhs[0] = SGD_dense(nlhs, prhs);
}
}
|
//
// coroutine.cpp
// ~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot 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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include <boost/asio/coroutine.hpp>
#include "unit_test.hpp"
// Must come after all other headers.
#include <boost/asio/yield.hpp>
//------------------------------------------------------------------------------
// Coroutine completes via yield break.
void yield_break_coro(boost::asio::coroutine& coro)
{
reenter (coro)
{
yield return;
yield break;
}
}
void yield_break_test()
{
boost::asio::coroutine coro;
BOOST_ASIO_CHECK(!coro.is_complete());
yield_break_coro(coro);
BOOST_ASIO_CHECK(!coro.is_complete());
yield_break_coro(coro);
BOOST_ASIO_CHECK(coro.is_complete());
}
//------------------------------------------------------------------------------
// Coroutine completes via return.
void return_coro(boost::asio::coroutine& coro)
{
reenter (coro)
{
return;
}
}
void return_test()
{
boost::asio::coroutine coro;
return_coro(coro);
BOOST_ASIO_CHECK(coro.is_complete());
}
//------------------------------------------------------------------------------
// Coroutine completes via exception.
void exception_coro(boost::asio::coroutine& coro)
{
reenter (coro)
{
throw 1;
}
}
void exception_test()
{
boost::asio::coroutine coro;
try { exception_coro(coro); } catch (int) {}
BOOST_ASIO_CHECK(coro.is_complete());
}
//------------------------------------------------------------------------------
// Coroutine completes by falling off the end.
void fall_off_end_coro(boost::asio::coroutine& coro)
{
reenter (coro)
{
}
}
void fall_off_end_test()
{
boost::asio::coroutine coro;
fall_off_end_coro(coro);
BOOST_ASIO_CHECK(coro.is_complete());
}
//------------------------------------------------------------------------------
BOOST_ASIO_TEST_SUITE
(
"coroutine",
BOOST_ASIO_TEST_CASE(yield_break_test)
BOOST_ASIO_TEST_CASE(return_test)
BOOST_ASIO_TEST_CASE(exception_test)
BOOST_ASIO_TEST_CASE(fall_off_end_test)
)
|
#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>
#include <stdexcept>
TEST(ErrorHandlingMatrix, checkNotNanEigenRow) {
stan::math::vector_d y;
y.resize(3);
EXPECT_NO_THROW(stan::math::check_not_nan("checkNotNanEigenRow(%1)",
"y", y));
EXPECT_NO_THROW(stan::math::check_not_nan("checkNotNanEigenRow(%1)",
"y", y));
y(1) = std::numeric_limits<double>::quiet_NaN();
EXPECT_THROW(stan::math::check_not_nan("checkNotNanEigenRow", "y", y),
std::domain_error);
EXPECT_THROW(stan::math::check_not_nan("checkNotNanEigenRow", "y", y),
std::domain_error);
}
|
/**
* @file SerialNumberSignatureOfKnowledge.cpp
*
* @brief SerialNumberSignatureOfKnowledge class for the Zerocoin library.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017-2019 The EXCL developers
#include <streams.h>
#include "SerialNumberSignatureOfKnowledge.h"
namespace libzerocoin {
SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const ZerocoinParams* p): params(p) { }
// Use one 256 bit seed and concatenate 4 unique 256 bit hashes to make a 1024 bit hash
CBigNum SeedTo1024(uint256 hashSeed) {
CHashWriter hasher(0,0);
hasher << hashSeed;
std::vector<unsigned char> vResult;
std::vector<unsigned char> vHash = CBigNum(hasher.GetHash()).getvch();
vResult.insert(vResult.end(), vHash.begin(), vHash.end());
for (int i = 0; i < 3; i ++) {
hasher << vResult;
vHash = CBigNum(hasher.GetHash()).getvch();
vResult.insert(vResult.end(), vHash.begin(), vHash.end());
}
CBigNum bnResult;
bnResult.setvch(vResult);
return bnResult;
}
SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const
ZerocoinParams* p, const PrivateCoin& coin, const Commitment& commitmentToCoin, uint256 msghash):
params(p),
s_notprime(p->zkp_iterations),
sprime(p->zkp_iterations)
{
// Sanity check: verify that the order of the "accumulatedValueCommitmentGroup" is
// equal to the modulus of "coinCommitmentGroup". Otherwise we will produce invalid proofs.
if (params->coinCommitmentGroup.modulus != params->serialNumberSoKCommitmentGroup.groupOrder)
throw std::runtime_error("Groups are not structured correctly.");
CBigNum a = params->coinCommitmentGroup.g;
CBigNum b = params->coinCommitmentGroup.h;
CBigNum g = params->serialNumberSoKCommitmentGroup.g;
CBigNum h = params->serialNumberSoKCommitmentGroup.h;
CHashWriter hasher(0,0);
hasher << *params << commitmentToCoin.getCommitmentValue() << coin.getSerialNumber() << msghash;
std::vector<CBigNum> r(params->zkp_iterations);
std::vector<CBigNum> v_seed(params->zkp_iterations);
std::vector<CBigNum> v_expanded(params->zkp_iterations);
std::vector<CBigNum> c(params->zkp_iterations);
for(uint32_t i=0; i < params->zkp_iterations; i++) {
r[i] = CBigNum::randBignum(params->coinCommitmentGroup.groupOrder);
//use a random 256 bit seed that expands to 1024 bit for v[i]
while (true) {
uint256 hashRand = CBigNum::randBignum(CBigNum(~uint256(0))).getuint256();
CBigNum bnExpanded = SeedTo1024(hashRand);
if(bnExpanded > params->serialNumberSoKCommitmentGroup.groupOrder)
continue;
v_seed[i] = CBigNum(hashRand);
v_expanded[i] = bnExpanded;
break;
}
}
for(uint32_t i=0; i < params->zkp_iterations; i++) {
// compute g^{ {a^x b^r} h^v} mod p2
c[i] = challengeCalculation(coin.getSerialNumber(), r[i], v_expanded[i]);
}
// We can't hash data in parallel either
// because OPENMP cannot not guarantee loops
// execute in order.
for(uint32_t i=0; i < params->zkp_iterations; i++)
hasher << c[i];
this->hash = hasher.GetHash();
unsigned char *hashbytes = (unsigned char*) &hash;
for(uint32_t i = 0; i < params->zkp_iterations; i++) {
int bit = i % 8;
int byte = i / 8;
bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
if (challenge_bit) {
s_notprime[i] = r[i];
sprime[i] = v_seed[i];
} else {
s_notprime[i] = r[i] - coin.getRandomness();
sprime[i] = v_expanded[i] - (commitmentToCoin.getRandomness() *
b.pow_mod(r[i] - coin.getRandomness(), params->serialNumberSoKCommitmentGroup.groupOrder));
}
}
}
inline CBigNum SerialNumberSignatureOfKnowledge::challengeCalculation(const CBigNum& a_exp,const CBigNum& b_exp,
const CBigNum& h_exp) const {
CBigNum a = params->coinCommitmentGroup.g;
CBigNum b = params->coinCommitmentGroup.h;
CBigNum g = params->serialNumberSoKCommitmentGroup.g;
CBigNum h = params->serialNumberSoKCommitmentGroup.h;
CBigNum exponent = (a.pow_mod(a_exp, params->serialNumberSoKCommitmentGroup.groupOrder) *
b.pow_mod(b_exp, params->serialNumberSoKCommitmentGroup.groupOrder)) % params->serialNumberSoKCommitmentGroup.groupOrder;
return (g.pow_mod(exponent, params->serialNumberSoKCommitmentGroup.modulus) * h.pow_mod(h_exp, params->serialNumberSoKCommitmentGroup.modulus)) % params->serialNumberSoKCommitmentGroup.modulus;
}
bool SerialNumberSignatureOfKnowledge::Verify(const CBigNum& coinSerialNumber, const CBigNum& valueOfCommitmentToCoin,
const uint256 msghash, bool isInParamsValidationRange) const {
CBigNum a = params->coinCommitmentGroup.g;
CBigNum b = params->coinCommitmentGroup.h;
CBigNum g = params->serialNumberSoKCommitmentGroup.g;
CBigNum h = params->serialNumberSoKCommitmentGroup.h;
//// Params validation.
if(isInParamsValidationRange) {
// Check that the serial is within the max size
if (!IsValidSerial(params, coinSerialNumber))
return error("Invalid serial range");
// Check that the commitment is in the correct group
if (!IsValidCommitmentToCoinRange(params, valueOfCommitmentToCoin))
return error("Invalid commitment to coin range");
}
//// Verification
CHashWriter hasher(0,0);
hasher << *params << valueOfCommitmentToCoin << coinSerialNumber << msghash;
std::vector<CBigNum> tprime(params->zkp_iterations);
unsigned char *hashbytes = (unsigned char*) &this->hash;
try {
for (uint32_t i = 0; i < params->zkp_iterations; i++) {
int bit = i % 8;
int byte = i / 8;
bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
if (challenge_bit) {
CBigNum bn = SeedTo1024(sprime[i].getuint256());
if (bn > params->serialNumberSoKCommitmentGroup.groupOrder && isInParamsValidationRange)
return error("SoK Verify() :: sprime in pos %d not in valid range", i);
tprime[i] = challengeCalculation(coinSerialNumber, s_notprime[i], bn);
} else {
CBigNum exp = b.pow_mod(s_notprime[i], params->serialNumberSoKCommitmentGroup.groupOrder);
tprime[i] = ((valueOfCommitmentToCoin.pow_mod(exp, params->serialNumberSoKCommitmentGroup.modulus) %
params->serialNumberSoKCommitmentGroup.modulus) *
(h.pow_mod(sprime[i], params->serialNumberSoKCommitmentGroup.modulus) %
params->serialNumberSoKCommitmentGroup.modulus)) %
params->serialNumberSoKCommitmentGroup.modulus;
}
}
for (uint32_t i = 0; i < params->zkp_iterations; i++) {
hasher << tprime[i];
}
return hasher.GetHash() == hash;
}catch (std::range_error e){
return error("SoK Verify() :: sprime invalid range.");
}
}
} /* namespace libzerocoin */
|
#include <cmath>
#include <catch/catch.hpp>
#include <Eigen/Dense>
#include "configure.h"
#include "factory.h"
#include "normal_multivar.h"
#include "numeric_utils.h"
TEST_CASE("Test generation of random numbers", "[RandomNumbers]") {
// Initialize the factories
config::initialize();
// Seed value for repeatability
int seed = 100;
auto random_generator = Factory<numeric_utils::RandomGenerator, int>::instance()
->create("MultivariateNormal", std::move(seed));
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> random_numbers;
SECTION("Generate normally distributed random numbers for single random "
"variable") {
Eigen::VectorXd means(1);
Eigen::MatrixXd cov(1,1);
means(0) = 1.789;
cov(0, 0) = 0.0123;
// Single random variable
random_generator->generate(random_numbers, means, cov, 100);
double average = 0.0;
for (unsigned int i = 0; i < random_numbers.size(); ++i) {
average = average + random_numbers(i);
}
average = average / random_numbers.size();
REQUIRE(average == Approx(means(0)).epsilon(0.01));
}
SECTION("Generate normally distributed random numbers for multiple "
"uncorrelated random variables", "[RandomNumbers]") {
Eigen::VectorXd means(4);
Eigen::MatrixXd cov = Eigen::MatrixXd::Zero(4,4);
means << 1.789, 0.01, -10012.7, 702;
cov(0, 0) = 0.0123 * 0.0123;
cov(1, 1) = 0.00005;
cov(2, 2) = 50.0;
cov(3, 3) = 25;
// Random variable vector
random_generator->generate(random_numbers, means, cov, 1000);
std::vector<double> averages(means.size());
for (unsigned int i = 0; i < random_numbers.cols(); ++i) {
for (unsigned int j = 0; j < means.size(); ++j) {
averages[j] = averages[j] + random_numbers(j, i);
}
}
REQUIRE(averages[0] / random_numbers.cols() == Approx(means(0)).epsilon(0.01));
REQUIRE(averages[1] / random_numbers.cols() == Approx(means(1)).epsilon(0.02));
REQUIRE(averages[2] / random_numbers.cols() == Approx(means(2)).epsilon(0.01));
REQUIRE(averages[3] / random_numbers.cols() == Approx(means(3)).epsilon(0.01));
}
SECTION("Generate normally distributed random numbers for correlated random "
"variable", "[RandomNumbers]") {
Eigen::VectorXd means(3);
Eigen::MatrixXd cov = Eigen::MatrixXd::Zero(3, 3);
means << 64.0, 300.0, 60.0;
// Try bad COV matrix
// clang-format off
cov << 1.0, 1.0, 0.0,
1.0, 1.0, 1.0,
0.0, 1.0, 1.0;
// clang-format on
bool success = random_generator->generate(random_numbers, means, cov, 250000);
REQUIRE(success == false);
// Try good COV matrix
// clang-format off
cov << 504.0, 360.0, 180.0,
360.0, 360.0, 0.0,
180.0, 0.0, 720.0;
// clang-format on
success = random_generator->generate(random_numbers, means, cov, 250000);
REQUIRE(success == true);
Eigen::VectorXd averages = Eigen::VectorXd::Zero(means.size());
for (unsigned int i = 0; i < means.size(); ++i) {
for (unsigned int j = 0; j < random_numbers.cols(); ++j) {
averages(i) = averages(i) + random_numbers(i, j);
}
}
averages = averages / random_numbers.cols();
REQUIRE(averages(0) == Approx(means(0)).epsilon(0.01));
REQUIRE(averages(1) == Approx(means(1)).epsilon(0.01));
REQUIRE(averages(2) == Approx(means(2)).epsilon(0.01));
// Compute covariance matrix from random values
Eigen::MatrixXd deviation_scores =
Eigen::MatrixXd::Zero(random_numbers.rows(), random_numbers.cols());
for (unsigned int i = 0; i < random_numbers.cols(); ++i) {
deviation_scores.col(i) = random_numbers.col(i) - averages;
}
Eigen::MatrixXd calculated_cov =
(deviation_scores * deviation_scores.transpose()) / random_numbers.cols();
REQUIRE(cov.lpNorm<2>() == Approx(calculated_cov.lpNorm<2>()).epsilon(0.01));
}
SECTION("Check that number generated using the same seed match", "[RandomNumbers]") {
int seed = 500;
auto random_generator1 =
Factory<numeric_utils::RandomGenerator, int>::instance()->create(
"MultivariateNormal", std::move(seed));
auto random_generator2 =
Factory<numeric_utils::RandomGenerator, int>::instance()->create(
"MultivariateNormal", std::move(seed));
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> random_numbers1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> random_numbers2;
Eigen::VectorXd means(1);
Eigen::MatrixXd cov(1,1);
means(0) = 1.789;
cov(0, 0) = 0.0123;
random_generator1->generate(random_numbers1, means, cov, 100);
random_generator2->generate(random_numbers2, means, cov, 100);
REQUIRE(random_numbers1 == random_numbers2);
}
}
|
#include "widgets/helper/NotebookTab.hpp"
#include "Application.hpp"
#include "common/Common.hpp"
#include "debug/Log.hpp"
#include "singletons/SettingsManager.hpp"
#include "singletons/ThemeManager.hpp"
#include "util/Clamp.hpp"
#include "util/Helpers.hpp"
#include "widgets/Notebook.hpp"
#include "widgets/dialogs/SettingsDialog.hpp"
#include "widgets/dialogs/TextInputDialog.hpp"
#include <QApplication>
#include <QDebug>
#include <QLinearGradient>
#include <QMimeData>
#include <QPainter>
#include <boost/bind.hpp>
namespace chatterino {
NotebookTab::NotebookTab(Notebook *notebook)
: RippleEffectButton(notebook)
, positionChangedAnimation_(this, "pos")
, notebook_(notebook)
, menu_(this)
{
auto app = getApp();
this->setAcceptDrops(true);
this->positionChangedAnimation_.setEasingCurve(QEasingCurve(QEasingCurve::InCubic));
app->settings->showTabCloseButton.connect(boost::bind(&NotebookTab::hideTabXChanged, this, _1),
this->managedConnections_);
this->setMouseTracking(true);
this->menu_.addAction("Rename", [this]() {
TextInputDialog d(this);
d.setWindowTitle("Change tab title (Leave empty for default behaviour)");
d.setText(this->getCustomTitle());
d.highlightText();
if (d.exec() == QDialog::Accepted) {
QString newTitle = d.getText();
this->setCustomTitle(newTitle);
}
});
// QAction *enableHighlightsOnNewMessageAction =
// new QAction("Enable highlights on new message", &this->menu);
// enableHighlightsOnNewMessageAction->setCheckable(true);
this->menu_.addAction("Close", [=]() { this->notebook_->removePage(this->page); });
// this->menu.addAction(enableHighlightsOnNewMessageAction);
// QObject::connect(enableHighlightsOnNewMessageAction, &QAction::toggled, [this](bool
// newValue) {
// Log("New value is {}", newValue); //
// });
}
void NotebookTab::themeRefreshEvent()
{
this->update();
// this->setMouseEffectColor(QColor("#999"));
this->setMouseEffectColor(this->themeManager->tabs.regular.text);
}
void NotebookTab::updateSize()
{
float scale = getScale();
int width;
QFontMetrics metrics = getApp()->fonts->getFontMetrics(
FontStyle::UiTabs, float(qreal(this->getScale()) * this->devicePixelRatioF()));
if (this->hasXButton()) {
width = (metrics.width(this->getTitle()) + int(32 * scale));
} else {
width = (metrics.width(this->getTitle()) + int(16 * scale));
}
width = clamp(width, this->height(), int(150 * scale));
if (this->width() != width) {
this->resize(width, int(NOTEBOOK_TAB_HEIGHT * scale));
this->notebook_->performLayout();
}
}
const QString &NotebookTab::getCustomTitle() const
{
return this->customTitle_;
}
void NotebookTab::setCustomTitle(const QString &newTitle)
{
if (this->customTitle_ != newTitle) {
this->customTitle_ = newTitle;
this->titleUpdated();
}
}
void NotebookTab::resetCustomTitle()
{
this->setCustomTitle(QString());
}
bool NotebookTab::hasCustomTitle() const
{
return !this->customTitle_.isEmpty();
}
void NotebookTab::setDefaultTitle(const QString &title)
{
if (this->defaultTitle_ != title) {
this->defaultTitle_ = title;
if (this->customTitle_.isEmpty()) {
this->titleUpdated();
}
}
}
const QString &NotebookTab::getDefaultTitle() const
{
return this->defaultTitle_;
}
const QString &NotebookTab::getTitle() const
{
return this->customTitle_.isEmpty() ? this->defaultTitle_ : this->customTitle_;
}
void NotebookTab::titleUpdated()
{
this->updateSize();
this->update();
}
bool NotebookTab::isSelected() const
{
return this->selected_;
}
void NotebookTab::setSelected(bool value)
{
this->selected_ = value;
this->highlightState_ = HighlightState::None;
this->update();
}
void NotebookTab::setHighlightState(HighlightState newHighlightStyle)
{
if (this->isSelected()) {
return;
}
if (this->highlightState_ != HighlightState::Highlighted) {
this->highlightState_ = newHighlightStyle;
this->update();
}
}
QRect NotebookTab::getDesiredRect() const
{
return QRect(this->positionAnimationDesiredPoint_, size());
}
void NotebookTab::hideTabXChanged(bool)
{
this->updateSize();
this->update();
}
void NotebookTab::moveAnimated(QPoint pos, bool animated)
{
this->positionAnimationDesiredPoint_ = pos;
QWidget *w = this->window();
if ((w != nullptr && !w->isVisible()) || !animated || !this->positionChangedAnimationRunning_) {
this->move(pos);
this->positionChangedAnimationRunning_ = true;
return;
}
if (this->positionChangedAnimation_.endValue() == pos) {
return;
}
this->positionChangedAnimation_.stop();
this->positionChangedAnimation_.setDuration(75);
this->positionChangedAnimation_.setStartValue(this->pos());
this->positionChangedAnimation_.setEndValue(pos);
this->positionChangedAnimation_.start();
}
void NotebookTab::paintEvent(QPaintEvent *)
{
auto app = getApp();
QPainter painter(this);
float scale = this->getScale();
painter.setFont(getApp()->fonts->getFont(
FontStyle::UiTabs, scale * 96.f / this->logicalDpiX() * this->devicePixelRatioF()));
QFontMetrics metrics = app->fonts->getFontMetrics(
FontStyle::UiTabs, scale * 96.f / this->logicalDpiX() * this->devicePixelRatioF());
int height = int(scale * NOTEBOOK_TAB_HEIGHT);
// int fullHeight = (int)(scale * 48);
// select the right tab colors
chatterino::ThemeManager::TabColors colors;
chatterino::ThemeManager::TabColors regular = this->themeManager->tabs.regular;
if (this->selected_) {
colors = this->themeManager->tabs.selected;
} else if (this->highlightState_ == HighlightState::Highlighted) {
colors = this->themeManager->tabs.highlighted;
} else if (this->highlightState_ == HighlightState::NewMessage) {
colors = this->themeManager->tabs.newMessage;
} else {
colors = this->themeManager->tabs.regular;
}
bool windowFocused = this->window() == QApplication::activeWindow();
// || SettingsDialog::getHandle() == QApplication::activeWindow();
QBrush tabBackground = /*this->mouseOver_ ? colors.backgrounds.hover
:*/ (windowFocused ? colors.backgrounds.regular
: colors.backgrounds.unfocused);
// painter.fillRect(rect(), this->mouseOver_ ? regular.backgrounds.hover
// : (windowFocused ? regular.backgrounds.regular
// :
// regular.backgrounds.unfocused));
// fill the tab background
auto bgRect = rect();
bgRect.setTop(bgRect.top() + 2);
painter.fillRect(bgRect, tabBackground);
// draw border
// painter.setPen(QPen("#fff"));
// QPainterPath path(QPointF(0, height));
// path.lineTo(0, 0);
// path.lineTo(this->width() - 1, 0);
// path.lineTo(this->width() - 1, this->height() - 1);
// path.lineTo(0, this->height() - 1);
// painter.drawPath(path);
// top line
painter.fillRect(QRectF(0, (this->selected_ ? 0.f : 1.f) * scale, this->width(),
(this->selected_ ? 2.f : 1.f) * scale),
this->mouseOver_
? colors.line.hover
: (windowFocused ? colors.line.regular : colors.line.unfocused));
// set the pen color
painter.setPen(colors.text);
// set area for text
int rectW = (!app->settings->showTabCloseButton ? 0 : int(16 * scale));
QRect rect(0, 0, this->width() - rectW, height);
// draw text
int offset = int(scale * 8);
QRect textRect(offset, this->selected_ ? 1 : 2, this->width() - offset - offset, height);
if (this->shouldDrawXButton()) {
textRect.setRight(textRect.right() - this->height() / 2);
}
int width = metrics.width(this->getTitle());
Qt::Alignment alignment = width > textRect.width() ? Qt::AlignLeft | Qt::AlignVCenter
: Qt::AlignHCenter | Qt::AlignVCenter;
QTextOption option(alignment);
option.setWrapMode(QTextOption::NoWrap);
painter.drawText(textRect, this->getTitle(), option);
// draw close x
if (this->shouldDrawXButton()) {
QRect xRect = this->getXRect();
if (!xRect.isNull()) {
painter.setBrush(QColor("#fff"));
if (this->mouseOverX_) {
painter.fillRect(xRect, QColor(0, 0, 0, 64));
if (this->mouseDownX_) {
painter.fillRect(xRect, QColor(0, 0, 0, 64));
}
}
int a = static_cast<int>(scale * 4);
painter.drawLine(xRect.topLeft() + QPoint(a, a), xRect.bottomRight() + QPoint(-a, -a));
painter.drawLine(xRect.topRight() + QPoint(-a, a), xRect.bottomLeft() + QPoint(a, -a));
}
}
// draw line at bottom
if (!this->selected_) {
painter.fillRect(0, this->height() - 1, this->width(), 1, app->themes->window.background);
this->fancyPaint(painter);
}
}
bool NotebookTab::hasXButton()
{
return getApp()->settings->showTabCloseButton && this->notebook_->getAllowUserTabManagement();
}
bool NotebookTab::shouldDrawXButton()
{
return this->hasXButton() && (this->mouseOver_ || this->selected_);
}
void NotebookTab::mousePressEvent(QMouseEvent *event)
{
this->mouseDown_ = true;
this->mouseDownX_ = this->getXRect().contains(event->pos());
this->update();
this->notebook_->select(page);
if (this->notebook_->getAllowUserTabManagement()) {
switch (event->button()) {
case Qt::RightButton: {
this->menu_.popup(event->globalPos());
} break;
default:;
}
}
}
void NotebookTab::mouseReleaseEvent(QMouseEvent *event)
{
this->mouseDown_ = false;
auto removeThisPage = [this] {
auto reply = QMessageBox::question(this, "Remove this tab",
"Are you sure that you want to remove this tab?",
QMessageBox::Yes | QMessageBox::Cancel);
if (reply == QMessageBox::Yes) {
this->notebook_->removePage(this->page);
}
};
if (event->button() == Qt::MiddleButton) {
if (this->rect().contains(event->pos())) {
removeThisPage();
}
} else {
if (this->hasXButton() && this->mouseDownX_ && this->getXRect().contains(event->pos())) {
this->mouseDownX_ = false;
removeThisPage();
} else {
this->update();
}
}
}
void NotebookTab::enterEvent(QEvent *event)
{
this->mouseOver_ = true;
this->update();
RippleEffectButton::enterEvent(event);
}
void NotebookTab::leaveEvent(QEvent *event)
{
this->mouseOverX_ = false;
this->mouseOver_ = false;
this->update();
RippleEffectButton::leaveEvent(event);
}
void NotebookTab::dragEnterEvent(QDragEnterEvent *event)
{
if (!event->mimeData()->hasFormat("chatterino/split"))
return;
if (!SplitContainer::isDraggingSplit)
return;
if (this->notebook_->getAllowUserTabManagement()) {
this->notebook_->select(this->page);
}
}
void NotebookTab::mouseMoveEvent(QMouseEvent *event)
{
auto app = getApp();
if (app->settings->showTabCloseButton && this->notebook_->getAllowUserTabManagement()) //
{
bool overX = this->getXRect().contains(event->pos());
if (overX != this->mouseOverX_) {
// Over X state has been changed (we either left or entered it;
this->mouseOverX_ = overX;
this->update();
}
}
QPoint relPoint = this->mapToParent(event->pos());
if (this->mouseDown_ && !this->getDesiredRect().contains(relPoint) &&
this->notebook_->getAllowUserTabManagement()) //
{
int index;
QWidget *clickedPage = this->notebook_->tabAt(relPoint, index, this->width());
if (clickedPage != nullptr && clickedPage != this->page) {
this->notebook_->rearrangePage(this->page, index);
}
}
RippleEffectButton::mouseMoveEvent(event);
}
QRect NotebookTab::getXRect()
{
// if (!this->notebook->getAllowUserTabManagement()) {
// return QRect();
// }
float s = this->getScale();
return QRect(this->width() - static_cast<int>(20 * s), static_cast<int>(6 * s),
static_cast<int>(16 * s), static_cast<int>(16 * s));
}
} // namespace chatterino
|
/* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2018, ITU/ISO/IEC
* 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 ITU/ISO/IEC 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.
*/
/** \file Contexts.cpp
* \brief Classes providing probability descriptions and contexts (also contains context initialization values)
*/
#include "Contexts.h"
#include <algorithm>
#include <cstring>
#include <limits>
const uint8_t ProbModelTables::m_NextState[128][2] =
{
{ 2, 1 },{ 0, 3 },{ 4, 0 },{ 1, 5 },{ 6, 2 },{ 3, 7 },{ 8, 4 },{ 5, 9 },
{ 10, 4 },{ 5, 11 },{ 12, 8 },{ 9, 13 },{ 14, 8 },{ 9, 15 },{ 16, 10 },{ 11, 17 },
{ 18, 12 },{ 13, 19 },{ 20, 14 },{ 15, 21 },{ 22, 16 },{ 17, 23 },{ 24, 18 },{ 19, 25 },
{ 26, 18 },{ 19, 27 },{ 28, 22 },{ 23, 29 },{ 30, 22 },{ 23, 31 },{ 32, 24 },{ 25, 33 },
{ 34, 26 },{ 27, 35 },{ 36, 26 },{ 27, 37 },{ 38, 30 },{ 31, 39 },{ 40, 30 },{ 31, 41 },
{ 42, 32 },{ 33, 43 },{ 44, 32 },{ 33, 45 },{ 46, 36 },{ 37, 47 },{ 48, 36 },{ 37, 49 },
{ 50, 38 },{ 39, 51 },{ 52, 38 },{ 39, 53 },{ 54, 42 },{ 43, 55 },{ 56, 42 },{ 43, 57 },
{ 58, 44 },{ 45, 59 },{ 60, 44 },{ 45, 61 },{ 62, 46 },{ 47, 63 },{ 64, 48 },{ 49, 65 },
{ 66, 48 },{ 49, 67 },{ 68, 50 },{ 51, 69 },{ 70, 52 },{ 53, 71 },{ 72, 52 },{ 53, 73 },
{ 74, 54 },{ 55, 75 },{ 76, 54 },{ 55, 77 },{ 78, 56 },{ 57, 79 },{ 80, 58 },{ 59, 81 },
{ 82, 58 },{ 59, 83 },{ 84, 60 },{ 61, 85 },{ 86, 60 },{ 61, 87 },{ 88, 60 },{ 61, 89 },
{ 90, 62 },{ 63, 91 },{ 92, 64 },{ 65, 93 },{ 94, 64 },{ 65, 95 },{ 96, 66 },{ 67, 97 },
{ 98, 66 },{ 67, 99 },{ 100, 66 },{ 67,101 },{ 102, 68 },{ 69,103 },{ 104, 68 },{ 69,105 },
{ 106, 70 },{ 71,107 },{ 108, 70 },{ 71,109 },{ 110, 70 },{ 71,111 },{ 112, 72 },{ 73,113 },
{ 114, 72 },{ 73,115 },{ 116, 72 },{ 73,117 },{ 118, 74 },{ 75,119 },{ 120, 74 },{ 75,121 },
{ 122, 74 },{ 75,123 },{ 124, 76 },{ 77,125 },{ 124, 76 },{ 77,125 },{ 126,126 },{ 127,127 }
};
const uint32_t ProbModelTables::m_EstFracBits[128] =
{
0x07b23, 0x085f9, 0x074a0, 0x08cbc, 0x06ee4, 0x09354, 0x067f4, 0x09c1b, 0x060b0, 0x0a62a, 0x05a9c, 0x0af5b, 0x0548d, 0x0b955, 0x04f56, 0x0c2a9,
0x04a87, 0x0cbf7, 0x045d6, 0x0d5c3, 0x04144, 0x0e01b, 0x03d88, 0x0e937, 0x039e0, 0x0f2cd, 0x03663, 0x0fc9e, 0x03347, 0x10600, 0x03050, 0x10f95,
0x02d4d, 0x11a02, 0x02ad3, 0x12333, 0x0286e, 0x12cad, 0x02604, 0x136df, 0x02425, 0x13f48, 0x021f4, 0x149c4, 0x0203e, 0x1527b, 0x01e4d, 0x15d00,
0x01c99, 0x166de, 0x01b18, 0x17017, 0x019a5, 0x17988, 0x01841, 0x18327, 0x016df, 0x18d50, 0x015d9, 0x19547, 0x0147c, 0x1a083, 0x0138e, 0x1a8a3,
0x01251, 0x1b418, 0x01166, 0x1bd27, 0x01068, 0x1c77b, 0x00f7f, 0x1d18e, 0x00eda, 0x1d91a, 0x00e19, 0x1e254, 0x00d4f, 0x1ec9a, 0x00c90, 0x1f6e0,
0x00c01, 0x1fef8, 0x00b5f, 0x208b1, 0x00ab6, 0x21362, 0x00a15, 0x21e46, 0x00988, 0x2285d, 0x00934, 0x22ea8, 0x008a8, 0x239b2, 0x0081d, 0x24577,
0x007c9, 0x24ce6, 0x00763, 0x25663, 0x00710, 0x25e8f, 0x006a0, 0x26a26, 0x00672, 0x26f23, 0x005e8, 0x27ef8, 0x005ba, 0x284b5, 0x0055e, 0x29057,
0x0050c, 0x29bab, 0x004c1, 0x2a674, 0x004a7, 0x2aa5e, 0x0046f, 0x2b32f, 0x0041f, 0x2c0ad, 0x003e7, 0x2ca8d, 0x003ba, 0x2d323, 0x0010c, 0x3bfbb
};
const BinFracBits ProbModelTables::m_BinFracBits_128[128] =
{
{{0x07b23, 0x085f9}}, {{0x085f9, 0x07b23}}, {{0x074a0, 0x08cbc}}, {{0x08cbc, 0x074a0}}, {{0x06ee4, 0x09354}}, {{0x09354, 0x06ee4}}, {{0x067f4, 0x09c1b}}, {{0x09c1b, 0x067f4}},
{{0x060b0, 0x0a62a}}, {{0x0a62a, 0x060b0}}, {{0x05a9c, 0x0af5b}}, {{0x0af5b, 0x05a9c}}, {{0x0548d, 0x0b955}}, {{0x0b955, 0x0548d}}, {{0x04f56, 0x0c2a9}}, {{0x0c2a9, 0x04f56}},
{{0x04a87, 0x0cbf7}}, {{0x0cbf7, 0x04a87}}, {{0x045d6, 0x0d5c3}}, {{0x0d5c3, 0x045d6}}, {{0x04144, 0x0e01b}}, {{0x0e01b, 0x04144}}, {{0x03d88, 0x0e937}}, {{0x0e937, 0x03d88}},
{{0x039e0, 0x0f2cd}}, {{0x0f2cd, 0x039e0}}, {{0x03663, 0x0fc9e}}, {{0x0fc9e, 0x03663}}, {{0x03347, 0x10600}}, {{0x10600, 0x03347}}, {{0x03050, 0x10f95}}, {{0x10f95, 0x03050}},
{{0x02d4d, 0x11a02}}, {{0x11a02, 0x02d4d}}, {{0x02ad3, 0x12333}}, {{0x12333, 0x02ad3}}, {{0x0286e, 0x12cad}}, {{0x12cad, 0x0286e}}, {{0x02604, 0x136df}}, {{0x136df, 0x02604}},
{{0x02425, 0x13f48}}, {{0x13f48, 0x02425}}, {{0x021f4, 0x149c4}}, {{0x149c4, 0x021f4}}, {{0x0203e, 0x1527b}}, {{0x1527b, 0x0203e}}, {{0x01e4d, 0x15d00}}, {{0x15d00, 0x01e4d}},
{{0x01c99, 0x166de}}, {{0x166de, 0x01c99}}, {{0x01b18, 0x17017}}, {{0x17017, 0x01b18}}, {{0x019a5, 0x17988}}, {{0x17988, 0x019a5}}, {{0x01841, 0x18327}}, {{0x18327, 0x01841}},
{{0x016df, 0x18d50}}, {{0x18d50, 0x016df}}, {{0x015d9, 0x19547}}, {{0x19547, 0x015d9}}, {{0x0147c, 0x1a083}}, {{0x1a083, 0x0147c}}, {{0x0138e, 0x1a8a3}}, {{0x1a8a3, 0x0138e}},
{{0x01251, 0x1b418}}, {{0x1b418, 0x01251}}, {{0x01166, 0x1bd27}}, {{0x1bd27, 0x01166}}, {{0x01068, 0x1c77b}}, {{0x1c77b, 0x01068}}, {{0x00f7f, 0x1d18e}}, {{0x1d18e, 0x00f7f}},
{{0x00eda, 0x1d91a}}, {{0x1d91a, 0x00eda}}, {{0x00e19, 0x1e254}}, {{0x1e254, 0x00e19}}, {{0x00d4f, 0x1ec9a}}, {{0x1ec9a, 0x00d4f}}, {{0x00c90, 0x1f6e0}}, {{0x1f6e0, 0x00c90}},
{{0x00c01, 0x1fef8}}, {{0x1fef8, 0x00c01}}, {{0x00b5f, 0x208b1}}, {{0x208b1, 0x00b5f}}, {{0x00ab6, 0x21362}}, {{0x21362, 0x00ab6}}, {{0x00a15, 0x21e46}}, {{0x21e46, 0x00a15}},
{{0x00988, 0x2285d}}, {{0x2285d, 0x00988}}, {{0x00934, 0x22ea8}}, {{0x22ea8, 0x00934}}, {{0x008a8, 0x239b2}}, {{0x239b2, 0x008a8}}, {{0x0081d, 0x24577}}, {{0x24577, 0x0081d}},
{{0x007c9, 0x24ce6}}, {{0x24ce6, 0x007c9}}, {{0x00763, 0x25663}}, {{0x25663, 0x00763}}, {{0x00710, 0x25e8f}}, {{0x25e8f, 0x00710}}, {{0x006a0, 0x26a26}}, {{0x26a26, 0x006a0}},
{{0x00672, 0x26f23}}, {{0x26f23, 0x00672}}, {{0x005e8, 0x27ef8}}, {{0x27ef8, 0x005e8}}, {{0x005ba, 0x284b5}}, {{0x284b5, 0x005ba}}, {{0x0055e, 0x29057}}, {{0x29057, 0x0055e}},
{{0x0050c, 0x29bab}}, {{0x29bab, 0x0050c}}, {{0x004c1, 0x2a674}}, {{0x2a674, 0x004c1}}, {{0x004a7, 0x2aa5e}}, {{0x2aa5e, 0x004a7}}, {{0x0046f, 0x2b32f}}, {{0x2b32f, 0x0046f}},
{{0x0041f, 0x2c0ad}}, {{0x2c0ad, 0x0041f}}, {{0x003e7, 0x2ca8d}}, {{0x2ca8d, 0x003e7}}, {{0x003ba, 0x2d323}}, {{0x2d323, 0x003ba}}, {{0x0010c, 0x3bfbb}}, {{0x3bfbb, 0x0010c}}
};
#if JEM_TOOLS
const BinFracBits ProbModelTables::m_BinFracBits_256[256] =
{
{{0x0005c, 0x48000}}, {{0x00116, 0x3b520}}, {{0x001d0, 0x356cb}}, {{0x0028b, 0x318a9}}, {{0x00346, 0x2ea40}}, {{0x00403, 0x2c531}}, {{0x004c0, 0x2a658}}, {{0x0057e, 0x28beb}},
{{0x0063c, 0x274ce}}, {{0x006fc, 0x26044}}, {{0x007bc, 0x24dc9}}, {{0x0087d, 0x23cfc}}, {{0x0093f, 0x22d96}}, {{0x00a01, 0x21f60}}, {{0x00ac4, 0x2122e}}, {{0x00b89, 0x205dd}},
{{0x00c4e, 0x1fa51}}, {{0x00d13, 0x1ef74}}, {{0x00dda, 0x1e531}}, {{0x00ea2, 0x1db78}}, {{0x00f6a, 0x1d23c}}, {{0x01033, 0x1c970}}, {{0x010fd, 0x1c10b}}, {{0x011c8, 0x1b903}},
{{0x01294, 0x1b151}}, {{0x01360, 0x1a9ee}}, {{0x0142e, 0x1a2d4}}, {{0x014fc, 0x19bfc}}, {{0x015cc, 0x19564}}, {{0x0169c, 0x18f06}}, {{0x0176d, 0x188de}}, {{0x0183f, 0x182e8}},
{{0x01912, 0x17d23}}, {{0x019e6, 0x1778a}}, {{0x01abb, 0x1721c}}, {{0x01b91, 0x16cd5}}, {{0x01c68, 0x167b4}}, {{0x01d40, 0x162b6}}, {{0x01e19, 0x15dda}}, {{0x01ef3, 0x1591e}},
{{0x01fcd, 0x15480}}, {{0x020a9, 0x14fff}}, {{0x02186, 0x14b99}}, {{0x02264, 0x1474e}}, {{0x02343, 0x1431b}}, {{0x02423, 0x13f01}}, {{0x02504, 0x13afd}}, {{0x025e6, 0x1370f}},
{{0x026ca, 0x13336}}, {{0x027ae, 0x12f71}}, {{0x02894, 0x12bc0}}, {{0x0297a, 0x12821}}, {{0x02a62, 0x12494}}, {{0x02b4b, 0x12118}}, {{0x02c35, 0x11dac}}, {{0x02d20, 0x11a51}},
{{0x02e0c, 0x11704}}, {{0x02efa, 0x113c7}}, {{0x02fe9, 0x11098}}, {{0x030d9, 0x10d77}}, {{0x031ca, 0x10a63}}, {{0x032bc, 0x1075c}}, {{0x033b0, 0x10461}}, {{0x034a5, 0x10173}},
{{0x0359b, 0x0fe90}}, {{0x03693, 0x0fbb9}}, {{0x0378c, 0x0f8ed}}, {{0x03886, 0x0f62b}}, {{0x03981, 0x0f374}}, {{0x03a7e, 0x0f0c7}}, {{0x03b7c, 0x0ee23}}, {{0x03c7c, 0x0eb89}},
{{0x03d7d, 0x0e8f9}}, {{0x03e7f, 0x0e671}}, {{0x03f83, 0x0e3f2}}, {{0x04088, 0x0e17c}}, {{0x0418e, 0x0df0e}}, {{0x04297, 0x0dca8}}, {{0x043a0, 0x0da4a}}, {{0x044ab, 0x0d7f3}},
{{0x045b8, 0x0d5a5}}, {{0x046c6, 0x0d35d}}, {{0x047d6, 0x0d11c}}, {{0x048e7, 0x0cee3}}, {{0x049fa, 0x0ccb0}}, {{0x04b0e, 0x0ca84}}, {{0x04c24, 0x0c85e}}, {{0x04d3c, 0x0c63f}},
{{0x04e55, 0x0c426}}, {{0x04f71, 0x0c212}}, {{0x0508d, 0x0c005}}, {{0x051ac, 0x0bdfe}}, {{0x052cc, 0x0bbfc}}, {{0x053ee, 0x0b9ff}}, {{0x05512, 0x0b808}}, {{0x05638, 0x0b617}},
{{0x0575f, 0x0b42a}}, {{0x05888, 0x0b243}}, {{0x059b4, 0x0b061}}, {{0x05ae1, 0x0ae83}}, {{0x05c10, 0x0acaa}}, {{0x05d41, 0x0aad6}}, {{0x05e74, 0x0a907}}, {{0x05fa9, 0x0a73c}},
{{0x060e0, 0x0a575}}, {{0x06219, 0x0a3b3}}, {{0x06354, 0x0a1f5}}, {{0x06491, 0x0a03b}}, {{0x065d1, 0x09e85}}, {{0x06712, 0x09cd4}}, {{0x06856, 0x09b26}}, {{0x0699c, 0x0997c}},
{{0x06ae4, 0x097d6}}, {{0x06c2f, 0x09634}}, {{0x06d7c, 0x09495}}, {{0x06ecb, 0x092fa}}, {{0x0701d, 0x09162}}, {{0x07171, 0x08fce}}, {{0x072c7, 0x08e3e}}, {{0x07421, 0x08cb0}},
{{0x0757c, 0x08b26}}, {{0x076da, 0x089a0}}, {{0x0783b, 0x0881c}}, {{0x0799f, 0x0869c}}, {{0x07b05, 0x0851f}}, {{0x07c6e, 0x083a4}}, {{0x07dd9, 0x0822d}}, {{0x07f48, 0x080b9}},
{{0x080b9, 0x07f48}}, {{0x0822d, 0x07dd9}}, {{0x083a4, 0x07c6e}}, {{0x0851f, 0x07b05}}, {{0x0869c, 0x0799f}}, {{0x0881c, 0x0783b}}, {{0x089a0, 0x076da}}, {{0x08b26, 0x0757c}},
{{0x08cb0, 0x07421}}, {{0x08e3e, 0x072c7}}, {{0x08fce, 0x07171}}, {{0x09162, 0x0701d}}, {{0x092fa, 0x06ecb}}, {{0x09495, 0x06d7c}}, {{0x09634, 0x06c2f}}, {{0x097d6, 0x06ae4}},
{{0x0997c, 0x0699c}}, {{0x09b26, 0x06856}}, {{0x09cd4, 0x06712}}, {{0x09e85, 0x065d1}}, {{0x0a03b, 0x06491}}, {{0x0a1f5, 0x06354}}, {{0x0a3b3, 0x06219}}, {{0x0a575, 0x060e0}},
{{0x0a73c, 0x05fa9}}, {{0x0a907, 0x05e74}}, {{0x0aad6, 0x05d41}}, {{0x0acaa, 0x05c10}}, {{0x0ae83, 0x05ae1}}, {{0x0b061, 0x059b4}}, {{0x0b243, 0x05888}}, {{0x0b42a, 0x0575f}},
{{0x0b617, 0x05638}}, {{0x0b808, 0x05512}}, {{0x0b9ff, 0x053ee}}, {{0x0bbfc, 0x052cc}}, {{0x0bdfe, 0x051ac}}, {{0x0c005, 0x0508d}}, {{0x0c212, 0x04f71}}, {{0x0c426, 0x04e55}},
{{0x0c63f, 0x04d3c}}, {{0x0c85e, 0x04c24}}, {{0x0ca84, 0x04b0e}}, {{0x0ccb0, 0x049fa}}, {{0x0cee3, 0x048e7}}, {{0x0d11c, 0x047d6}}, {{0x0d35d, 0x046c6}}, {{0x0d5a5, 0x045b8}},
{{0x0d7f3, 0x044ab}}, {{0x0da4a, 0x043a0}}, {{0x0dca8, 0x04297}}, {{0x0df0e, 0x0418e}}, {{0x0e17c, 0x04088}}, {{0x0e3f2, 0x03f83}}, {{0x0e671, 0x03e7f}}, {{0x0e8f9, 0x03d7d}},
{{0x0eb89, 0x03c7c}}, {{0x0ee23, 0x03b7c}}, {{0x0f0c7, 0x03a7e}}, {{0x0f374, 0x03981}}, {{0x0f62b, 0x03886}}, {{0x0f8ed, 0x0378c}}, {{0x0fbb9, 0x03693}}, {{0x0fe90, 0x0359b}},
{{0x10173, 0x034a5}}, {{0x10461, 0x033b0}}, {{0x1075c, 0x032bc}}, {{0x10a63, 0x031ca}}, {{0x10d77, 0x030d9}}, {{0x11098, 0x02fe9}}, {{0x113c7, 0x02efa}}, {{0x11704, 0x02e0c}},
{{0x11a51, 0x02d20}}, {{0x11dac, 0x02c35}}, {{0x12118, 0x02b4b}}, {{0x12494, 0x02a62}}, {{0x12821, 0x0297a}}, {{0x12bc0, 0x02894}}, {{0x12f71, 0x027ae}}, {{0x13336, 0x026ca}},
{{0x1370f, 0x025e6}}, {{0x13afd, 0x02504}}, {{0x13f01, 0x02423}}, {{0x1431b, 0x02343}}, {{0x1474e, 0x02264}}, {{0x14b99, 0x02186}}, {{0x14fff, 0x020a9}}, {{0x15480, 0x01fcd}},
{{0x1591e, 0x01ef3}}, {{0x15dda, 0x01e19}}, {{0x162b6, 0x01d40}}, {{0x167b4, 0x01c68}}, {{0x16cd5, 0x01b91}}, {{0x1721c, 0x01abb}}, {{0x1778a, 0x019e6}}, {{0x17d23, 0x01912}},
{{0x182e8, 0x0183f}}, {{0x188de, 0x0176d}}, {{0x18f06, 0x0169c}}, {{0x19564, 0x015cc}}, {{0x19bfc, 0x014fc}}, {{0x1a2d4, 0x0142e}}, {{0x1a9ee, 0x01360}}, {{0x1b151, 0x01294}},
{{0x1b903, 0x011c8}}, {{0x1c10b, 0x010fd}}, {{0x1c970, 0x01033}}, {{0x1d23c, 0x00f6a}}, {{0x1db78, 0x00ea2}}, {{0x1e531, 0x00dda}}, {{0x1ef74, 0x00d13}}, {{0x1fa51, 0x00c4e}},
{{0x205dd, 0x00b89}}, {{0x2122e, 0x00ac4}}, {{0x21f60, 0x00a01}}, {{0x22d96, 0x0093f}}, {{0x23cfc, 0x0087d}}, {{0x24dc9, 0x007bc}}, {{0x26044, 0x006fc}}, {{0x274ce, 0x0063c}},
{{0x28beb, 0x0057e}}, {{0x2a658, 0x004c0}}, {{0x2c531, 0x00403}}, {{0x2ea40, 0x00346}}, {{0x318a9, 0x0028b}}, {{0x356cb, 0x001d0}}, {{0x3b520, 0x00116}}, {{0x48000, 0x0005c}}
};
#endif
const uint32_t ProbModelTables::m_EstFracProb[128] =
{
0x041b5, 0x03df6, 0x04410, 0x03bbc, 0x04636, 0x039a3, 0x048e6, 0x036f6, 0x04bd3, 0x0340c, 0x04e5d, 0x03185, 0x050fa, 0x02eeb, 0x0534b, 0x02c9b,
0x0557e, 0x02a6a, 0x057b1, 0x02839, 0x059e4, 0x02608, 0x05bba, 0x02433, 0x05d8f, 0x0225e, 0x05f58, 0x02097, 0x060f7, 0x01efa, 0x06288, 0x01d69,
0x06427, 0x01bcb, 0x06581, 0x01a72, 0x066d4, 0x0191f, 0x0682f, 0x017c6, 0x0693e, 0x016b7, 0x06a80, 0x01576, 0x06b7e, 0x01478, 0x06ca1, 0x01356,
0x06da2, 0x01255, 0x06e88, 0x01170, 0x06f67, 0x01092, 0x0703e, 0x00fba, 0x07116, 0x00ee3, 0x071b7, 0x00e42, 0x0728f, 0x00d6a, 0x07323, 0x00cd6,
0x073e9, 0x00c11, 0x0747d, 0x00b7d, 0x0751e, 0x00add, 0x075b2, 0x00a49, 0x0761b, 0x009e0, 0x07697, 0x00964, 0x07719, 0x008e2, 0x07794, 0x00867,
0x077f1, 0x0080b, 0x0785b, 0x007a1, 0x078c9, 0x00733, 0x07932, 0x006ca, 0x0798f, 0x0066d, 0x079c6, 0x00636, 0x07a23, 0x005da, 0x07a7f, 0x0057d,
0x07ab7, 0x00546, 0x07afb, 0x00502, 0x07b32, 0x004cb, 0x07b7d, 0x00480, 0x07b9c, 0x00461, 0x07bf8, 0x00405, 0x07c17, 0x003e6, 0x07c55, 0x003a9,
0x07c8c, 0x00371, 0x07cbf, 0x0033f, 0x07cd0, 0x0032e, 0x07cf6, 0x00308, 0x07d2c, 0x002d1, 0x07d52, 0x002ab, 0x07d71, 0x0028c, 0x07f46, 0x000b5
};
const uint8_t ProbModelTables::m_LPSTable_64_4[64][4] =
{
{ 128, 176, 208, 240 },
{ 128, 167, 197, 227 },
{ 128, 158, 187, 216 },
{ 123, 150, 178, 205 },
{ 116, 142, 169, 195 },
{ 111, 135, 160, 185 },
{ 105, 128, 152, 175 },
{ 100, 122, 144, 166 },
{ 95, 116, 137, 158 },
{ 90, 110, 130, 150 },
{ 85, 104, 123, 142 },
{ 81, 99, 117, 135 },
{ 77, 94, 111, 128 },
{ 73, 89, 105, 122 },
{ 69, 85, 100, 116 },
{ 66, 80, 95, 110 },
{ 62, 76, 90, 104 },
{ 59, 72, 86, 99 },
{ 56, 69, 81, 94 },
{ 53, 65, 77, 89 },
{ 51, 62, 73, 85 },
{ 48, 59, 69, 80 },
{ 46, 56, 66, 76 },
{ 43, 53, 63, 72 },
{ 41, 50, 59, 69 },
{ 39, 48, 56, 65 },
{ 37, 45, 54, 62 },
{ 35, 43, 51, 59 },
{ 33, 41, 48, 56 },
{ 32, 39, 46, 53 },
{ 30, 37, 43, 50 },
{ 29, 35, 41, 48 },
{ 27, 33, 39, 45 },
{ 26, 31, 37, 43 },
{ 24, 30, 35, 41 },
{ 23, 28, 33, 39 },
{ 22, 27, 32, 37 },
{ 21, 26, 30, 35 },
{ 20, 24, 29, 33 },
{ 19, 23, 27, 31 },
{ 18, 22, 26, 30 },
{ 17, 21, 25, 28 },
{ 16, 20, 23, 27 },
{ 15, 19, 22, 25 },
{ 14, 18, 21, 24 },
{ 14, 17, 20, 23 },
{ 13, 16, 19, 22 },
{ 12, 15, 18, 21 },
{ 12, 14, 17, 20 },
{ 11, 14, 16, 19 },
{ 11, 13, 15, 18 },
{ 10, 12, 15, 17 },
{ 10, 12, 14, 16 },
{ 9, 11, 13, 15 },
{ 9, 11, 12, 14 },
{ 8, 10, 12, 14 },
{ 8, 9, 11, 13 },
{ 7, 9, 11, 12 },
{ 7, 9, 10, 12 },
{ 7, 8, 10, 11 },
{ 6, 8, 9, 11 },
{ 6, 7, 9, 10 },
{ 6, 7, 8, 9 },
{ 2, 2, 2, 2 }
};
#if JEM_TOOLS
const uint16_t ProbModelTables::m_LPSTable_512_64[512][64] =
{
{ 253, 257, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 325, 329, 333, 337, 341, 345, 349, 353, 357, 361, 365, 369, 373, 377, 381, 385, 389, 393, 397, 401, 405, 409, 413, 417, 421, 425, 429, 433, 437, 441, 445, 449, 453, 457, 461, 465, 469, 473, 477, 481, 485, 489, 493, 497, 501, 505,},
{ 253, 257, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 325, 329, 333, 337, 341, 345, 349, 353, 357, 361, 365, 369, 373, 377, 381, 385, 389, 393, 397, 401, 405, 409, 413, 417, 421, 425, 429, 433, 437, 441, 445, 449, 453, 457, 461, 465, 469, 473, 477, 481, 485, 489, 493, 497, 501, 505,},
{ 253, 257, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 325, 329, 333, 337, 341, 345, 349, 353, 357, 361, 365, 369, 373, 377, 381, 385, 389, 393, 397, 401, 405, 409, 413, 417, 421, 425, 429, 433, 437, 441, 445, 449, 453, 457, 461, 465, 469, 473, 477, 481, 485, 489, 493, 497, 501, 505,},
{ 253, 257, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 325, 329, 333, 337, 341, 345, 349, 353, 357, 361, 365, 369, 373, 377, 381, 385, 389, 393, 397, 401, 405, 409, 413, 417, 421, 425, 429, 433, 437, 441, 445, 449, 453, 457, 461, 465, 469, 473, 477, 481, 485, 489, 493, 497, 501, 505,},
{ 253, 257, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 325, 329, 333, 337, 341, 345, 349, 353, 357, 361, 365, 369, 373, 377, 381, 385, 389, 393, 396, 400, 404, 408, 412, 416, 420, 424, 428, 432, 436, 440, 444, 448, 452, 456, 460, 464, 468, 472, 476, 480, 484, 488, 492, 496, 500, 504,},
{ 253, 257, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 324, 328, 332, 336, 340, 344, 348, 352, 356, 360, 364, 368, 372, 376, 380, 384, 388, 392, 396, 400, 404, 408, 412, 415, 419, 423, 427, 431, 435, 439, 443, 447, 451, 455, 459, 463, 467, 471, 475, 479, 483, 487, 491, 495, 499, 503,},
{ 253, 257, 261, 265, 269, 272, 276, 280, 284, 288, 292, 296, 300, 304, 308, 312, 316, 320, 324, 328, 332, 336, 340, 344, 348, 351, 355, 359, 363, 367, 371, 375, 379, 383, 387, 391, 395, 399, 403, 407, 411, 415, 419, 423, 427, 430, 434, 438, 442, 446, 450, 454, 458, 462, 466, 470, 474, 478, 482, 486, 490, 494, 498, 502,},
{ 252, 256, 260, 264, 268, 272, 276, 280, 284, 288, 292, 296, 300, 303, 307, 311, 315, 319, 323, 327, 331, 335, 339, 343, 347, 351, 355, 359, 363, 367, 370, 374, 378, 382, 386, 390, 394, 398, 402, 406, 410, 414, 418, 422, 426, 430, 434, 437, 441, 445, 449, 453, 457, 461, 465, 469, 473, 477, 481, 485, 489, 493, 497, 501,},
{ 252, 256, 260, 264, 267, 271, 275, 279, 283, 287, 291, 295, 299, 303, 307, 311, 315, 319, 323, 326, 330, 334, 338, 342, 346, 350, 354, 358, 362, 366, 370, 374, 378, 382, 385, 389, 393, 397, 401, 405, 409, 413, 417, 421, 425, 429, 433, 437, 441, 444, 448, 452, 456, 460, 464, 468, 472, 476, 480, 484, 488, 492, 496, 500,},
{ 251, 255, 259, 263, 267, 271, 275, 279, 283, 287, 291, 294, 298, 302, 306, 310, 314, 318, 322, 326, 330, 334, 338, 342, 345, 349, 353, 357, 361, 365, 369, 373, 377, 381, 385, 389, 393, 397, 400, 404, 408, 412, 416, 420, 424, 428, 432, 436, 440, 444, 448, 451, 455, 459, 463, 467, 471, 475, 479, 483, 487, 491, 495, 499,},
{ 251, 255, 259, 263, 266, 270, 274, 278, 282, 286, 290, 294, 298, 302, 306, 310, 313, 317, 321, 325, 329, 333, 337, 341, 345, 349, 353, 357, 360, 364, 368, 372, 376, 380, 384, 388, 392, 396, 400, 404, 407, 411, 415, 419, 423, 427, 431, 435, 439, 443, 447, 451, 454, 458, 462, 466, 470, 474, 478, 482, 486, 490, 494, 498,},
{ 250, 254, 258, 262, 266, 270, 274, 278, 282, 285, 289, 293, 297, 301, 305, 309, 313, 317, 321, 325, 328, 332, 336, 340, 344, 348, 352, 356, 360, 364, 368, 371, 375, 379, 383, 387, 391, 395, 399, 403, 407, 411, 414, 418, 422, 426, 430, 434, 438, 442, 446, 450, 454, 457, 461, 465, 469, 473, 477, 481, 485, 489, 493, 497,},
{ 250, 254, 258, 261, 265, 269, 273, 277, 281, 285, 289, 293, 297, 300, 304, 308, 312, 316, 320, 324, 328, 332, 336, 340, 343, 347, 351, 355, 359, 363, 367, 371, 375, 379, 382, 386, 390, 394, 398, 402, 406, 410, 414, 418, 421, 425, 429, 433, 437, 441, 445, 449, 453, 457, 460, 464, 468, 472, 476, 480, 484, 488, 492, 496,},
{ 249, 253, 257, 261, 265, 269, 273, 277, 280, 284, 288, 292, 296, 300, 304, 308, 312, 315, 319, 323, 327, 331, 335, 339, 343, 347, 351, 354, 358, 362, 366, 370, 374, 378, 382, 386, 389, 393, 397, 401, 405, 409, 413, 417, 421, 425, 428, 432, 436, 440, 444, 448, 452, 456, 460, 463, 467, 471, 475, 479, 483, 487, 491, 495,},
{ 249, 253, 257, 260, 264, 268, 272, 276, 280, 284, 288, 292, 295, 299, 303, 307, 311, 315, 319, 323, 326, 330, 334, 338, 342, 346, 350, 354, 358, 361, 365, 369, 373, 377, 381, 385, 389, 393, 396, 400, 404, 408, 412, 416, 420, 424, 428, 431, 435, 439, 443, 447, 451, 455, 459, 463, 466, 470, 474, 478, 482, 486, 490, 494,},
{ 248, 252, 256, 260, 264, 268, 272, 275, 279, 283, 287, 291, 295, 299, 303, 306, 310, 314, 318, 322, 326, 330, 334, 337, 341, 345, 349, 353, 357, 361, 365, 368, 372, 376, 380, 384, 388, 392, 396, 400, 403, 407, 411, 415, 419, 423, 427, 431, 434, 438, 442, 446, 450, 454, 458, 462, 465, 469, 473, 477, 481, 485, 489, 493,},
{ 248, 252, 255, 259, 263, 267, 271, 275, 279, 283, 286, 290, 294, 298, 302, 306, 310, 314, 317, 321, 325, 329, 333, 337, 341, 345, 348, 352, 356, 360, 364, 368, 372, 375, 379, 383, 387, 391, 395, 399, 403, 406, 410, 414, 418, 422, 426, 430, 434, 437, 441, 445, 449, 453, 457, 461, 465, 468, 472, 476, 480, 484, 488, 492,},
{ 247, 251, 255, 259, 263, 267, 270, 274, 278, 282, 286, 290, 294, 297, 301, 305, 309, 313, 317, 321, 325, 328, 332, 336, 340, 344, 348, 352, 355, 359, 363, 367, 371, 375, 379, 382, 386, 390, 394, 398, 402, 406, 410, 413, 417, 421, 425, 429, 433, 437, 440, 444, 448, 452, 456, 460, 464, 467, 471, 475, 479, 483, 487, 491,},
{ 247, 251, 254, 258, 262, 266, 270, 274, 278, 281, 285, 289, 293, 297, 301, 305, 308, 312, 316, 320, 324, 328, 332, 335, 339, 343, 347, 351, 355, 359, 362, 366, 370, 374, 378, 382, 386, 389, 393, 397, 401, 405, 409, 413, 416, 420, 424, 428, 432, 436, 440, 443, 447, 451, 455, 459, 463, 467, 470, 474, 478, 482, 486, 490,},
{ 246, 250, 254, 258, 262, 265, 269, 273, 277, 281, 285, 289, 292, 296, 300, 304, 308, 312, 316, 319, 323, 327, 331, 335, 339, 342, 346, 350, 354, 358, 362, 366, 369, 373, 377, 381, 385, 389, 392, 396, 400, 404, 408, 412, 416, 419, 423, 427, 431, 435, 439, 442, 446, 450, 454, 458, 462, 466, 469, 473, 477, 481, 485, 489,},
{ 246, 250, 253, 257, 261, 265, 269, 273, 276, 280, 284, 288, 292, 296, 300, 303, 307, 311, 315, 319, 323, 326, 330, 334, 338, 342, 346, 349, 353, 357, 361, 365, 369, 372, 376, 380, 384, 388, 392, 396, 399, 403, 407, 411, 415, 419, 422, 426, 430, 434, 438, 442, 445, 449, 453, 457, 461, 465, 468, 472, 476, 480, 484, 488,},
{ 245, 249, 253, 257, 261, 264, 268, 272, 276, 280, 284, 287, 291, 295, 299, 303, 307, 310, 314, 318, 322, 326, 330, 333, 337, 341, 345, 349, 353, 356, 360, 364, 368, 372, 376, 379, 383, 387, 391, 395, 399, 402, 406, 410, 414, 418, 422, 425, 429, 433, 437, 441, 445, 448, 452, 456, 460, 464, 468, 471, 475, 479, 483, 487,},
{ 245, 249, 252, 256, 260, 264, 268, 272, 275, 279, 283, 287, 291, 294, 298, 302, 306, 310, 314, 317, 321, 325, 329, 333, 337, 340, 344, 348, 352, 356, 359, 363, 367, 371, 375, 379, 382, 386, 390, 394, 398, 402, 405, 409, 413, 417, 421, 424, 428, 432, 436, 440, 444, 447, 451, 455, 459, 463, 467, 470, 474, 478, 482, 486,},
{ 244, 248, 252, 256, 260, 263, 267, 271, 275, 279, 282, 286, 290, 294, 298, 301, 305, 309, 313, 317, 321, 324, 328, 332, 336, 340, 343, 347, 351, 355, 359, 363, 366, 370, 374, 378, 382, 385, 389, 393, 397, 401, 405, 408, 412, 416, 420, 424, 427, 431, 435, 439, 443, 447, 450, 454, 458, 462, 466, 469, 473, 477, 481, 485,},
{ 244, 248, 251, 255, 259, 263, 267, 270, 274, 278, 282, 286, 289, 293, 297, 301, 305, 308, 312, 316, 320, 324, 328, 331, 335, 339, 343, 347, 350, 354, 358, 362, 366, 369, 373, 377, 381, 385, 388, 392, 396, 400, 404, 408, 411, 415, 419, 423, 427, 430, 434, 438, 442, 446, 449, 453, 457, 461, 465, 468, 472, 476, 480, 484,},
{ 243, 247, 251, 255, 258, 262, 266, 270, 274, 277, 281, 285, 289, 293, 296, 300, 304, 308, 312, 315, 319, 323, 327, 331, 334, 338, 342, 346, 350, 353, 357, 361, 365, 369, 372, 376, 380, 384, 388, 391, 395, 399, 403, 407, 410, 414, 418, 422, 426, 429, 433, 437, 441, 445, 448, 452, 456, 460, 464, 467, 471, 475, 479, 483,},
{ 243, 247, 250, 254, 258, 262, 266, 269, 273, 277, 281, 284, 288, 292, 296, 300, 303, 307, 311, 315, 319, 322, 326, 330, 334, 338, 341, 345, 349, 353, 357, 360, 364, 368, 372, 376, 379, 383, 387, 391, 394, 398, 402, 406, 410, 413, 417, 421, 425, 429, 432, 436, 440, 444, 448, 451, 455, 459, 463, 467, 470, 474, 478, 482,},
{ 242, 246, 250, 254, 257, 261, 265, 269, 273, 276, 280, 284, 288, 291, 295, 299, 303, 307, 310, 314, 318, 322, 326, 329, 333, 337, 341, 344, 348, 352, 356, 360, 363, 367, 371, 375, 379, 382, 386, 390, 394, 397, 401, 405, 409, 413, 416, 420, 424, 428, 432, 435, 439, 443, 447, 450, 454, 458, 462, 466, 469, 473, 477, 481,},
{ 242, 246, 249, 253, 257, 261, 264, 268, 272, 276, 280, 283, 287, 291, 295, 298, 302, 306, 310, 314, 317, 321, 325, 329, 332, 336, 340, 344, 348, 351, 355, 359, 363, 366, 370, 374, 378, 382, 385, 389, 393, 397, 400, 404, 408, 412, 416, 419, 423, 427, 431, 434, 438, 442, 446, 450, 453, 457, 461, 465, 468, 472, 476, 480,},
{ 241, 245, 249, 253, 256, 260, 264, 268, 271, 275, 279, 283, 286, 290, 294, 298, 302, 305, 309, 313, 317, 320, 324, 328, 332, 335, 339, 343, 347, 351, 354, 358, 362, 366, 369, 373, 377, 381, 384, 388, 392, 396, 400, 403, 407, 411, 415, 418, 422, 426, 430, 433, 437, 441, 445, 449, 452, 456, 460, 464, 467, 471, 475, 479,},
{ 241, 245, 248, 252, 256, 260, 263, 267, 271, 275, 278, 282, 286, 290, 293, 297, 301, 305, 308, 312, 316, 320, 324, 327, 331, 335, 339, 342, 346, 350, 354, 357, 361, 365, 369, 372, 376, 380, 384, 387, 391, 395, 399, 403, 406, 410, 414, 418, 421, 425, 429, 433, 436, 440, 444, 448, 451, 455, 459, 463, 466, 470, 474, 478,},
{ 240, 244, 248, 252, 255, 259, 263, 267, 270, 274, 278, 282, 285, 289, 293, 297, 300, 304, 308, 312, 315, 319, 323, 327, 330, 334, 338, 342, 345, 349, 353, 357, 360, 364, 368, 372, 375, 379, 383, 387, 390, 394, 398, 402, 405, 409, 413, 417, 420, 424, 428, 432, 435, 439, 443, 447, 450, 454, 458, 462, 465, 469, 473, 477,},
{ 240, 243, 247, 251, 255, 258, 262, 266, 270, 273, 277, 281, 285, 288, 292, 296, 300, 303, 307, 311, 315, 318, 322, 326, 330, 333, 337, 341, 345, 348, 352, 356, 360, 363, 367, 371, 375, 378, 382, 386, 390, 393, 397, 401, 405, 408, 412, 416, 420, 423, 427, 431, 435, 438, 442, 446, 450, 453, 457, 461, 465, 468, 472, 476,},
{ 239, 243, 247, 250, 254, 258, 262, 265, 269, 273, 277, 280, 284, 288, 292, 295, 299, 303, 307, 310, 314, 318, 321, 325, 329, 333, 336, 340, 344, 348, 351, 355, 359, 363, 366, 370, 374, 378, 381, 385, 389, 393, 396, 400, 404, 407, 411, 415, 419, 422, 426, 430, 434, 437, 441, 445, 449, 452, 456, 460, 464, 467, 471, 475,},
{ 239, 242, 246, 250, 254, 257, 261, 265, 269, 272, 276, 280, 284, 287, 291, 295, 298, 302, 306, 310, 313, 317, 321, 325, 328, 332, 336, 339, 343, 347, 351, 354, 358, 362, 366, 369, 373, 377, 381, 384, 388, 392, 395, 399, 403, 407, 410, 414, 418, 422, 425, 429, 433, 436, 440, 444, 448, 451, 455, 459, 463, 466, 470, 474,},
{ 238, 242, 246, 249, 253, 257, 261, 264, 268, 272, 275, 279, 283, 287, 290, 294, 298, 302, 305, 309, 313, 316, 320, 324, 328, 331, 335, 339, 342, 346, 350, 354, 357, 361, 365, 369, 372, 376, 380, 383, 387, 391, 395, 398, 402, 406, 409, 413, 417, 421, 424, 428, 432, 436, 439, 443, 447, 450, 454, 458, 462, 465, 469, 473,},
{ 238, 241, 245, 249, 253, 256, 260, 264, 267, 271, 275, 279, 282, 286, 290, 293, 297, 301, 305, 308, 312, 316, 319, 323, 327, 331, 334, 338, 342, 345, 349, 353, 357, 360, 364, 368, 371, 375, 379, 383, 386, 390, 394, 397, 401, 405, 409, 412, 416, 420, 423, 427, 431, 435, 438, 442, 446, 449, 453, 457, 461, 464, 468, 472,},
{ 237, 241, 245, 248, 252, 256, 259, 263, 267, 271, 274, 278, 282, 285, 289, 293, 297, 300, 304, 308, 311, 315, 319, 323, 326, 330, 334, 337, 341, 345, 348, 352, 356, 360, 363, 367, 371, 374, 378, 382, 386, 389, 393, 397, 400, 404, 408, 411, 415, 419, 423, 426, 430, 434, 437, 441, 445, 449, 452, 456, 460, 463, 467, 471,},
{ 237, 240, 244, 248, 252, 255, 259, 263, 266, 270, 274, 277, 281, 285, 289, 292, 296, 300, 303, 307, 311, 314, 318, 322, 326, 329, 333, 337, 340, 344, 348, 351, 355, 359, 363, 366, 370, 374, 377, 381, 385, 388, 392, 396, 400, 403, 407, 411, 414, 418, 422, 425, 429, 433, 437, 440, 444, 448, 451, 455, 459, 462, 466, 470,},
{ 236, 240, 244, 247, 251, 255, 258, 262, 266, 269, 273, 277, 281, 284, 288, 292, 295, 299, 303, 306, 310, 314, 317, 321, 325, 329, 332, 336, 340, 343, 347, 351, 354, 358, 362, 365, 369, 373, 377, 380, 384, 388, 391, 395, 399, 402, 406, 410, 413, 417, 421, 425, 428, 432, 436, 439, 443, 447, 450, 454, 458, 461, 465, 469,},
{ 236, 239, 243, 247, 250, 254, 258, 262, 265, 269, 273, 276, 280, 284, 287, 291, 295, 298, 302, 306, 309, 313, 317, 320, 324, 328, 332, 335, 339, 343, 346, 350, 354, 357, 361, 365, 368, 372, 376, 379, 383, 387, 390, 394, 398, 402, 405, 409, 413, 416, 420, 424, 427, 431, 435, 438, 442, 446, 449, 453, 457, 460, 464, 468,},
{ 235, 239, 243, 246, 250, 254, 257, 261, 265, 268, 272, 276, 279, 283, 287, 290, 294, 298, 301, 305, 309, 312, 316, 320, 323, 327, 331, 334, 338, 342, 346, 349, 353, 357, 360, 364, 368, 371, 375, 379, 382, 386, 390, 393, 397, 401, 404, 408, 412, 415, 419, 423, 426, 430, 434, 437, 441, 445, 448, 452, 456, 459, 463, 467,},
{ 235, 238, 242, 246, 249, 253, 257, 260, 264, 268, 271, 275, 279, 282, 286, 290, 293, 297, 301, 304, 308, 312, 315, 319, 323, 326, 330, 334, 337, 341, 345, 348, 352, 356, 359, 363, 367, 370, 374, 378, 381, 385, 389, 392, 396, 400, 403, 407, 411, 414, 418, 422, 425, 429, 433, 436, 440, 444, 447, 451, 455, 458, 462, 466,},
{ 234, 238, 242, 245, 249, 253, 256, 260, 264, 267, 271, 275, 278, 282, 285, 289, 293, 296, 300, 304, 307, 311, 315, 318, 322, 326, 329, 333, 337, 340, 344, 348, 351, 355, 359, 362, 366, 370, 373, 377, 381, 384, 388, 392, 395, 399, 403, 406, 410, 414, 417, 421, 425, 428, 432, 436, 439, 443, 447, 450, 454, 458, 461, 465,},
{ 234, 237, 241, 245, 248, 252, 256, 259, 263, 267, 270, 274, 278, 281, 285, 289, 292, 296, 299, 303, 307, 310, 314, 318, 321, 325, 329, 332, 336, 340, 343, 347, 351, 354, 358, 362, 365, 369, 373, 376, 380, 383, 387, 391, 394, 398, 402, 405, 409, 413, 416, 420, 424, 427, 431, 435, 438, 442, 446, 449, 453, 457, 460, 464,},
{ 233, 237, 241, 244, 248, 251, 255, 259, 262, 266, 270, 273, 277, 281, 284, 288, 292, 295, 299, 302, 306, 310, 313, 317, 321, 324, 328, 332, 335, 339, 343, 346, 350, 354, 357, 361, 364, 368, 372, 375, 379, 383, 386, 390, 394, 397, 401, 405, 408, 412, 415, 419, 423, 426, 430, 434, 437, 441, 445, 448, 452, 456, 459, 463,},
{ 233, 236, 240, 244, 247, 251, 255, 258, 262, 265, 269, 273, 276, 280, 284, 287, 291, 295, 298, 302, 305, 309, 313, 316, 320, 324, 327, 331, 335, 338, 342, 345, 349, 353, 356, 360, 364, 367, 371, 375, 378, 382, 385, 389, 393, 396, 400, 404, 407, 411, 415, 418, 422, 425, 429, 433, 436, 440, 444, 447, 451, 455, 458, 462,},
{ 232, 236, 240, 243, 247, 250, 254, 258, 261, 265, 269, 272, 276, 279, 283, 287, 290, 294, 298, 301, 305, 308, 312, 316, 319, 323, 327, 330, 334, 337, 341, 345, 348, 352, 356, 359, 363, 367, 370, 374, 377, 381, 385, 388, 392, 396, 399, 403, 406, 410, 414, 417, 421, 425, 428, 432, 435, 439, 443, 446, 450, 454, 457, 461,},
{ 232, 235, 239, 243, 246, 250, 253, 257, 261, 264, 268, 272, 275, 279, 282, 286, 290, 293, 297, 301, 304, 308, 311, 315, 319, 322, 326, 330, 333, 337, 340, 344, 348, 351, 355, 358, 362, 366, 369, 373, 377, 380, 384, 387, 391, 395, 398, 402, 406, 409, 413, 416, 420, 424, 427, 431, 435, 438, 442, 445, 449, 453, 456, 460,},
{ 231, 235, 238, 242, 246, 249, 253, 257, 260, 264, 267, 271, 275, 278, 282, 285, 289, 293, 296, 300, 304, 307, 311, 314, 318, 322, 325, 329, 332, 336, 340, 343, 347, 350, 354, 358, 361, 365, 369, 372, 376, 379, 383, 387, 390, 394, 397, 401, 405, 408, 412, 416, 419, 423, 426, 430, 434, 437, 441, 444, 448, 452, 455, 459,},
{ 231, 234, 238, 242, 245, 249, 252, 256, 260, 263, 267, 270, 274, 278, 281, 285, 288, 292, 296, 299, 303, 306, 310, 314, 317, 321, 324, 328, 332, 335, 339, 343, 346, 350, 353, 357, 361, 364, 368, 371, 375, 379, 382, 386, 389, 393, 397, 400, 404, 407, 411, 415, 418, 422, 425, 429, 433, 436, 440, 443, 447, 451, 454, 458,},
{ 230, 234, 237, 241, 245, 248, 252, 255, 259, 263, 266, 270, 273, 277, 281, 284, 288, 291, 295, 299, 302, 306, 309, 313, 317, 320, 324, 327, 331, 335, 338, 342, 345, 349, 353, 356, 360, 363, 367, 371, 374, 378, 381, 385, 389, 392, 396, 399, 403, 407, 410, 414, 417, 421, 425, 428, 432, 435, 439, 443, 446, 450, 453, 457,},
{ 230, 233, 237, 241, 244, 248, 251, 255, 258, 262, 266, 269, 273, 276, 280, 284, 287, 291, 294, 298, 302, 305, 309, 312, 316, 319, 323, 327, 330, 334, 337, 341, 345, 348, 352, 355, 359, 363, 366, 370, 373, 377, 381, 384, 388, 391, 395, 398, 402, 406, 409, 413, 416, 420, 424, 427, 431, 434, 438, 442, 445, 449, 452, 456,},
{ 229, 233, 236, 240, 244, 247, 251, 254, 258, 261, 265, 269, 272, 276, 279, 283, 287, 290, 294, 297, 301, 304, 308, 312, 315, 319, 322, 326, 330, 333, 337, 340, 344, 347, 351, 355, 358, 362, 365, 369, 373, 376, 380, 383, 387, 390, 394, 398, 401, 405, 408, 412, 416, 419, 423, 426, 430, 433, 437, 441, 444, 448, 451, 455,},
{ 229, 232, 236, 239, 243, 247, 250, 254, 257, 261, 264, 268, 272, 275, 279, 282, 286, 290, 293, 297, 300, 304, 307, 311, 315, 318, 322, 325, 329, 332, 336, 340, 343, 347, 350, 354, 357, 361, 365, 368, 372, 375, 379, 382, 386, 390, 393, 397, 400, 404, 407, 411, 415, 418, 422, 425, 429, 432, 436, 440, 443, 447, 450, 454,},
{ 228, 232, 235, 239, 243, 246, 250, 253, 257, 260, 264, 267, 271, 275, 278, 282, 285, 289, 292, 296, 300, 303, 307, 310, 314, 317, 321, 325, 328, 332, 335, 339, 342, 346, 350, 353, 357, 360, 364, 367, 371, 374, 378, 382, 385, 389, 392, 396, 399, 403, 407, 410, 414, 417, 421, 424, 428, 432, 435, 439, 442, 446, 449, 453,},
{ 228, 231, 235, 238, 242, 246, 249, 253, 256, 260, 263, 267, 270, 274, 278, 281, 285, 288, 292, 295, 299, 302, 306, 310, 313, 317, 320, 324, 327, 331, 335, 338, 342, 345, 349, 352, 356, 359, 363, 367, 370, 374, 377, 381, 384, 388, 391, 395, 399, 402, 406, 409, 413, 416, 420, 423, 427, 431, 434, 438, 441, 445, 448, 452,},
{ 227, 231, 234, 238, 241, 245, 249, 252, 256, 259, 263, 266, 270, 273, 277, 281, 284, 288, 291, 295, 298, 302, 305, 309, 312, 316, 320, 323, 327, 330, 334, 337, 341, 344, 348, 352, 355, 359, 362, 366, 369, 373, 376, 380, 383, 387, 391, 394, 398, 401, 405, 408, 412, 415, 419, 423, 426, 430, 433, 437, 440, 444, 447, 451,},
{ 227, 230, 234, 237, 241, 244, 248, 252, 255, 259, 262, 266, 269, 273, 276, 280, 283, 287, 291, 294, 298, 301, 305, 308, 312, 315, 319, 322, 326, 329, 333, 337, 340, 344, 347, 351, 354, 358, 361, 365, 368, 372, 376, 379, 383, 386, 390, 393, 397, 400, 404, 407, 411, 415, 418, 422, 425, 429, 432, 436, 439, 443, 446, 450,},
{ 226, 230, 233, 237, 240, 244, 247, 251, 255, 258, 262, 265, 269, 272, 276, 279, 283, 286, 290, 293, 297, 300, 304, 308, 311, 315, 318, 322, 325, 329, 332, 336, 339, 343, 346, 350, 354, 357, 361, 364, 368, 371, 375, 378, 382, 385, 389, 392, 396, 399, 403, 407, 410, 414, 417, 421, 424, 428, 431, 435, 438, 442, 445, 449,},
{ 226, 229, 233, 236, 240, 243, 247, 250, 254, 257, 261, 265, 268, 272, 275, 279, 282, 286, 289, 293, 296, 300, 303, 307, 310, 314, 317, 321, 325, 328, 332, 335, 339, 342, 346, 349, 353, 356, 360, 363, 367, 370, 374, 377, 381, 384, 388, 392, 395, 399, 402, 406, 409, 413, 416, 420, 423, 427, 430, 434, 437, 441, 444, 448,},
{ 225, 229, 232, 236, 239, 243, 246, 250, 253, 257, 260, 264, 267, 271, 275, 278, 282, 285, 289, 292, 296, 299, 303, 306, 310, 313, 317, 320, 324, 327, 331, 334, 338, 341, 345, 348, 352, 355, 359, 363, 366, 370, 373, 377, 380, 384, 387, 391, 394, 398, 401, 405, 408, 412, 415, 419, 422, 426, 429, 433, 436, 440, 443, 447,},
{ 225, 228, 232, 235, 239, 242, 246, 249, 253, 256, 260, 263, 267, 270, 274, 277, 281, 284, 288, 291, 295, 298, 302, 306, 309, 313, 316, 320, 323, 327, 330, 334, 337, 341, 344, 348, 351, 355, 358, 362, 365, 369, 372, 376, 379, 383, 386, 390, 393, 397, 400, 404, 407, 411, 414, 418, 421, 425, 428, 432, 435, 439, 442, 446,},
{ 224, 228, 231, 235, 238, 242, 245, 249, 252, 256, 259, 263, 266, 270, 273, 277, 280, 284, 287, 291, 294, 298, 301, 305, 308, 312, 315, 319, 322, 326, 329, 333, 336, 340, 343, 347, 350, 354, 357, 361, 364, 368, 371, 375, 378, 382, 385, 389, 392, 396, 399, 403, 406, 410, 413, 417, 420, 424, 427, 431, 434, 438, 441, 445,},
{ 224, 227, 231, 234, 238, 241, 245, 248, 252, 255, 259, 262, 266, 269, 273, 276, 280, 283, 287, 290, 294, 297, 301, 304, 308, 311, 315, 318, 322, 325, 329, 332, 336, 339, 343, 346, 350, 353, 357, 360, 364, 367, 371, 374, 378, 381, 385, 388, 392, 395, 399, 402, 406, 409, 413, 416, 420, 423, 427, 430, 434, 437, 441, 444,},
{ 223, 227, 230, 234, 237, 241, 244, 248, 251, 255, 258, 262, 265, 269, 272, 276, 279, 283, 286, 290, 293, 297, 300, 303, 307, 310, 314, 317, 321, 324, 328, 331, 335, 338, 342, 345, 349, 352, 356, 359, 363, 366, 370, 373, 377, 380, 384, 387, 391, 394, 398, 401, 405, 408, 412, 415, 419, 422, 426, 429, 433, 436, 440, 443,},
{ 223, 226, 230, 233, 237, 240, 244, 247, 251, 254, 258, 261, 265, 268, 271, 275, 278, 282, 285, 289, 292, 296, 299, 303, 306, 310, 313, 317, 320, 324, 327, 331, 334, 338, 341, 345, 348, 352, 355, 358, 362, 365, 369, 372, 376, 379, 383, 386, 390, 393, 397, 400, 404, 407, 411, 414, 418, 421, 425, 428, 432, 435, 439, 442,},
{ 222, 226, 229, 233, 236, 240, 243, 247, 250, 254, 257, 260, 264, 267, 271, 274, 278, 281, 285, 288, 292, 295, 299, 302, 306, 309, 313, 316, 319, 323, 326, 330, 333, 337, 340, 344, 347, 351, 354, 358, 361, 365, 368, 372, 375, 379, 382, 385, 389, 392, 396, 399, 403, 406, 410, 413, 417, 420, 424, 427, 431, 434, 438, 441,},
{ 222, 225, 229, 232, 236, 239, 243, 246, 249, 253, 256, 260, 263, 267, 270, 274, 277, 281, 284, 288, 291, 295, 298, 301, 305, 308, 312, 315, 319, 322, 326, 329, 333, 336, 340, 343, 346, 350, 353, 357, 360, 364, 367, 371, 374, 378, 381, 385, 388, 392, 395, 398, 402, 405, 409, 412, 416, 419, 423, 426, 430, 433, 437, 440,},
{ 221, 225, 228, 232, 235, 239, 242, 245, 249, 252, 256, 259, 263, 266, 270, 273, 277, 280, 283, 287, 290, 294, 297, 301, 304, 308, 311, 315, 318, 322, 325, 328, 332, 335, 339, 342, 346, 349, 353, 356, 360, 363, 366, 370, 373, 377, 380, 384, 387, 391, 394, 398, 401, 404, 408, 411, 415, 418, 422, 425, 429, 432, 436, 439,},
{ 221, 224, 228, 231, 235, 238, 241, 245, 248, 252, 255, 259, 262, 266, 269, 272, 276, 279, 283, 286, 290, 293, 297, 300, 304, 307, 310, 314, 317, 321, 324, 328, 331, 335, 338, 341, 345, 348, 352, 355, 359, 362, 366, 369, 373, 376, 379, 383, 386, 390, 393, 397, 400, 404, 407, 410, 414, 417, 421, 424, 428, 431, 435, 438,},
{ 220, 224, 227, 231, 234, 237, 241, 244, 248, 251, 255, 258, 262, 265, 268, 272, 275, 279, 282, 286, 289, 293, 296, 299, 303, 306, 310, 313, 317, 320, 323, 327, 330, 334, 337, 341, 344, 348, 351, 354, 358, 361, 365, 368, 372, 375, 379, 382, 385, 389, 392, 396, 399, 403, 406, 410, 413, 416, 420, 423, 427, 430, 434, 437,},
{ 220, 223, 227, 230, 233, 237, 240, 244, 247, 251, 254, 258, 261, 264, 268, 271, 275, 278, 282, 285, 288, 292, 295, 299, 302, 306, 309, 312, 316, 319, 323, 326, 330, 333, 336, 340, 343, 347, 350, 354, 357, 361, 364, 367, 371, 374, 378, 381, 385, 388, 391, 395, 398, 402, 405, 409, 412, 415, 419, 422, 426, 429, 433, 436,},
{ 219, 223, 226, 230, 233, 236, 240, 243, 247, 250, 254, 257, 260, 264, 267, 271, 274, 277, 281, 284, 288, 291, 295, 298, 301, 305, 308, 312, 315, 319, 322, 325, 329, 332, 336, 339, 343, 346, 349, 353, 356, 360, 363, 367, 370, 373, 377, 380, 384, 387, 391, 394, 397, 401, 404, 408, 411, 415, 418, 421, 425, 428, 432, 435,},
{ 219, 222, 226, 229, 232, 236, 239, 243, 246, 250, 253, 256, 260, 263, 267, 270, 273, 277, 280, 284, 287, 291, 294, 297, 301, 304, 308, 311, 314, 318, 321, 325, 328, 332, 335, 338, 342, 345, 349, 352, 355, 359, 362, 366, 369, 373, 376, 379, 383, 386, 390, 393, 396, 400, 403, 407, 410, 414, 417, 420, 424, 427, 431, 434,},
{ 218, 222, 225, 228, 232, 235, 239, 242, 246, 249, 252, 256, 259, 263, 266, 269, 273, 276, 280, 283, 286, 290, 293, 297, 300, 304, 307, 310, 314, 317, 321, 324, 327, 331, 334, 338, 341, 344, 348, 351, 355, 358, 361, 365, 368, 372, 375, 379, 382, 385, 389, 392, 396, 399, 402, 406, 409, 413, 416, 419, 423, 426, 430, 433,},
{ 218, 221, 225, 228, 231, 235, 238, 242, 245, 248, 252, 255, 259, 262, 265, 269, 272, 276, 279, 282, 286, 289, 293, 296, 299, 303, 306, 310, 313, 316, 320, 323, 327, 330, 333, 337, 340, 344, 347, 350, 354, 357, 361, 364, 367, 371, 374, 378, 381, 384, 388, 391, 395, 398, 401, 405, 408, 412, 415, 418, 422, 425, 429, 432,},
{ 217, 221, 224, 227, 231, 234, 238, 241, 244, 248, 251, 255, 258, 261, 265, 268, 272, 275, 278, 282, 285, 289, 292, 295, 299, 302, 306, 309, 312, 316, 319, 322, 326, 329, 333, 336, 339, 343, 346, 350, 353, 356, 360, 363, 367, 370, 373, 377, 380, 384, 387, 390, 394, 397, 401, 404, 407, 411, 414, 418, 421, 424, 428, 431,},
{ 217, 220, 224, 227, 230, 234, 237, 240, 244, 247, 251, 254, 257, 261, 264, 268, 271, 274, 278, 281, 284, 288, 291, 295, 298, 301, 305, 308, 312, 315, 318, 322, 325, 329, 332, 335, 339, 342, 345, 349, 352, 356, 359, 362, 366, 369, 373, 376, 379, 383, 386, 389, 393, 396, 400, 403, 406, 410, 413, 417, 420, 423, 427, 430,},
{ 216, 220, 223, 226, 230, 233, 237, 240, 243, 247, 250, 253, 257, 260, 264, 267, 270, 274, 277, 280, 284, 287, 291, 294, 297, 301, 304, 307, 311, 314, 318, 321, 324, 328, 331, 335, 338, 341, 345, 348, 351, 355, 358, 362, 365, 368, 372, 375, 378, 382, 385, 389, 392, 395, 399, 402, 405, 409, 412, 416, 419, 422, 426, 429,},
{ 216, 219, 222, 226, 229, 233, 236, 239, 243, 246, 249, 253, 256, 260, 263, 266, 270, 273, 276, 280, 283, 287, 290, 293, 297, 300, 303, 307, 310, 314, 317, 320, 324, 327, 330, 334, 337, 340, 344, 347, 351, 354, 357, 361, 364, 367, 371, 374, 378, 381, 384, 388, 391, 394, 398, 401, 405, 408, 411, 415, 418, 421, 425, 428,},
{ 215, 219, 222, 225, 229, 232, 235, 239, 242, 246, 249, 252, 256, 259, 262, 266, 269, 272, 276, 279, 283, 286, 289, 293, 296, 299, 303, 306, 309, 313, 316, 320, 323, 326, 330, 333, 336, 340, 343, 346, 350, 353, 357, 360, 363, 367, 370, 373, 377, 380, 383, 387, 390, 394, 397, 400, 404, 407, 410, 414, 417, 420, 424, 427,},
{ 215, 218, 221, 225, 228, 232, 235, 238, 242, 245, 248, 252, 255, 258, 262, 265, 268, 272, 275, 279, 282, 285, 289, 292, 295, 299, 302, 305, 309, 312, 315, 319, 322, 325, 329, 332, 336, 339, 342, 346, 349, 352, 356, 359, 362, 366, 369, 372, 376, 379, 383, 386, 389, 393, 396, 399, 403, 406, 409, 413, 416, 419, 423, 426,},
{ 214, 218, 221, 224, 228, 231, 234, 238, 241, 244, 248, 251, 254, 258, 261, 264, 268, 271, 275, 278, 281, 285, 288, 291, 295, 298, 301, 305, 308, 311, 315, 318, 321, 325, 328, 331, 335, 338, 341, 345, 348, 352, 355, 358, 362, 365, 368, 372, 375, 378, 382, 385, 388, 392, 395, 398, 402, 405, 408, 412, 415, 418, 422, 425,},
{ 214, 217, 220, 224, 227, 230, 234, 237, 240, 244, 247, 250, 254, 257, 261, 264, 267, 271, 274, 277, 281, 284, 287, 291, 294, 297, 301, 304, 307, 311, 314, 317, 321, 324, 327, 331, 334, 337, 341, 344, 347, 351, 354, 357, 361, 364, 367, 371, 374, 377, 381, 384, 387, 391, 394, 397, 401, 404, 407, 411, 414, 417, 421, 424,},
{ 213, 217, 220, 223, 227, 230, 233, 237, 240, 243, 247, 250, 253, 257, 260, 263, 267, 270, 273, 277, 280, 283, 287, 290, 293, 297, 300, 303, 307, 310, 313, 317, 320, 323, 327, 330, 333, 337, 340, 343, 347, 350, 353, 357, 360, 363, 367, 370, 373, 377, 380, 383, 387, 390, 393, 397, 400, 403, 407, 410, 413, 417, 420, 423,},
{ 213, 216, 219, 223, 226, 229, 233, 236, 239, 243, 246, 249, 253, 256, 259, 263, 266, 269, 273, 276, 279, 283, 286, 289, 293, 296, 299, 303, 306, 309, 312, 316, 319, 322, 326, 329, 332, 336, 339, 342, 346, 349, 352, 356, 359, 362, 366, 369, 372, 376, 379, 382, 386, 389, 392, 396, 399, 402, 406, 409, 412, 416, 419, 422,},
{ 212, 216, 219, 222, 226, 229, 232, 235, 239, 242, 245, 249, 252, 255, 259, 262, 265, 269, 272, 275, 279, 282, 285, 289, 292, 295, 298, 302, 305, 308, 312, 315, 318, 322, 325, 328, 332, 335, 338, 342, 345, 348, 352, 355, 358, 361, 365, 368, 371, 375, 378, 381, 385, 388, 391, 395, 398, 401, 405, 408, 411, 415, 418, 421,},
{ 212, 215, 218, 222, 225, 228, 232, 235, 238, 242, 245, 248, 251, 255, 258, 261, 265, 268, 271, 275, 278, 281, 285, 288, 291, 294, 298, 301, 304, 308, 311, 314, 318, 321, 324, 328, 331, 334, 337, 341, 344, 347, 351, 354, 357, 361, 364, 367, 371, 374, 377, 380, 384, 387, 390, 394, 397, 400, 404, 407, 410, 414, 417, 420,},
{ 211, 215, 218, 221, 224, 228, 231, 234, 238, 241, 244, 248, 251, 254, 257, 261, 264, 267, 271, 274, 277, 281, 284, 287, 290, 294, 297, 300, 304, 307, 310, 314, 317, 320, 323, 327, 330, 333, 337, 340, 343, 347, 350, 353, 356, 360, 363, 366, 370, 373, 376, 380, 383, 386, 389, 393, 396, 399, 403, 406, 409, 413, 416, 419,},
{ 211, 214, 217, 221, 224, 227, 231, 234, 237, 240, 244, 247, 250, 254, 257, 260, 263, 267, 270, 273, 277, 280, 283, 286, 290, 293, 296, 300, 303, 306, 310, 313, 316, 319, 323, 326, 329, 333, 336, 339, 342, 346, 349, 352, 356, 359, 362, 366, 369, 372, 375, 379, 382, 385, 389, 392, 395, 398, 402, 405, 408, 412, 415, 418,},
{ 210, 214, 217, 220, 223, 227, 230, 233, 237, 240, 243, 246, 250, 253, 256, 260, 263, 266, 269, 273, 276, 279, 283, 286, 289, 292, 296, 299, 302, 306, 309, 312, 315, 319, 322, 325, 329, 332, 335, 338, 342, 345, 348, 352, 355, 358, 361, 365, 368, 371, 375, 378, 381, 384, 388, 391, 394, 398, 401, 404, 407, 411, 414, 417,},
{ 210, 213, 216, 220, 223, 226, 229, 233, 236, 239, 243, 246, 249, 252, 256, 259, 262, 265, 269, 272, 275, 279, 282, 285, 288, 292, 295, 298, 302, 305, 308, 311, 315, 318, 321, 324, 328, 331, 334, 338, 341, 344, 347, 351, 354, 357, 361, 364, 367, 370, 374, 377, 380, 383, 387, 390, 393, 397, 400, 403, 406, 410, 413, 416,},
{ 209, 213, 216, 219, 222, 226, 229, 232, 235, 239, 242, 245, 248, 252, 255, 258, 262, 265, 268, 271, 275, 278, 281, 284, 288, 291, 294, 298, 301, 304, 307, 311, 314, 317, 320, 324, 327, 330, 333, 337, 340, 343, 347, 350, 353, 356, 360, 363, 366, 369, 373, 376, 379, 383, 386, 389, 392, 396, 399, 402, 405, 409, 412, 415,},
{ 209, 212, 215, 219, 222, 225, 228, 232, 235, 238, 241, 245, 248, 251, 254, 258, 261, 264, 267, 271, 274, 277, 281, 284, 287, 290, 294, 297, 300, 303, 307, 310, 313, 316, 320, 323, 326, 329, 333, 336, 339, 342, 346, 349, 352, 356, 359, 362, 365, 369, 372, 375, 378, 382, 385, 388, 391, 395, 398, 401, 404, 408, 411, 414,},
{ 208, 212, 215, 218, 221, 225, 228, 231, 234, 238, 241, 244, 247, 251, 254, 257, 260, 264, 267, 270, 273, 277, 280, 283, 286, 290, 293, 296, 299, 303, 306, 309, 312, 316, 319, 322, 325, 329, 332, 335, 338, 342, 345, 348, 351, 355, 358, 361, 364, 368, 371, 374, 377, 381, 384, 387, 390, 394, 397, 400, 403, 407, 410, 413,},
{ 208, 211, 214, 217, 221, 224, 227, 230, 234, 237, 240, 243, 247, 250, 253, 256, 260, 263, 266, 269, 273, 276, 279, 282, 286, 289, 292, 295, 299, 302, 305, 308, 312, 315, 318, 321, 325, 328, 331, 334, 338, 341, 344, 347, 351, 354, 357, 360, 364, 367, 370, 373, 377, 380, 383, 386, 390, 393, 396, 399, 403, 406, 409, 412,},
{ 207, 210, 214, 217, 220, 223, 227, 230, 233, 236, 240, 243, 246, 249, 253, 256, 259, 262, 266, 269, 272, 275, 278, 282, 285, 288, 291, 295, 298, 301, 304, 308, 311, 314, 317, 321, 324, 327, 330, 334, 337, 340, 343, 346, 350, 353, 356, 359, 363, 366, 369, 372, 376, 379, 382, 385, 389, 392, 395, 398, 402, 405, 408, 411,},
{ 207, 210, 213, 216, 220, 223, 226, 229, 233, 236, 239, 242, 246, 249, 252, 255, 258, 262, 265, 268, 271, 275, 278, 281, 284, 288, 291, 294, 297, 300, 304, 307, 310, 313, 317, 320, 323, 326, 330, 333, 336, 339, 342, 346, 349, 352, 355, 359, 362, 365, 368, 372, 375, 378, 381, 384, 388, 391, 394, 397, 401, 404, 407, 410,},
{ 206, 209, 213, 216, 219, 222, 226, 229, 232, 235, 238, 242, 245, 248, 251, 255, 258, 261, 264, 267, 271, 274, 277, 280, 284, 287, 290, 293, 296, 300, 303, 306, 309, 313, 316, 319, 322, 325, 329, 332, 335, 338, 342, 345, 348, 351, 354, 358, 361, 364, 367, 371, 374, 377, 380, 383, 387, 390, 393, 396, 400, 403, 406, 409,},
{ 206, 209, 212, 215, 219, 222, 225, 228, 231, 235, 238, 241, 244, 248, 251, 254, 257, 260, 264, 267, 270, 273, 276, 280, 283, 286, 289, 293, 296, 299, 302, 305, 309, 312, 315, 318, 321, 325, 328, 331, 334, 338, 341, 344, 347, 350, 354, 357, 360, 363, 366, 370, 373, 376, 379, 383, 386, 389, 392, 395, 399, 402, 405, 408,},
{ 205, 208, 212, 215, 218, 221, 224, 228, 231, 234, 237, 241, 244, 247, 250, 253, 257, 260, 263, 266, 269, 273, 276, 279, 282, 285, 289, 292, 295, 298, 301, 305, 308, 311, 314, 317, 321, 324, 327, 330, 334, 337, 340, 343, 346, 350, 353, 356, 359, 362, 366, 369, 372, 375, 378, 382, 385, 388, 391, 394, 398, 401, 404, 407,},
{ 205, 208, 211, 214, 218, 221, 224, 227, 230, 234, 237, 240, 243, 246, 250, 253, 256, 259, 262, 266, 269, 272, 275, 278, 282, 285, 288, 291, 294, 298, 301, 304, 307, 310, 314, 317, 320, 323, 326, 330, 333, 336, 339, 342, 346, 349, 352, 355, 358, 362, 365, 368, 371, 374, 378, 381, 384, 387, 390, 394, 397, 400, 403, 406,},
{ 204, 207, 211, 214, 217, 220, 223, 227, 230, 233, 236, 239, 243, 246, 249, 252, 255, 259, 262, 265, 268, 271, 274, 278, 281, 284, 287, 290, 294, 297, 300, 303, 306, 310, 313, 316, 319, 322, 326, 329, 332, 335, 338, 341, 345, 348, 351, 354, 357, 361, 364, 367, 370, 373, 377, 380, 383, 386, 389, 393, 396, 399, 402, 405,},
{ 204, 207, 210, 213, 216, 220, 223, 226, 229, 232, 236, 239, 242, 245, 248, 252, 255, 258, 261, 264, 267, 271, 274, 277, 280, 283, 287, 290, 293, 296, 299, 302, 306, 309, 312, 315, 318, 322, 325, 328, 331, 334, 337, 341, 344, 347, 350, 353, 357, 360, 363, 366, 369, 372, 376, 379, 382, 385, 388, 392, 395, 398, 401, 404,},
{ 203, 206, 210, 213, 216, 219, 222, 225, 229, 232, 235, 238, 241, 245, 248, 251, 254, 257, 260, 264, 267, 270, 273, 276, 279, 283, 286, 289, 292, 295, 299, 302, 305, 308, 311, 314, 318, 321, 324, 327, 330, 333, 337, 340, 343, 346, 349, 353, 356, 359, 362, 365, 368, 372, 375, 378, 381, 384, 387, 391, 394, 397, 400, 403,},
{ 203, 206, 209, 212, 215, 219, 222, 225, 228, 231, 234, 238, 241, 244, 247, 250, 253, 257, 260, 263, 266, 269, 272, 276, 279, 282, 285, 288, 291, 295, 298, 301, 304, 307, 310, 314, 317, 320, 323, 326, 329, 333, 336, 339, 342, 345, 348, 352, 355, 358, 361, 364, 367, 371, 374, 377, 380, 383, 386, 390, 393, 396, 399, 402,},
{ 202, 205, 209, 212, 215, 218, 221, 224, 228, 231, 234, 237, 240, 243, 246, 250, 253, 256, 259, 262, 265, 269, 272, 275, 278, 281, 284, 288, 291, 294, 297, 300, 303, 307, 310, 313, 316, 319, 322, 325, 329, 332, 335, 338, 341, 344, 348, 351, 354, 357, 360, 363, 367, 370, 373, 376, 379, 382, 386, 389, 392, 395, 398, 401,},
{ 202, 205, 208, 211, 214, 218, 221, 224, 227, 230, 233, 236, 240, 243, 246, 249, 252, 255, 258, 262, 265, 268, 271, 274, 277, 281, 284, 287, 290, 293, 296, 299, 303, 306, 309, 312, 315, 318, 322, 325, 328, 331, 334, 337, 340, 344, 347, 350, 353, 356, 359, 363, 366, 369, 372, 375, 378, 381, 385, 388, 391, 394, 397, 400,},
{ 201, 204, 208, 211, 214, 217, 220, 223, 226, 230, 233, 236, 239, 242, 245, 248, 252, 255, 258, 261, 264, 267, 270, 274, 277, 280, 283, 286, 289, 292, 296, 299, 302, 305, 308, 311, 314, 318, 321, 324, 327, 330, 333, 336, 340, 343, 346, 349, 352, 355, 358, 362, 365, 368, 371, 374, 377, 380, 384, 387, 390, 393, 396, 399,},
{ 201, 204, 207, 210, 213, 216, 220, 223, 226, 229, 232, 235, 238, 242, 245, 248, 251, 254, 257, 260, 263, 267, 270, 273, 276, 279, 282, 285, 289, 292, 295, 298, 301, 304, 307, 311, 314, 317, 320, 323, 326, 329, 332, 336, 339, 342, 345, 348, 351, 354, 358, 361, 364, 367, 370, 373, 376, 380, 383, 386, 389, 392, 395, 398,},
{ 200, 203, 207, 210, 213, 216, 219, 222, 225, 228, 232, 235, 238, 241, 244, 247, 250, 253, 257, 260, 263, 266, 269, 272, 275, 278, 282, 285, 288, 291, 294, 297, 300, 304, 307, 310, 313, 316, 319, 322, 325, 329, 332, 335, 338, 341, 344, 347, 350, 354, 357, 360, 363, 366, 369, 372, 375, 379, 382, 385, 388, 391, 394, 397,},
{ 200, 203, 206, 209, 212, 215, 218, 222, 225, 228, 231, 234, 237, 240, 243, 247, 250, 253, 256, 259, 262, 265, 268, 272, 275, 278, 281, 284, 287, 290, 293, 297, 300, 303, 306, 309, 312, 315, 318, 321, 325, 328, 331, 334, 337, 340, 343, 346, 350, 353, 356, 359, 362, 365, 368, 371, 375, 378, 381, 384, 387, 390, 393, 396,},
{ 199, 202, 205, 209, 212, 215, 218, 221, 224, 227, 230, 233, 237, 240, 243, 246, 249, 252, 255, 258, 262, 265, 268, 271, 274, 277, 280, 283, 286, 290, 293, 296, 299, 302, 305, 308, 311, 314, 318, 321, 324, 327, 330, 333, 336, 339, 342, 346, 349, 352, 355, 358, 361, 364, 367, 370, 374, 377, 380, 383, 386, 389, 392, 395,},
{ 199, 202, 205, 208, 211, 214, 217, 220, 224, 227, 230, 233, 236, 239, 242, 245, 248, 252, 255, 258, 261, 264, 267, 270, 273, 276, 279, 283, 286, 289, 292, 295, 298, 301, 304, 307, 311, 314, 317, 320, 323, 326, 329, 332, 335, 338, 342, 345, 348, 351, 354, 357, 360, 363, 366, 370, 373, 376, 379, 382, 385, 388, 391, 394,},
{ 198, 201, 204, 208, 211, 214, 217, 220, 223, 226, 229, 232, 235, 239, 242, 245, 248, 251, 254, 257, 260, 263, 266, 269, 273, 276, 279, 282, 285, 288, 291, 294, 297, 300, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 335, 338, 341, 344, 347, 350, 353, 356, 359, 362, 366, 369, 372, 375, 378, 381, 384, 387, 390, 393,},
{ 198, 201, 204, 207, 210, 213, 216, 219, 222, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 260, 263, 266, 269, 272, 275, 278, 281, 284, 287, 290, 294, 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 362, 365, 368, 371, 374, 377, 380, 383, 386, 389, 392,},
{ 197, 200, 203, 206, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 247, 250, 253, 256, 259, 262, 265, 268, 271, 274, 277, 280, 284, 287, 290, 293, 296, 299, 302, 305, 308, 311, 314, 317, 321, 324, 327, 330, 333, 336, 339, 342, 345, 348, 351, 354, 358, 361, 364, 367, 370, 373, 376, 379, 382, 385, 388, 391,},
{ 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 231, 234, 237, 240, 243, 246, 249, 252, 255, 258, 261, 264, 267, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 304, 307, 310, 314, 317, 320, 323, 326, 329, 332, 335, 338, 341, 344, 347, 350, 354, 357, 360, 363, 366, 369, 372, 375, 378, 381, 384, 387, 390,},
{ 196, 199, 202, 205, 209, 212, 215, 218, 221, 224, 227, 230, 233, 236, 239, 242, 245, 248, 251, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 285, 288, 291, 294, 297, 301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 347, 350, 353, 356, 359, 362, 365, 368, 371, 374, 377, 380, 383, 386, 389,},
{ 196, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 229, 232, 236, 239, 242, 245, 248, 251, 254, 257, 260, 263, 266, 269, 272, 275, 278, 281, 284, 288, 291, 294, 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 327, 330, 333, 336, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379, 382, 385, 388,},
{ 195, 198, 201, 204, 207, 211, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 259, 262, 265, 268, 272, 275, 278, 281, 284, 287, 290, 293, 296, 299, 302, 305, 308, 311, 314, 317, 320, 323, 326, 329, 333, 336, 339, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369, 372, 375, 378, 381, 384, 387,},
{ 195, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 250, 253, 256, 259, 262, 265, 268, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 304, 307, 310, 313, 316, 320, 323, 326, 329, 332, 335, 338, 341, 344, 347, 350, 353, 356, 359, 362, 365, 368, 371, 374, 377, 380, 383, 386,},
{ 194, 197, 200, 203, 206, 209, 212, 215, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 249, 252, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 285, 288, 291, 294, 297, 300, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379, 382, 385,},
{ 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 230, 233, 236, 239, 242, 245, 248, 251, 254, 257, 260, 263, 266, 269, 272, 275, 279, 282, 285, 288, 291, 294, 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 327, 330, 333, 336, 339, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369, 372, 375, 378, 381, 384,},
{ 193, 196, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 229, 233, 236, 239, 242, 245, 248, 251, 254, 257, 260, 263, 266, 269, 272, 275, 278, 281, 284, 287, 290, 293, 296, 299, 302, 305, 308, 311, 314, 317, 320, 323, 326, 329, 332, 335, 338, 341, 344, 347, 350, 353, 356, 359, 362, 365, 368, 371, 374, 377, 380, 383,},
{ 193, 196, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 259, 262, 265, 268, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379, 382,},
{ 192, 195, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 249, 252, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 285, 288, 291, 294, 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 327, 330, 333, 336, 339, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369, 372, 375, 378, 381,},
{ 192, 195, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 249, 252, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 285, 288, 291, 294, 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 327, 330, 333, 336, 339, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369, 372, 375, 378, 381,},
{ 191, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 230, 233, 236, 239, 242, 245, 248, 251, 254, 257, 260, 263, 266, 269, 272, 275, 278, 281, 284, 287, 290, 293, 296, 299, 302, 305, 308, 311, 314, 317, 320, 323, 326, 329, 332, 335, 338, 341, 344, 347, 350, 353, 356, 359, 362, 365, 368, 371, 374, 377, 380,},
{ 191, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 259, 262, 265, 268, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376, 379,},
{ 190, 193, 196, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 259, 262, 265, 268, 271, 273, 276, 279, 282, 285, 288, 291, 294, 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 327, 330, 333, 336, 339, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369, 372, 375, 378,},
{ 190, 193, 196, 199, 202, 205, 208, 211, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 249, 252, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 285, 288, 291, 294, 296, 299, 302, 305, 308, 311, 314, 317, 320, 323, 326, 329, 332, 335, 338, 341, 344, 347, 350, 353, 356, 359, 362, 365, 368, 371, 374, 377,},
{ 189, 192, 195, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 242, 245, 248, 251, 254, 257, 260, 263, 266, 269, 272, 275, 278, 281, 284, 287, 290, 293, 296, 299, 302, 305, 308, 310, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373, 376,},
{ 189, 192, 195, 198, 201, 203, 206, 209, 212, 215, 218, 221, 224, 227, 230, 233, 236, 239, 242, 245, 248, 251, 254, 257, 260, 262, 265, 268, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 304, 307, 310, 313, 316, 319, 321, 324, 327, 330, 333, 336, 339, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369, 372, 375,},
{ 188, 191, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 256, 259, 262, 265, 268, 271, 274, 276, 279, 282, 285, 288, 291, 294, 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 326, 329, 332, 335, 338, 341, 344, 347, 350, 353, 356, 359, 362, 365, 368, 371, 374,},
{ 188, 191, 194, 197, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 243, 246, 249, 252, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 285, 287, 290, 293, 296, 299, 302, 305, 308, 311, 314, 317, 320, 323, 326, 329, 331, 334, 337, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370, 373,},
{ 187, 190, 193, 196, 199, 202, 205, 208, 211, 214, 217, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 249, 252, 255, 257, 260, 263, 266, 269, 272, 275, 278, 281, 284, 287, 290, 293, 296, 298, 301, 304, 307, 310, 313, 316, 319, 322, 325, 328, 331, 334, 336, 339, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369, 372,},
{ 187, 190, 193, 196, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 233, 236, 239, 242, 245, 248, 251, 254, 257, 260, 263, 266, 268, 271, 274, 277, 280, 283, 286, 289, 292, 295, 298, 301, 303, 306, 309, 312, 315, 318, 321, 324, 327, 330, 333, 336, 338, 341, 344, 347, 350, 353, 356, 359, 362, 365, 368, 371,},
{ 186, 189, 192, 195, 198, 201, 204, 207, 210, 212, 215, 218, 221, 224, 227, 230, 233, 236, 239, 242, 244, 247, 250, 253, 256, 259, 262, 265, 268, 271, 274, 276, 279, 282, 285, 288, 291, 294, 297, 300, 303, 306, 308, 311, 314, 317, 320, 323, 326, 329, 332, 335, 338, 340, 343, 346, 349, 352, 355, 358, 361, 364, 367, 370,},
{ 186, 189, 192, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 223, 226, 229, 232, 235, 238, 241, 244, 247, 250, 253, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 284, 287, 290, 293, 296, 299, 302, 305, 308, 311, 313, 316, 319, 322, 325, 328, 331, 334, 337, 340, 342, 345, 348, 351, 354, 357, 360, 363, 366, 369,},
{ 185, 188, 191, 194, 197, 200, 203, 206, 208, 211, 214, 217, 220, 223, 226, 229, 232, 234, 237, 240, 243, 246, 249, 252, 255, 258, 261, 263, 266, 269, 272, 275, 278, 281, 284, 287, 289, 292, 295, 298, 301, 304, 307, 310, 313, 316, 318, 321, 324, 327, 330, 333, 336, 339, 342, 344, 347, 350, 353, 356, 359, 362, 365, 368,},
{ 185, 188, 191, 193, 196, 199, 202, 205, 208, 211, 214, 217, 219, 222, 225, 228, 231, 234, 237, 240, 242, 245, 248, 251, 254, 257, 260, 263, 266, 268, 271, 274, 277, 280, 283, 286, 289, 292, 294, 297, 300, 303, 306, 309, 312, 315, 318, 320, 323, 326, 329, 332, 335, 338, 341, 344, 346, 349, 352, 355, 358, 361, 364, 367,},
{ 184, 187, 190, 193, 196, 199, 202, 204, 207, 210, 213, 216, 219, 222, 225, 227, 230, 233, 236, 239, 242, 245, 248, 250, 253, 256, 259, 262, 265, 268, 271, 273, 276, 279, 282, 285, 288, 291, 294, 297, 299, 302, 305, 308, 311, 314, 317, 320, 322, 325, 328, 331, 334, 337, 340, 343, 345, 348, 351, 354, 357, 360, 363, 366,},
{ 184, 187, 189, 192, 195, 198, 201, 204, 207, 210, 212, 215, 218, 221, 224, 227, 230, 233, 235, 238, 241, 244, 247, 250, 253, 256, 258, 261, 264, 267, 270, 273, 276, 278, 281, 284, 287, 290, 293, 296, 299, 301, 304, 307, 310, 313, 316, 319, 322, 324, 327, 330, 333, 336, 339, 342, 345, 347, 350, 353, 356, 359, 362, 365,},
{ 183, 186, 189, 192, 195, 198, 200, 203, 206, 209, 212, 215, 218, 220, 223, 226, 229, 232, 235, 238, 241, 243, 246, 249, 252, 255, 258, 261, 263, 266, 269, 272, 275, 278, 281, 283, 286, 289, 292, 295, 298, 301, 304, 306, 309, 312, 315, 318, 321, 324, 326, 329, 332, 335, 338, 341, 344, 346, 349, 352, 355, 358, 361, 364,},
{ 183, 186, 188, 191, 194, 197, 200, 203, 206, 208, 211, 214, 217, 220, 223, 226, 228, 231, 234, 237, 240, 243, 246, 248, 251, 254, 257, 260, 263, 266, 268, 271, 274, 277, 280, 283, 286, 288, 291, 294, 297, 300, 303, 306, 308, 311, 314, 317, 320, 323, 326, 328, 331, 334, 337, 340, 343, 346, 348, 351, 354, 357, 360, 363,},
{ 182, 185, 188, 191, 194, 196, 199, 202, 205, 208, 211, 214, 216, 219, 222, 225, 228, 231, 234, 236, 239, 242, 245, 248, 251, 253, 256, 259, 262, 265, 268, 271, 273, 276, 279, 282, 285, 288, 290, 293, 296, 299, 302, 305, 308, 310, 313, 316, 319, 322, 325, 327, 330, 333, 336, 339, 342, 345, 347, 350, 353, 356, 359, 362,},
{ 182, 185, 187, 190, 193, 196, 199, 202, 204, 207, 210, 213, 216, 219, 222, 224, 227, 230, 233, 236, 239, 241, 244, 247, 250, 253, 256, 258, 261, 264, 267, 270, 273, 275, 278, 281, 284, 287, 290, 293, 295, 298, 301, 304, 307, 310, 312, 315, 318, 321, 324, 327, 329, 332, 335, 338, 341, 344, 346, 349, 352, 355, 358, 361,},
{ 181, 184, 187, 190, 193, 195, 198, 201, 204, 207, 210, 212, 215, 218, 221, 224, 227, 229, 232, 235, 238, 241, 244, 246, 249, 252, 255, 258, 261, 263, 266, 269, 272, 275, 278, 280, 283, 286, 289, 292, 295, 297, 300, 303, 306, 309, 312, 314, 317, 320, 323, 326, 329, 331, 334, 337, 340, 343, 346, 348, 351, 354, 357, 360,},
{ 181, 184, 186, 189, 192, 195, 198, 201, 203, 206, 209, 212, 215, 217, 220, 223, 226, 229, 232, 234, 237, 240, 243, 246, 249, 251, 254, 257, 260, 263, 265, 268, 271, 274, 277, 280, 282, 285, 288, 291, 294, 297, 299, 302, 305, 308, 311, 313, 316, 319, 322, 325, 328, 330, 333, 336, 339, 342, 345, 347, 350, 353, 356, 359,},
{ 180, 183, 186, 189, 192, 194, 197, 200, 203, 206, 208, 211, 214, 217, 220, 222, 225, 228, 231, 234, 237, 239, 242, 245, 248, 251, 253, 256, 259, 262, 265, 268, 270, 273, 276, 279, 282, 284, 287, 290, 293, 296, 299, 301, 304, 307, 310, 313, 315, 318, 321, 324, 327, 330, 332, 335, 338, 341, 344, 346, 349, 352, 355, 358,},
{ 180, 183, 185, 188, 191, 194, 197, 199, 202, 205, 208, 211, 213, 216, 219, 222, 225, 227, 230, 233, 236, 239, 242, 244, 247, 250, 253, 256, 258, 261, 264, 267, 270, 272, 275, 278, 281, 284, 286, 289, 292, 295, 298, 301, 303, 306, 309, 312, 315, 317, 320, 323, 326, 329, 331, 334, 337, 340, 343, 345, 348, 351, 354, 357,},
{ 179, 182, 185, 188, 190, 193, 196, 199, 202, 204, 207, 210, 213, 216, 218, 221, 224, 227, 230, 232, 235, 238, 241, 244, 246, 249, 252, 255, 258, 260, 263, 266, 269, 272, 274, 277, 280, 283, 286, 288, 291, 294, 297, 300, 302, 305, 308, 311, 314, 316, 319, 322, 325, 328, 330, 333, 336, 339, 342, 344, 347, 350, 353, 356,},
{ 179, 182, 184, 187, 190, 193, 196, 198, 201, 204, 207, 209, 212, 215, 218, 221, 223, 226, 229, 232, 235, 237, 240, 243, 246, 249, 251, 254, 257, 260, 263, 265, 268, 271, 274, 277, 279, 282, 285, 288, 290, 293, 296, 299, 302, 304, 307, 310, 313, 316, 318, 321, 324, 327, 330, 332, 335, 338, 341, 344, 346, 349, 352, 355,},
{ 178, 181, 184, 187, 189, 192, 195, 198, 201, 203, 206, 209, 212, 214, 217, 220, 223, 226, 228, 231, 234, 237, 240, 242, 245, 248, 251, 253, 256, 259, 262, 265, 267, 270, 273, 276, 279, 281, 284, 287, 290, 292, 295, 298, 301, 304, 306, 309, 312, 315, 318, 320, 323, 326, 329, 331, 334, 337, 340, 343, 345, 348, 351, 354,},
{ 178, 181, 183, 186, 189, 192, 194, 197, 200, 203, 206, 208, 211, 214, 217, 219, 222, 225, 228, 231, 233, 236, 239, 242, 244, 247, 250, 253, 256, 258, 261, 264, 267, 269, 272, 275, 278, 281, 283, 286, 289, 292, 294, 297, 300, 303, 306, 308, 311, 314, 317, 319, 322, 325, 328, 331, 333, 336, 339, 342, 344, 347, 350, 353,},
{ 177, 180, 183, 186, 188, 191, 194, 197, 199, 202, 205, 208, 210, 213, 216, 219, 222, 224, 227, 230, 233, 235, 238, 241, 244, 246, 249, 252, 255, 258, 260, 263, 266, 269, 271, 274, 277, 280, 282, 285, 288, 291, 294, 296, 299, 302, 305, 307, 310, 313, 316, 318, 321, 324, 327, 330, 332, 335, 338, 341, 343, 346, 349, 352,},
{ 177, 180, 182, 185, 188, 191, 193, 196, 199, 202, 204, 207, 210, 213, 215, 218, 221, 224, 226, 229, 232, 235, 238, 240, 243, 246, 249, 251, 254, 257, 260, 262, 265, 268, 271, 273, 276, 279, 282, 284, 287, 290, 293, 296, 298, 301, 304, 307, 309, 312, 315, 318, 320, 323, 326, 329, 331, 334, 337, 340, 342, 345, 348, 351,},
{ 176, 179, 182, 185, 187, 190, 193, 196, 198, 201, 204, 207, 209, 212, 215, 218, 220, 223, 226, 229, 231, 234, 237, 240, 242, 245, 248, 251, 253, 256, 259, 262, 264, 267, 270, 273, 275, 278, 281, 284, 286, 289, 292, 295, 297, 300, 303, 306, 308, 311, 314, 317, 319, 322, 325, 328, 330, 333, 336, 339, 341, 344, 347, 350,},
{ 176, 178, 181, 184, 187, 189, 192, 195, 198, 200, 203, 206, 209, 211, 214, 217, 220, 222, 225, 228, 231, 233, 236, 239, 242, 244, 247, 250, 253, 255, 258, 261, 264, 266, 269, 272, 275, 277, 280, 283, 286, 288, 291, 294, 297, 299, 302, 305, 308, 310, 313, 316, 319, 321, 324, 327, 330, 332, 335, 338, 341, 343, 346, 349,},
{ 175, 178, 181, 183, 186, 189, 192, 194, 197, 200, 203, 205, 208, 211, 214, 216, 219, 222, 225, 227, 230, 233, 235, 238, 241, 244, 246, 249, 252, 255, 257, 260, 263, 266, 268, 271, 274, 277, 279, 282, 285, 288, 290, 293, 296, 298, 301, 304, 307, 309, 312, 315, 318, 320, 323, 326, 329, 331, 334, 337, 340, 342, 345, 348,},
{ 175, 177, 180, 183, 186, 188, 191, 194, 197, 199, 202, 205, 208, 210, 213, 216, 218, 221, 224, 227, 229, 232, 235, 238, 240, 243, 246, 248, 251, 254, 257, 259, 262, 265, 268, 270, 273, 276, 279, 281, 284, 287, 289, 292, 295, 298, 300, 303, 306, 309, 311, 314, 317, 319, 322, 325, 328, 330, 333, 336, 339, 341, 344, 347,},
{ 174, 177, 180, 182, 185, 188, 191, 193, 196, 199, 201, 204, 207, 210, 212, 215, 218, 221, 223, 226, 229, 231, 234, 237, 240, 242, 245, 248, 250, 253, 256, 259, 261, 264, 267, 270, 272, 275, 278, 280, 283, 286, 289, 291, 294, 297, 299, 302, 305, 308, 310, 313, 316, 319, 321, 324, 327, 329, 332, 335, 338, 340, 343, 346,},
{ 174, 176, 179, 182, 185, 187, 190, 193, 195, 198, 201, 204, 206, 209, 212, 214, 217, 220, 223, 225, 228, 231, 233, 236, 239, 242, 244, 247, 250, 252, 255, 258, 261, 263, 266, 269, 271, 274, 277, 280, 282, 285, 288, 290, 293, 296, 299, 301, 304, 307, 309, 312, 315, 318, 320, 323, 326, 328, 331, 334, 337, 339, 342, 345,},
{ 173, 176, 179, 181, 184, 187, 189, 192, 195, 198, 200, 203, 206, 208, 211, 214, 217, 219, 222, 225, 227, 230, 233, 236, 238, 241, 244, 246, 249, 252, 254, 257, 260, 263, 265, 268, 271, 273, 276, 279, 282, 284, 287, 290, 292, 295, 298, 300, 303, 306, 309, 311, 314, 317, 319, 322, 325, 328, 330, 333, 336, 338, 341, 344,},
{ 173, 175, 178, 181, 184, 186, 189, 192, 194, 197, 200, 202, 205, 208, 211, 213, 216, 219, 221, 224, 227, 229, 232, 235, 238, 240, 243, 246, 248, 251, 254, 256, 259, 262, 265, 267, 270, 273, 275, 278, 281, 283, 286, 289, 292, 294, 297, 300, 302, 305, 308, 310, 313, 316, 319, 321, 324, 327, 329, 332, 335, 337, 340, 343,},
{ 172, 175, 178, 180, 183, 186, 188, 191, 194, 196, 199, 202, 205, 207, 210, 213, 215, 218, 221, 223, 226, 229, 231, 234, 237, 240, 242, 245, 248, 250, 253, 256, 258, 261, 264, 266, 269, 272, 275, 277, 280, 283, 285, 288, 291, 293, 296, 299, 301, 304, 307, 310, 312, 315, 318, 320, 323, 326, 328, 331, 334, 336, 339, 342,},
{ 172, 174, 177, 180, 182, 185, 188, 191, 193, 196, 199, 201, 204, 207, 209, 212, 215, 217, 220, 223, 225, 228, 231, 233, 236, 239, 242, 244, 247, 250, 252, 255, 258, 260, 263, 266, 268, 271, 274, 276, 279, 282, 284, 287, 290, 293, 295, 298, 301, 303, 306, 309, 311, 314, 317, 319, 322, 325, 327, 330, 333, 335, 338, 341,},
{ 171, 174, 177, 179, 182, 185, 187, 190, 193, 195, 198, 201, 203, 206, 209, 211, 214, 217, 219, 222, 225, 227, 230, 233, 235, 238, 241, 243, 246, 249, 252, 254, 257, 260, 262, 265, 268, 270, 273, 276, 278, 281, 284, 286, 289, 292, 294, 297, 300, 302, 305, 308, 310, 313, 316, 318, 321, 324, 326, 329, 332, 334, 337, 340,},
{ 171, 173, 176, 179, 181, 184, 187, 189, 192, 195, 197, 200, 203, 205, 208, 211, 213, 216, 219, 221, 224, 227, 229, 232, 235, 237, 240, 243, 245, 248, 251, 253, 256, 259, 261, 264, 267, 269, 272, 275, 277, 280, 283, 285, 288, 291, 293, 296, 299, 301, 304, 307, 309, 312, 315, 317, 320, 323, 325, 328, 331, 333, 336, 339,},
{ 170, 173, 176, 178, 181, 184, 186, 189, 192, 194, 197, 200, 202, 205, 207, 210, 213, 215, 218, 221, 223, 226, 229, 231, 234, 237, 239, 242, 245, 247, 250, 253, 255, 258, 261, 263, 266, 269, 271, 274, 277, 279, 282, 285, 287, 290, 293, 295, 298, 301, 303, 306, 309, 311, 314, 317, 319, 322, 325, 327, 330, 333, 335, 338,},
{ 170, 172, 175, 178, 180, 183, 186, 188, 191, 194, 196, 199, 202, 204, 207, 210, 212, 215, 217, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 247, 249, 252, 255, 257, 260, 263, 265, 268, 271, 273, 276, 278, 281, 284, 286, 289, 292, 294, 297, 300, 302, 305, 308, 310, 313, 316, 318, 321, 324, 326, 329, 332, 334, 337,},
{ 169, 172, 175, 177, 180, 182, 185, 188, 190, 193, 196, 198, 201, 204, 206, 209, 212, 214, 217, 219, 222, 225, 227, 230, 233, 235, 238, 241, 243, 246, 249, 251, 254, 257, 259, 262, 264, 267, 270, 272, 275, 278, 280, 283, 286, 288, 291, 294, 296, 299, 301, 304, 307, 309, 312, 315, 317, 320, 323, 325, 328, 331, 333, 336,},
{ 169, 171, 174, 177, 179, 182, 185, 187, 190, 192, 195, 198, 200, 203, 206, 208, 211, 214, 216, 219, 221, 224, 227, 229, 232, 235, 237, 240, 243, 245, 248, 250, 253, 256, 258, 261, 264, 266, 269, 272, 274, 277, 279, 282, 285, 287, 290, 293, 295, 298, 301, 303, 306, 308, 311, 314, 316, 319, 322, 324, 327, 330, 332, 335,},
{ 168, 171, 174, 176, 179, 181, 184, 187, 189, 192, 195, 197, 200, 202, 205, 208, 210, 213, 216, 218, 221, 223, 226, 229, 231, 234, 237, 239, 242, 244, 247, 250, 252, 255, 258, 260, 263, 266, 268, 271, 273, 276, 279, 281, 284, 287, 289, 292, 294, 297, 300, 302, 305, 308, 310, 313, 315, 318, 321, 323, 326, 329, 331, 334,},
{ 168, 170, 173, 176, 178, 181, 183, 186, 189, 191, 194, 197, 199, 202, 204, 207, 210, 212, 215, 218, 220, 223, 225, 228, 231, 233, 236, 239, 241, 244, 246, 249, 252, 254, 257, 259, 262, 265, 267, 270, 273, 275, 278, 280, 283, 286, 288, 291, 294, 296, 299, 301, 304, 307, 309, 312, 315, 317, 320, 322, 325, 328, 330, 333,},
{ 167, 170, 172, 175, 178, 180, 183, 186, 188, 191, 193, 196, 199, 201, 204, 206, 209, 212, 214, 217, 220, 222, 225, 227, 230, 233, 235, 238, 240, 243, 246, 248, 251, 253, 256, 259, 261, 264, 267, 269, 272, 274, 277, 280, 282, 285, 287, 290, 293, 295, 298, 301, 303, 306, 308, 311, 314, 316, 319, 321, 324, 327, 329, 332,},
{ 167, 169, 172, 175, 177, 180, 182, 185, 188, 190, 193, 195, 198, 201, 203, 206, 208, 211, 214, 216, 219, 221, 224, 227, 229, 232, 234, 237, 240, 242, 245, 248, 250, 253, 255, 258, 261, 263, 266, 268, 271, 274, 276, 279, 281, 284, 287, 289, 292, 294, 297, 300, 302, 305, 307, 310, 313, 315, 318, 320, 323, 326, 328, 331,},
{ 166, 169, 171, 174, 177, 179, 182, 184, 187, 190, 192, 195, 197, 200, 203, 205, 208, 210, 213, 216, 218, 221, 223, 226, 229, 231, 234, 236, 239, 242, 244, 247, 249, 252, 255, 257, 260, 262, 265, 268, 270, 273, 275, 278, 281, 283, 286, 288, 291, 294, 296, 299, 301, 304, 307, 309, 312, 314, 317, 320, 322, 325, 327, 330,},
{ 166, 168, 171, 174, 176, 179, 181, 184, 186, 189, 192, 194, 197, 199, 202, 205, 207, 210, 212, 215, 218, 220, 223, 225, 228, 230, 233, 236, 238, 241, 243, 246, 249, 251, 254, 256, 259, 262, 264, 267, 269, 272, 275, 277, 280, 282, 285, 287, 290, 293, 295, 298, 300, 303, 306, 308, 311, 313, 316, 319, 321, 324, 326, 329,},
{ 165, 168, 170, 173, 176, 178, 181, 183, 186, 188, 191, 194, 196, 199, 201, 204, 207, 209, 212, 214, 217, 219, 222, 225, 227, 230, 232, 235, 238, 240, 243, 245, 248, 250, 253, 256, 258, 261, 263, 266, 269, 271, 274, 276, 279, 281, 284, 287, 289, 292, 294, 297, 300, 302, 305, 307, 310, 312, 315, 318, 320, 323, 325, 328,},
{ 165, 167, 170, 172, 175, 178, 180, 183, 185, 188, 190, 193, 196, 198, 201, 203, 206, 209, 211, 214, 216, 219, 221, 224, 227, 229, 232, 234, 237, 239, 242, 245, 247, 250, 252, 255, 257, 260, 263, 265, 268, 270, 273, 275, 278, 281, 283, 286, 288, 291, 293, 296, 299, 301, 304, 306, 309, 311, 314, 317, 319, 322, 324, 327,},
{ 164, 167, 169, 172, 175, 177, 180, 182, 185, 187, 190, 192, 195, 198, 200, 203, 205, 208, 210, 213, 216, 218, 221, 223, 226, 228, 231, 234, 236, 239, 241, 244, 246, 249, 252, 254, 257, 259, 262, 264, 267, 269, 272, 275, 277, 280, 282, 285, 287, 290, 293, 295, 298, 300, 303, 305, 308, 311, 313, 316, 318, 321, 323, 326,},
{ 164, 166, 169, 171, 174, 177, 179, 182, 184, 187, 189, 192, 194, 197, 200, 202, 205, 207, 210, 212, 215, 217, 220, 223, 225, 228, 230, 233, 235, 238, 241, 243, 246, 248, 251, 253, 256, 258, 261, 264, 266, 269, 271, 274, 276, 279, 281, 284, 287, 289, 292, 294, 297, 299, 302, 304, 307, 310, 312, 315, 317, 320, 322, 325,},
{ 163, 166, 168, 171, 173, 176, 179, 181, 184, 186, 189, 191, 194, 196, 199, 202, 204, 207, 209, 212, 214, 217, 219, 222, 224, 227, 230, 232, 235, 237, 240, 242, 245, 247, 250, 253, 255, 258, 260, 263, 265, 268, 270, 273, 275, 278, 281, 283, 286, 288, 291, 293, 296, 298, 301, 304, 306, 309, 311, 314, 316, 319, 321, 324,},
{ 163, 165, 168, 170, 173, 175, 178, 181, 183, 186, 188, 191, 193, 196, 198, 201, 203, 206, 209, 211, 214, 216, 219, 221, 224, 226, 229, 231, 234, 236, 239, 242, 244, 247, 249, 252, 254, 257, 259, 262, 264, 267, 270, 272, 275, 277, 280, 282, 285, 287, 290, 292, 295, 298, 300, 303, 305, 308, 310, 313, 315, 318, 320, 323,},
{ 162, 165, 167, 170, 172, 175, 177, 180, 183, 185, 188, 190, 193, 195, 198, 200, 203, 205, 208, 210, 213, 215, 218, 221, 223, 226, 228, 231, 233, 236, 238, 241, 243, 246, 248, 251, 254, 256, 259, 261, 264, 266, 269, 271, 274, 276, 279, 281, 284, 286, 289, 292, 294, 297, 299, 302, 304, 307, 309, 312, 314, 317, 319, 322,},
{ 162, 164, 167, 169, 172, 174, 177, 179, 182, 184, 187, 190, 192, 195, 197, 200, 202, 205, 207, 210, 212, 215, 217, 220, 222, 225, 227, 230, 233, 235, 238, 240, 243, 245, 248, 250, 253, 255, 258, 260, 263, 265, 268, 270, 273, 275, 278, 281, 283, 286, 288, 291, 293, 296, 298, 301, 303, 306, 308, 311, 313, 316, 318, 321,},
{ 161, 164, 166, 169, 171, 174, 176, 179, 181, 184, 186, 189, 191, 194, 197, 199, 202, 204, 207, 209, 212, 214, 217, 219, 222, 224, 227, 229, 232, 234, 237, 239, 242, 244, 247, 249, 252, 254, 257, 260, 262, 265, 267, 270, 272, 275, 277, 280, 282, 285, 287, 290, 292, 295, 297, 300, 302, 305, 307, 310, 312, 315, 317, 320,},
{ 161, 163, 166, 168, 171, 173, 176, 178, 181, 183, 186, 188, 191, 193, 196, 198, 201, 203, 206, 208, 211, 213, 216, 219, 221, 224, 226, 229, 231, 234, 236, 239, 241, 244, 246, 249, 251, 254, 256, 259, 261, 264, 266, 269, 271, 274, 276, 279, 281, 284, 286, 289, 291, 294, 296, 299, 301, 304, 306, 309, 311, 314, 316, 319,},
{ 160, 163, 165, 168, 170, 173, 175, 178, 180, 183, 185, 188, 190, 193, 195, 198, 200, 203, 205, 208, 210, 213, 215, 218, 220, 223, 225, 228, 230, 233, 235, 238, 240, 243, 245, 248, 250, 253, 255, 258, 260, 263, 265, 268, 270, 273, 275, 278, 280, 283, 285, 288, 290, 293, 295, 298, 300, 303, 305, 308, 310, 313, 315, 318,},
{ 160, 162, 165, 167, 170, 172, 175, 177, 180, 182, 185, 187, 190, 192, 195, 197, 200, 202, 205, 207, 210, 212, 215, 217, 220, 222, 225, 227, 230, 232, 235, 237, 240, 242, 245, 247, 250, 252, 255, 257, 260, 262, 265, 267, 270, 272, 275, 277, 280, 282, 285, 287, 290, 292, 295, 297, 300, 302, 305, 307, 310, 312, 315, 317,},
{ 159, 162, 164, 167, 169, 172, 174, 177, 179, 182, 184, 187, 189, 192, 194, 197, 199, 202, 204, 207, 209, 212, 214, 216, 219, 221, 224, 226, 229, 231, 234, 236, 239, 241, 244, 246, 249, 251, 254, 256, 259, 261, 264, 266, 269, 271, 274, 276, 279, 281, 284, 286, 289, 291, 294, 296, 299, 301, 304, 306, 309, 311, 314, 316,},
{ 159, 161, 164, 166, 169, 171, 174, 176, 179, 181, 184, 186, 189, 191, 193, 196, 198, 201, 203, 206, 208, 211, 213, 216, 218, 221, 223, 226, 228, 231, 233, 236, 238, 241, 243, 246, 248, 251, 253, 255, 258, 260, 263, 265, 268, 270, 273, 275, 278, 280, 283, 285, 288, 290, 293, 295, 298, 300, 303, 305, 308, 310, 313, 315,},
{ 158, 161, 163, 166, 168, 171, 173, 176, 178, 181, 183, 185, 188, 190, 193, 195, 198, 200, 203, 205, 208, 210, 213, 215, 218, 220, 223, 225, 227, 230, 232, 235, 237, 240, 242, 245, 247, 250, 252, 255, 257, 260, 262, 265, 267, 270, 272, 274, 277, 279, 282, 284, 287, 289, 292, 294, 297, 299, 302, 304, 307, 309, 312, 314,},
{ 158, 160, 163, 165, 168, 170, 173, 175, 177, 180, 182, 185, 187, 190, 192, 195, 197, 200, 202, 205, 207, 210, 212, 214, 217, 219, 222, 224, 227, 229, 232, 234, 237, 239, 242, 244, 246, 249, 251, 254, 256, 259, 261, 264, 266, 269, 271, 274, 276, 279, 281, 283, 286, 288, 291, 293, 296, 298, 301, 303, 306, 308, 311, 313,},
{ 157, 160, 162, 165, 167, 170, 172, 174, 177, 179, 182, 184, 187, 189, 192, 194, 197, 199, 201, 204, 206, 209, 211, 214, 216, 219, 221, 224, 226, 229, 231, 233, 236, 238, 241, 243, 246, 248, 251, 253, 256, 258, 260, 263, 265, 268, 270, 273, 275, 278, 280, 283, 285, 287, 290, 292, 295, 297, 300, 302, 305, 307, 310, 312,},
{ 157, 159, 162, 164, 167, 169, 171, 174, 176, 179, 181, 184, 186, 189, 191, 193, 196, 198, 201, 203, 206, 208, 211, 213, 216, 218, 220, 223, 225, 228, 230, 233, 235, 238, 240, 242, 245, 247, 250, 252, 255, 257, 260, 262, 265, 267, 269, 272, 274, 277, 279, 282, 284, 287, 289, 291, 294, 296, 299, 301, 304, 306, 309, 311,},
{ 156, 159, 161, 164, 166, 168, 171, 173, 176, 178, 181, 183, 186, 188, 190, 193, 195, 198, 200, 203, 205, 208, 210, 212, 215, 217, 220, 222, 225, 227, 229, 232, 234, 237, 239, 242, 244, 247, 249, 251, 254, 256, 259, 261, 264, 266, 269, 271, 273, 276, 278, 281, 283, 286, 288, 291, 293, 295, 298, 300, 303, 305, 308, 310,},
{ 156, 158, 161, 163, 165, 168, 170, 173, 175, 178, 180, 183, 185, 187, 190, 192, 195, 197, 200, 202, 204, 207, 209, 212, 214, 217, 219, 221, 224, 226, 229, 231, 234, 236, 238, 241, 243, 246, 248, 251, 253, 256, 258, 260, 263, 265, 268, 270, 273, 275, 277, 280, 282, 285, 287, 290, 292, 294, 297, 299, 302, 304, 307, 309,},
{ 155, 158, 160, 163, 165, 167, 170, 172, 175, 177, 180, 182, 184, 187, 189, 192, 194, 196, 199, 201, 204, 206, 209, 211, 213, 216, 218, 221, 223, 226, 228, 230, 233, 235, 238, 240, 243, 245, 247, 250, 252, 255, 257, 260, 262, 264, 267, 269, 272, 274, 277, 279, 281, 284, 286, 289, 291, 294, 296, 298, 301, 303, 306, 308,},
{ 155, 157, 160, 162, 164, 167, 169, 172, 174, 177, 179, 181, 184, 186, 189, 191, 193, 196, 198, 201, 203, 206, 208, 210, 213, 215, 218, 220, 222, 225, 227, 230, 232, 235, 237, 239, 242, 244, 247, 249, 251, 254, 256, 259, 261, 264, 266, 268, 271, 273, 276, 278, 280, 283, 285, 288, 290, 293, 295, 297, 300, 302, 305, 307,},
{ 154, 157, 159, 161, 164, 166, 169, 171, 174, 176, 178, 181, 183, 186, 188, 190, 193, 195, 198, 200, 202, 205, 207, 210, 212, 215, 217, 219, 222, 224, 227, 229, 231, 234, 236, 239, 241, 243, 246, 248, 251, 253, 255, 258, 260, 263, 265, 268, 270, 272, 275, 277, 280, 282, 284, 287, 289, 292, 294, 296, 299, 301, 304, 306,},
{ 154, 156, 159, 161, 163, 166, 168, 171, 173, 175, 178, 180, 183, 185, 187, 190, 192, 195, 197, 199, 202, 204, 207, 209, 211, 214, 216, 219, 221, 223, 226, 228, 231, 233, 235, 238, 240, 243, 245, 247, 250, 252, 255, 257, 259, 262, 264, 267, 269, 271, 274, 276, 279, 281, 283, 286, 288, 291, 293, 295, 298, 300, 303, 305,},
{ 153, 156, 158, 160, 163, 165, 168, 170, 172, 175, 177, 180, 182, 184, 187, 189, 192, 194, 196, 199, 201, 204, 206, 208, 211, 213, 216, 218, 220, 223, 225, 227, 230, 232, 235, 237, 239, 242, 244, 247, 249, 251, 254, 256, 259, 261, 263, 266, 268, 271, 273, 275, 278, 280, 283, 285, 287, 290, 292, 295, 297, 299, 302, 304,},
{ 153, 155, 158, 160, 162, 165, 167, 169, 172, 174, 177, 179, 181, 184, 186, 189, 191, 193, 196, 198, 200, 203, 205, 208, 210, 212, 215, 217, 220, 222, 224, 227, 229, 232, 234, 236, 239, 241, 243, 246, 248, 251, 253, 255, 258, 260, 263, 265, 267, 270, 272, 274, 277, 279, 282, 284, 286, 289, 291, 294, 296, 298, 301, 303,},
{ 152, 155, 157, 159, 162, 164, 167, 169, 171, 174, 176, 178, 181, 183, 186, 188, 190, 193, 195, 197, 200, 202, 205, 207, 209, 212, 214, 216, 219, 221, 224, 226, 228, 231, 233, 236, 238, 240, 243, 245, 247, 250, 252, 255, 257, 259, 262, 264, 266, 269, 271, 274, 276, 278, 281, 283, 285, 288, 290, 293, 295, 297, 300, 302,},
{ 152, 154, 156, 159, 161, 164, 166, 168, 171, 173, 175, 178, 180, 183, 185, 187, 190, 192, 194, 197, 199, 202, 204, 206, 209, 211, 213, 216, 218, 221, 223, 225, 228, 230, 232, 235, 237, 239, 242, 244, 247, 249, 251, 254, 256, 258, 261, 263, 266, 268, 270, 273, 275, 277, 280, 282, 285, 287, 289, 292, 294, 296, 299, 301,},
{ 151, 154, 156, 158, 161, 163, 165, 168, 170, 173, 175, 177, 180, 182, 184, 187, 189, 191, 194, 196, 199, 201, 203, 206, 208, 210, 213, 215, 217, 220, 222, 225, 227, 229, 232, 234, 236, 239, 241, 243, 246, 248, 251, 253, 255, 258, 260, 262, 265, 267, 269, 272, 274, 277, 279, 281, 284, 286, 288, 291, 293, 295, 298, 300,},
{ 151, 153, 155, 158, 160, 163, 165, 167, 170, 172, 174, 177, 179, 181, 184, 186, 188, 191, 193, 196, 198, 200, 203, 205, 207, 210, 212, 214, 217, 219, 221, 224, 226, 228, 231, 233, 236, 238, 240, 243, 245, 247, 250, 252, 254, 257, 259, 261, 264, 266, 269, 271, 273, 276, 278, 280, 283, 285, 287, 290, 292, 294, 297, 299,},
{ 150, 153, 155, 157, 160, 162, 164, 167, 169, 171, 174, 176, 178, 181, 183, 185, 188, 190, 193, 195, 197, 200, 202, 204, 207, 209, 211, 214, 216, 218, 221, 223, 225, 228, 230, 232, 235, 237, 239, 242, 244, 247, 249, 251, 254, 256, 258, 261, 263, 265, 268, 270, 272, 275, 277, 279, 282, 284, 286, 289, 291, 293, 296, 298,},
{ 150, 152, 154, 157, 159, 161, 164, 166, 168, 171, 173, 175, 178, 180, 183, 185, 187, 190, 192, 194, 197, 199, 201, 204, 206, 208, 211, 213, 215, 218, 220, 222, 225, 227, 229, 232, 234, 236, 239, 241, 243, 246, 248, 250, 253, 255, 257, 260, 262, 264, 267, 269, 271, 274, 276, 278, 281, 283, 285, 288, 290, 292, 295, 297,},
{ 149, 152, 154, 156, 159, 161, 163, 166, 168, 170, 173, 175, 177, 180, 182, 184, 187, 189, 191, 194, 196, 198, 201, 203, 205, 208, 210, 212, 215, 217, 219, 222, 224, 226, 229, 231, 233, 236, 238, 240, 243, 245, 247, 250, 252, 254, 257, 259, 261, 264, 266, 268, 271, 273, 275, 278, 280, 282, 285, 287, 289, 292, 294, 296,},
{ 149, 151, 153, 156, 158, 160, 163, 165, 167, 170, 172, 174, 177, 179, 181, 184, 186, 188, 191, 193, 195, 198, 200, 202, 205, 207, 209, 212, 214, 216, 218, 221, 223, 225, 228, 230, 232, 235, 237, 239, 242, 244, 246, 249, 251, 253, 256, 258, 260, 263, 265, 267, 270, 272, 274, 277, 279, 281, 284, 286, 288, 291, 293, 295,},
{ 148, 151, 153, 155, 158, 160, 162, 164, 167, 169, 171, 174, 176, 178, 181, 183, 185, 188, 190, 192, 195, 197, 199, 202, 204, 206, 208, 211, 213, 215, 218, 220, 222, 225, 227, 229, 232, 234, 236, 239, 241, 243, 246, 248, 250, 252, 255, 257, 259, 262, 264, 266, 269, 271, 273, 276, 278, 280, 283, 285, 287, 290, 292, 294,},
{ 148, 150, 152, 155, 157, 159, 162, 164, 166, 169, 171, 173, 175, 178, 180, 182, 185, 187, 189, 192, 194, 196, 199, 201, 203, 205, 208, 210, 212, 215, 217, 219, 222, 224, 226, 229, 231, 233, 235, 238, 240, 242, 245, 247, 249, 252, 254, 256, 259, 261, 263, 265, 268, 270, 272, 275, 277, 279, 282, 284, 286, 289, 291, 293,},
{ 147, 150, 152, 154, 156, 159, 161, 163, 166, 168, 170, 173, 175, 177, 179, 182, 184, 186, 189, 191, 193, 196, 198, 200, 202, 205, 207, 209, 212, 214, 216, 219, 221, 223, 225, 228, 230, 232, 235, 237, 239, 242, 244, 246, 248, 251, 253, 255, 258, 260, 262, 265, 267, 269, 271, 274, 276, 278, 281, 283, 285, 288, 290, 292,},
{ 147, 149, 151, 154, 156, 158, 161, 163, 165, 167, 170, 172, 174, 177, 179, 181, 183, 186, 188, 190, 193, 195, 197, 199, 202, 204, 206, 209, 211, 213, 216, 218, 220, 222, 225, 227, 229, 232, 234, 236, 238, 241, 243, 245, 248, 250, 252, 255, 257, 259, 261, 264, 266, 268, 271, 273, 275, 277, 280, 282, 284, 287, 289, 291,},
{ 146, 149, 151, 153, 155, 158, 160, 162, 165, 167, 169, 171, 174, 176, 178, 181, 183, 185, 187, 190, 192, 194, 197, 199, 201, 203, 206, 208, 210, 213, 215, 217, 219, 222, 224, 226, 229, 231, 233, 235, 238, 240, 242, 245, 247, 249, 251, 254, 256, 258, 261, 263, 265, 267, 270, 272, 274, 277, 279, 281, 283, 286, 288, 290,},
{ 146, 148, 150, 153, 155, 157, 159, 162, 164, 166, 169, 171, 173, 175, 178, 180, 182, 184, 187, 189, 191, 194, 196, 198, 200, 203, 205, 207, 210, 212, 214, 216, 219, 221, 223, 225, 228, 230, 232, 235, 237, 239, 241, 244, 246, 248, 251, 253, 255, 257, 260, 262, 264, 266, 269, 271, 273, 276, 278, 280, 282, 285, 287, 289,},
{ 145, 148, 150, 152, 154, 157, 159, 161, 163, 166, 168, 170, 172, 175, 177, 179, 182, 184, 186, 188, 191, 193, 195, 197, 200, 202, 204, 207, 209, 211, 213, 216, 218, 220, 222, 225, 227, 229, 231, 234, 236, 238, 241, 243, 245, 247, 250, 252, 254, 256, 259, 261, 263, 266, 268, 270, 272, 275, 277, 279, 281, 284, 286, 288,},
{ 145, 147, 149, 152, 154, 156, 158, 161, 163, 165, 167, 170, 172, 174, 176, 179, 181, 183, 185, 188, 190, 192, 195, 197, 199, 201, 204, 206, 208, 210, 213, 215, 217, 219, 222, 224, 226, 228, 231, 233, 235, 237, 240, 242, 244, 247, 249, 251, 253, 256, 258, 260, 262, 265, 267, 269, 271, 274, 276, 278, 280, 283, 285, 287,},
{ 144, 147, 149, 151, 153, 156, 158, 160, 162, 165, 167, 169, 171, 174, 176, 178, 180, 183, 185, 187, 189, 192, 194, 196, 198, 201, 203, 205, 207, 210, 212, 214, 216, 219, 221, 223, 225, 228, 230, 232, 234, 237, 239, 241, 243, 246, 248, 250, 252, 255, 257, 259, 261, 264, 266, 268, 270, 273, 275, 277, 279, 282, 284, 286,},
{ 144, 146, 148, 150, 153, 155, 157, 159, 162, 164, 166, 168, 171, 173, 175, 177, 180, 182, 184, 186, 189, 191, 193, 195, 198, 200, 202, 204, 207, 209, 211, 213, 216, 218, 220, 222, 225, 227, 229, 231, 234, 236, 238, 240, 243, 245, 247, 249, 252, 254, 256, 258, 261, 263, 265, 267, 270, 272, 274, 276, 279, 281, 283, 285,},
{ 143, 145, 148, 150, 152, 154, 157, 159, 161, 163, 166, 168, 170, 172, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 204, 206, 208, 210, 213, 215, 217, 219, 222, 224, 226, 228, 231, 233, 235, 237, 239, 242, 244, 246, 248, 251, 253, 255, 257, 260, 262, 264, 266, 269, 271, 273, 275, 278, 280, 282, 284,},
{ 143, 145, 147, 149, 152, 154, 156, 158, 161, 163, 165, 167, 170, 172, 174, 176, 178, 181, 183, 185, 187, 190, 192, 194, 196, 199, 201, 203, 205, 207, 210, 212, 214, 216, 219, 221, 223, 225, 228, 230, 232, 234, 236, 239, 241, 243, 245, 248, 250, 252, 254, 257, 259, 261, 263, 265, 268, 270, 272, 274, 277, 279, 281, 283,},
{ 142, 144, 147, 149, 151, 153, 156, 158, 160, 162, 164, 167, 169, 171, 173, 176, 178, 180, 182, 184, 187, 189, 191, 193, 196, 198, 200, 202, 204, 207, 209, 211, 213, 216, 218, 220, 222, 224, 227, 229, 231, 233, 236, 238, 240, 242, 244, 247, 249, 251, 253, 256, 258, 260, 262, 264, 267, 269, 271, 273, 276, 278, 280, 282,},
{ 142, 144, 146, 148, 151, 153, 155, 157, 159, 162, 164, 166, 168, 171, 173, 175, 177, 179, 182, 184, 186, 188, 190, 193, 195, 197, 199, 202, 204, 206, 208, 210, 213, 215, 217, 219, 221, 224, 226, 228, 230, 233, 235, 237, 239, 241, 244, 246, 248, 250, 252, 255, 257, 259, 261, 264, 266, 268, 270, 272, 275, 277, 279, 281,},
{ 141, 143, 146, 148, 150, 152, 154, 157, 159, 161, 163, 166, 168, 170, 172, 174, 177, 179, 181, 183, 185, 188, 190, 192, 194, 196, 199, 201, 203, 205, 207, 210, 212, 214, 216, 218, 221, 223, 225, 227, 230, 232, 234, 236, 238, 241, 243, 245, 247, 249, 252, 254, 256, 258, 260, 263, 265, 267, 269, 271, 274, 276, 278, 280,},
{ 141, 143, 145, 147, 150, 152, 154, 156, 158, 161, 163, 165, 167, 169, 172, 174, 176, 178, 180, 183, 185, 187, 189, 191, 194, 196, 198, 200, 202, 205, 207, 209, 211, 213, 216, 218, 220, 222, 224, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 249, 251, 253, 255, 257, 260, 262, 264, 266, 268, 271, 273, 275, 277, 279,},
{ 140, 142, 145, 147, 149, 151, 153, 156, 158, 160, 162, 164, 167, 169, 171, 173, 175, 178, 180, 182, 184, 186, 188, 191, 193, 195, 197, 199, 202, 204, 206, 208, 210, 213, 215, 217, 219, 221, 224, 226, 228, 230, 232, 234, 237, 239, 241, 243, 245, 248, 250, 252, 254, 256, 259, 261, 263, 265, 267, 270, 272, 274, 276, 278,},
{ 140, 142, 144, 146, 148, 151, 153, 155, 157, 159, 162, 164, 166, 168, 170, 173, 175, 177, 179, 181, 183, 186, 188, 190, 192, 194, 197, 199, 201, 203, 205, 207, 210, 212, 214, 216, 218, 221, 223, 225, 227, 229, 231, 234, 236, 238, 240, 242, 245, 247, 249, 251, 253, 255, 258, 260, 262, 264, 266, 269, 271, 273, 275, 277,},
{ 139, 141, 144, 146, 148, 150, 152, 154, 157, 159, 161, 163, 165, 168, 170, 172, 174, 176, 178, 181, 183, 185, 187, 189, 191, 194, 196, 198, 200, 202, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 231, 233, 235, 237, 239, 242, 244, 246, 248, 250, 252, 255, 257, 259, 261, 263, 265, 268, 270, 272, 274, 276,},
{ 139, 141, 143, 145, 147, 150, 152, 154, 156, 158, 160, 163, 165, 167, 169, 171, 173, 176, 178, 180, 182, 184, 186, 189, 191, 193, 195, 197, 199, 202, 204, 206, 208, 210, 212, 215, 217, 219, 221, 223, 225, 228, 230, 232, 234, 236, 238, 241, 243, 245, 247, 249, 251, 254, 256, 258, 260, 262, 264, 267, 269, 271, 273, 275,},
{ 138, 140, 143, 145, 147, 149, 151, 153, 156, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 194, 197, 199, 201, 203, 205, 207, 210, 212, 214, 216, 218, 220, 222, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 251, 253, 255, 257, 259, 261, 264, 266, 268, 270, 272, 274,},
{ 138, 140, 142, 144, 146, 149, 151, 153, 155, 157, 159, 161, 164, 166, 168, 170, 172, 174, 176, 179, 181, 183, 185, 187, 189, 192, 194, 196, 198, 200, 202, 204, 207, 209, 211, 213, 215, 217, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252, 254, 256, 258, 260, 263, 265, 267, 269, 271, 273,},
{ 137, 139, 142, 144, 146, 148, 150, 152, 154, 157, 159, 161, 163, 165, 167, 169, 172, 174, 176, 178, 180, 182, 184, 187, 189, 191, 193, 195, 197, 199, 202, 204, 206, 208, 210, 212, 214, 217, 219, 221, 223, 225, 227, 229, 232, 234, 236, 238, 240, 242, 244, 247, 249, 251, 253, 255, 257, 259, 262, 264, 266, 268, 270, 272,},
{ 137, 139, 141, 143, 145, 147, 150, 152, 154, 156, 158, 160, 162, 165, 167, 169, 171, 173, 175, 177, 179, 182, 184, 186, 188, 190, 192, 194, 197, 199, 201, 203, 205, 207, 209, 212, 214, 216, 218, 220, 222, 224, 226, 229, 231, 233, 235, 237, 239, 241, 244, 246, 248, 250, 252, 254, 256, 259, 261, 263, 265, 267, 269, 271,},
{ 136, 138, 141, 143, 145, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 170, 172, 175, 177, 179, 181, 183, 185, 187, 189, 192, 194, 196, 198, 200, 202, 204, 207, 209, 211, 213, 215, 217, 219, 221, 224, 226, 228, 230, 232, 234, 236, 238, 241, 243, 245, 247, 249, 251, 253, 255, 258, 260, 262, 264, 266, 268, 270,},
{ 136, 138, 140, 142, 144, 146, 148, 151, 153, 155, 157, 159, 161, 163, 165, 168, 170, 172, 174, 176, 178, 180, 182, 185, 187, 189, 191, 193, 195, 197, 199, 202, 204, 206, 208, 210, 212, 214, 216, 218, 221, 223, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 250, 252, 255, 257, 259, 261, 263, 265, 267, 269,},
{ 135, 137, 139, 142, 144, 146, 148, 150, 152, 154, 156, 158, 161, 163, 165, 167, 169, 171, 173, 175, 178, 180, 182, 184, 186, 188, 190, 192, 194, 197, 199, 201, 203, 205, 207, 209, 211, 213, 216, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 247, 249, 251, 254, 256, 258, 260, 262, 264, 266, 268,},
{ 135, 137, 139, 141, 143, 145, 147, 149, 152, 154, 156, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 192, 194, 196, 198, 200, 202, 204, 206, 208, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 232, 234, 236, 238, 240, 242, 244, 246, 248, 251, 253, 255, 257, 259, 261, 263, 265, 267,},
{ 134, 136, 138, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 248, 250, 252, 254, 256, 258, 260, 262, 264, 266,},
{ 134, 136, 138, 140, 142, 144, 146, 148, 150, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 245, 247, 249, 251, 253, 255, 257, 259, 261, 263, 265,},
{ 133, 135, 137, 139, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 242, 244, 246, 248, 250, 252, 254, 256, 258, 260, 262, 264,},
{ 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 239, 241, 243, 245, 247, 249, 251, 253, 255, 257, 259, 261, 263,},
{ 132, 134, 136, 138, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 256, 258, 260, 262,},
{ 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255, 257, 259, 261,},
{ 131, 133, 135, 137, 139, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 256, 258, 260,},
{ 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255, 257, 259,},
{ 130, 132, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 256, 258,},
{ 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255, 257,},
{ 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 256,},
{ 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255,},
{ 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254,},
{ 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254,},
{ 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253,},
{ 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252,},
{ 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251,},
{ 126, 128, 130, 132, 134, 136, 138, 140, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250,},
{ 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249,},
{ 125, 127, 129, 131, 133, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248,},
{ 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247,},
{ 124, 126, 128, 130, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246,},
{ 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245,},
{ 123, 125, 127, 129, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244,},
{ 122, 124, 126, 128, 130, 132, 134, 136, 138, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243,},
{ 122, 124, 126, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242,},
{ 121, 123, 125, 127, 129, 131, 133, 135, 136, 138, 140, 142, 144, 146, 148, 150, 152, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 172, 174, 176, 178, 180, 182, 184, 186, 188, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 208, 210, 212, 214, 216, 218, 220, 222, 224, 225, 227, 229, 231, 233, 235, 237, 239, 241,},
{ 121, 123, 125, 126, 128, 130, 132, 134, 136, 138, 140, 142, 143, 145, 147, 149, 151, 153, 155, 157, 158, 160, 162, 164, 166, 168, 170, 172, 174, 175, 177, 179, 181, 183, 185, 187, 189, 191, 192, 194, 196, 198, 200, 202, 204, 206, 208, 209, 211, 213, 215, 217, 219, 221, 223, 225, 226, 228, 230, 232, 234, 236, 238, 240,},
{ 120, 122, 124, 126, 128, 130, 132, 133, 135, 137, 139, 141, 143, 145, 147, 148, 150, 152, 154, 156, 158, 160, 162, 163, 165, 167, 169, 171, 173, 175, 177, 178, 180, 182, 184, 186, 188, 190, 192, 194, 195, 197, 199, 201, 203, 205, 207, 209, 210, 212, 214, 216, 218, 220, 222, 224, 225, 227, 229, 231, 233, 235, 237, 239,},
{ 120, 122, 123, 125, 127, 129, 131, 133, 135, 137, 138, 140, 142, 144, 146, 148, 150, 152, 153, 155, 157, 159, 161, 163, 165, 167, 168, 170, 172, 174, 176, 178, 180, 181, 183, 185, 187, 189, 191, 193, 195, 196, 198, 200, 202, 204, 206, 208, 210, 211, 213, 215, 217, 219, 221, 223, 225, 226, 228, 230, 232, 234, 236, 238,},
{ 119, 121, 123, 125, 127, 129, 130, 132, 134, 136, 138, 140, 142, 143, 145, 147, 149, 151, 153, 155, 157, 158, 160, 162, 164, 166, 168, 170, 171, 173, 175, 177, 179, 181, 183, 184, 186, 188, 190, 192, 194, 196, 198, 199, 201, 203, 205, 207, 209, 211, 212, 214, 216, 218, 220, 222, 224, 225, 227, 229, 231, 233, 235, 237,},
{ 119, 121, 122, 124, 126, 128, 130, 132, 134, 135, 137, 139, 141, 143, 145, 147, 148, 150, 152, 154, 156, 158, 160, 161, 163, 165, 167, 169, 171, 173, 174, 176, 178, 180, 182, 184, 186, 187, 189, 191, 193, 195, 197, 199, 200, 202, 204, 206, 208, 210, 212, 213, 215, 217, 219, 221, 223, 225, 226, 228, 230, 232, 234, 236,},
{ 118, 120, 122, 124, 126, 127, 129, 131, 133, 135, 137, 139, 140, 142, 144, 146, 148, 150, 152, 153, 155, 157, 159, 161, 163, 164, 166, 168, 170, 172, 174, 176, 177, 179, 181, 183, 185, 187, 188, 190, 192, 194, 196, 198, 200, 201, 203, 205, 207, 209, 211, 212, 214, 216, 218, 220, 222, 224, 225, 227, 229, 231, 233, 235,},
{ 118, 120, 121, 123, 125, 127, 129, 131, 132, 134, 136, 138, 140, 142, 144, 145, 147, 149, 151, 153, 155, 156, 158, 160, 162, 164, 166, 167, 169, 171, 173, 175, 177, 178, 180, 182, 184, 186, 188, 190, 191, 193, 195, 197, 199, 201, 202, 204, 206, 208, 210, 212, 213, 215, 217, 219, 221, 223, 224, 226, 228, 230, 232, 234,},
{ 117, 119, 121, 123, 125, 126, 128, 130, 132, 134, 136, 137, 139, 141, 143, 145, 147, 148, 150, 152, 154, 156, 158, 159, 161, 163, 165, 167, 169, 170, 172, 174, 176, 178, 180, 181, 183, 185, 187, 189, 191, 192, 194, 196, 198, 200, 202, 203, 205, 207, 209, 211, 213, 214, 216, 218, 220, 222, 224, 225, 227, 229, 231, 233,},
{ 117, 119, 120, 122, 124, 126, 128, 130, 131, 133, 135, 137, 139, 140, 142, 144, 146, 148, 150, 151, 153, 155, 157, 159, 161, 162, 164, 166, 168, 170, 171, 173, 175, 177, 179, 181, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 202, 204, 206, 208, 210, 212, 213, 215, 217, 219, 221, 223, 224, 226, 228, 230, 232,},
{ 116, 118, 120, 122, 124, 125, 127, 129, 131, 133, 134, 136, 138, 140, 142, 143, 145, 147, 149, 151, 153, 154, 156, 158, 160, 162, 163, 165, 167, 169, 171, 173, 174, 176, 178, 180, 182, 183, 185, 187, 189, 191, 193, 194, 196, 198, 200, 202, 203, 205, 207, 209, 211, 213, 214, 216, 218, 220, 222, 223, 225, 227, 229, 231,},
{ 116, 118, 119, 121, 123, 125, 127, 128, 130, 132, 134, 136, 137, 139, 141, 143, 145, 146, 148, 150, 152, 154, 156, 157, 159, 161, 163, 165, 166, 168, 170, 172, 174, 175, 177, 179, 181, 183, 184, 186, 188, 190, 192, 194, 195, 197, 199, 201, 203, 204, 206, 208, 210, 212, 213, 215, 217, 219, 221, 222, 224, 226, 228, 230,},
{ 115, 117, 119, 121, 122, 124, 126, 128, 130, 131, 133, 135, 137, 139, 140, 142, 144, 146, 148, 149, 151, 153, 155, 157, 158, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 185, 187, 189, 191, 193, 194, 196, 198, 200, 202, 203, 205, 207, 209, 211, 212, 214, 216, 218, 220, 221, 223, 225, 227, 229,},
{ 115, 117, 118, 120, 122, 124, 126, 127, 129, 131, 133, 134, 136, 138, 140, 142, 143, 145, 147, 149, 151, 152, 154, 156, 158, 160, 161, 163, 165, 167, 169, 170, 172, 174, 176, 178, 179, 181, 183, 185, 186, 188, 190, 192, 194, 195, 197, 199, 201, 203, 204, 206, 208, 210, 212, 213, 215, 217, 219, 221, 222, 224, 226, 228,},
{ 114, 116, 118, 120, 121, 123, 125, 127, 129, 130, 132, 134, 136, 137, 139, 141, 143, 145, 146, 148, 150, 152, 154, 155, 157, 159, 161, 162, 164, 166, 168, 170, 171, 173, 175, 177, 179, 180, 182, 184, 186, 187, 189, 191, 193, 195, 196, 198, 200, 202, 204, 205, 207, 209, 211, 212, 214, 216, 218, 220, 221, 223, 225, 227,},
{ 114, 116, 117, 119, 121, 123, 124, 126, 128, 130, 132, 133, 135, 137, 139, 140, 142, 144, 146, 148, 149, 151, 153, 155, 156, 158, 160, 162, 164, 165, 167, 169, 171, 172, 174, 176, 178, 180, 181, 183, 185, 187, 188, 190, 192, 194, 196, 197, 199, 201, 203, 204, 206, 208, 210, 212, 213, 215, 217, 219, 220, 222, 224, 226,},
{ 113, 115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, 134, 136, 138, 140, 142, 143, 145, 147, 149, 150, 152, 154, 156, 157, 159, 161, 163, 165, 166, 168, 170, 172, 173, 175, 177, 179, 180, 182, 184, 186, 188, 189, 191, 193, 195, 196, 198, 200, 202, 203, 205, 207, 209, 211, 212, 214, 216, 218, 219, 221, 223, 225,},
{ 113, 115, 116, 118, 120, 122, 123, 125, 127, 129, 130, 132, 134, 136, 137, 139, 141, 143, 144, 146, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 174, 176, 178, 180, 181, 183, 185, 187, 189, 190, 192, 194, 196, 197, 199, 201, 203, 204, 206, 208, 210, 211, 213, 215, 217, 218, 220, 222, 224,},
{ 112, 114, 116, 118, 119, 121, 123, 125, 126, 128, 130, 132, 133, 135, 137, 139, 140, 142, 144, 146, 147, 149, 151, 153, 154, 156, 158, 160, 161, 163, 165, 167, 168, 170, 172, 174, 175, 177, 179, 181, 182, 184, 186, 188, 189, 191, 193, 195, 196, 198, 200, 202, 203, 205, 207, 209, 210, 212, 214, 216, 217, 219, 221, 223,},
{ 112, 113, 115, 117, 119, 120, 122, 124, 126, 127, 129, 131, 133, 134, 136, 138, 140, 141, 143, 145, 147, 148, 150, 152, 154, 155, 157, 159, 161, 162, 164, 166, 168, 169, 171, 173, 175, 176, 178, 180, 182, 183, 185, 187, 189, 190, 192, 194, 196, 197, 199, 201, 203, 204, 206, 208, 210, 211, 213, 215, 217, 218, 220, 222,},
{ 111, 113, 115, 116, 118, 120, 122, 123, 125, 127, 129, 130, 132, 134, 136, 137, 139, 141, 143, 144, 146, 148, 149, 151, 153, 155, 156, 158, 160, 162, 163, 165, 167, 169, 170, 172, 174, 176, 177, 179, 181, 183, 184, 186, 188, 189, 191, 193, 195, 196, 198, 200, 202, 203, 205, 207, 209, 210, 212, 214, 216, 217, 219, 221,},
{ 111, 112, 114, 116, 118, 119, 121, 123, 125, 126, 128, 130, 132, 133, 135, 137, 138, 140, 142, 144, 145, 147, 149, 151, 152, 154, 156, 157, 159, 161, 163, 164, 166, 168, 170, 171, 173, 175, 177, 178, 180, 182, 183, 185, 187, 189, 190, 192, 194, 196, 197, 199, 201, 202, 204, 206, 208, 209, 211, 213, 215, 216, 218, 220,},
{ 110, 112, 114, 115, 117, 119, 121, 122, 124, 126, 127, 129, 131, 133, 134, 136, 138, 140, 141, 143, 145, 146, 148, 150, 152, 153, 155, 157, 158, 160, 162, 164, 165, 167, 169, 171, 172, 174, 176, 177, 179, 181, 183, 184, 186, 188, 189, 191, 193, 195, 196, 198, 200, 202, 203, 205, 207, 208, 210, 212, 214, 215, 217, 219,},
{ 110, 111, 113, 115, 117, 118, 120, 122, 123, 125, 127, 129, 130, 132, 134, 135, 137, 139, 141, 142, 144, 146, 147, 149, 151, 153, 154, 156, 158, 159, 161, 163, 165, 166, 168, 170, 171, 173, 175, 177, 178, 180, 182, 183, 185, 187, 189, 190, 192, 194, 195, 197, 199, 201, 202, 204, 206, 207, 209, 211, 213, 214, 216, 218,},
{ 109, 111, 113, 114, 116, 118, 119, 121, 123, 125, 126, 128, 130, 131, 133, 135, 137, 138, 140, 142, 143, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 172, 174, 176, 178, 179, 181, 183, 184, 186, 188, 189, 191, 193, 195, 196, 198, 200, 201, 203, 205, 207, 208, 210, 212, 213, 215, 217,},
{ 109, 110, 112, 114, 116, 117, 119, 121, 122, 124, 126, 127, 129, 131, 133, 134, 136, 138, 139, 141, 143, 144, 146, 148, 150, 151, 153, 155, 156, 158, 160, 161, 163, 165, 167, 168, 170, 172, 173, 175, 177, 178, 180, 182, 184, 185, 187, 189, 190, 192, 194, 195, 197, 199, 201, 202, 204, 206, 207, 209, 211, 212, 214, 216,},
{ 108, 110, 112, 113, 115, 117, 118, 120, 122, 123, 125, 127, 129, 130, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 149, 151, 152, 154, 156, 157, 159, 161, 162, 164, 166, 167, 169, 171, 173, 174, 176, 178, 179, 181, 183, 184, 186, 188, 189, 191, 193, 195, 196, 198, 200, 201, 203, 205, 206, 208, 210, 211, 213, 215,},
{ 108, 109, 111, 113, 114, 116, 118, 120, 121, 123, 125, 126, 128, 130, 131, 133, 135, 136, 138, 140, 141, 143, 145, 146, 148, 150, 152, 153, 155, 157, 158, 160, 162, 163, 165, 167, 168, 170, 172, 173, 175, 177, 178, 180, 182, 184, 185, 187, 189, 190, 192, 194, 195, 197, 199, 200, 202, 204, 205, 207, 209, 210, 212, 214,},
{ 107, 109, 111, 112, 114, 116, 117, 119, 121, 122, 124, 126, 127, 129, 131, 132, 134, 136, 137, 139, 141, 142, 144, 146, 147, 149, 151, 152, 154, 156, 158, 159, 161, 163, 164, 166, 168, 169, 171, 173, 174, 176, 178, 179, 181, 183, 184, 186, 188, 189, 191, 193, 194, 196, 198, 199, 201, 203, 204, 206, 208, 209, 211, 213,},
{ 107, 108, 110, 112, 113, 115, 117, 118, 120, 122, 123, 125, 127, 128, 130, 132, 133, 135, 137, 138, 140, 142, 143, 145, 147, 148, 150, 152, 153, 155, 157, 158, 160, 162, 163, 165, 167, 168, 170, 172, 173, 175, 177, 178, 180, 182, 183, 185, 187, 188, 190, 192, 193, 195, 197, 198, 200, 202, 203, 205, 207, 208, 210, 212,},
{ 106, 108, 110, 111, 113, 115, 116, 118, 120, 121, 123, 125, 126, 128, 129, 131, 133, 134, 136, 138, 139, 141, 143, 144, 146, 148, 149, 151, 153, 154, 156, 158, 159, 161, 163, 164, 166, 168, 169, 171, 173, 174, 176, 178, 179, 181, 183, 184, 186, 188, 189, 191, 193, 194, 196, 198, 199, 201, 203, 204, 206, 208, 209, 211,},
{ 106, 107, 109, 111, 112, 114, 116, 117, 119, 121, 122, 124, 126, 127, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160, 162, 164, 165, 167, 169, 170, 172, 173, 175, 177, 178, 180, 182, 183, 185, 187, 188, 190, 192, 193, 195, 197, 198, 200, 202, 203, 205, 207, 208, 210,},
{ 105, 107, 109, 110, 112, 113, 115, 117, 118, 120, 122, 123, 125, 127, 128, 130, 132, 133, 135, 136, 138, 140, 141, 143, 145, 146, 148, 150, 151, 153, 155, 156, 158, 160, 161, 163, 164, 166, 168, 169, 171, 173, 174, 176, 178, 179, 181, 183, 184, 186, 187, 189, 191, 192, 194, 196, 197, 199, 201, 202, 204, 206, 207, 209,},
{ 105, 106, 108, 110, 111, 113, 115, 116, 118, 119, 121, 123, 124, 126, 128, 129, 131, 133, 134, 136, 137, 139, 141, 142, 144, 146, 147, 149, 151, 152, 154, 155, 157, 159, 160, 162, 164, 165, 167, 169, 170, 172, 173, 175, 177, 178, 180, 182, 183, 185, 187, 188, 190, 191, 193, 195, 196, 198, 200, 201, 203, 205, 206, 208,},
{ 104, 106, 108, 109, 111, 112, 114, 116, 117, 119, 121, 122, 124, 125, 127, 129, 130, 132, 134, 135, 137, 138, 140, 142, 143, 145, 147, 148, 150, 151, 153, 155, 156, 158, 160, 161, 163, 165, 166, 168, 169, 171, 173, 174, 176, 178, 179, 181, 182, 184, 186, 187, 189, 191, 192, 194, 195, 197, 199, 200, 202, 204, 205, 207,},
{ 104, 105, 107, 109, 110, 112, 113, 115, 117, 118, 120, 122, 123, 125, 126, 128, 130, 131, 133, 135, 136, 138, 139, 141, 143, 144, 146, 148, 149, 151, 152, 154, 156, 157, 159, 160, 162, 164, 165, 167, 169, 170, 172, 173, 175, 177, 178, 180, 182, 183, 185, 186, 188, 190, 191, 193, 195, 196, 198, 199, 201, 203, 204, 206,},
{ 103, 105, 106, 108, 110, 111, 113, 115, 116, 118, 119, 121, 123, 124, 126, 127, 129, 131, 132, 134, 136, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 156, 158, 160, 161, 163, 165, 166, 168, 169, 171, 173, 174, 176, 177, 179, 181, 182, 184, 186, 187, 189, 190, 192, 194, 195, 197, 198, 200, 202, 203, 205,},
{ 103, 104, 106, 108, 109, 111, 112, 114, 116, 117, 119, 120, 122, 124, 125, 127, 128, 130, 132, 133, 135, 136, 138, 140, 141, 143, 144, 146, 148, 149, 151, 153, 154, 156, 157, 159, 161, 162, 164, 165, 167, 169, 170, 172, 173, 175, 177, 178, 180, 181, 183, 185, 186, 188, 189, 191, 193, 194, 196, 197, 199, 201, 202, 204,},
{ 102, 104, 105, 107, 109, 110, 112, 113, 115, 117, 118, 120, 121, 123, 125, 126, 128, 129, 131, 133, 134, 136, 137, 139, 141, 142, 144, 145, 147, 149, 150, 152, 153, 155, 157, 158, 160, 161, 163, 165, 166, 168, 169, 171, 173, 174, 176, 177, 179, 181, 182, 184, 185, 187, 189, 190, 192, 193, 195, 197, 198, 200, 201, 203,},
{ 102, 103, 105, 107, 108, 110, 111, 113, 114, 116, 118, 119, 121, 122, 124, 126, 127, 129, 130, 132, 134, 135, 137, 138, 140, 141, 143, 145, 146, 148, 149, 151, 153, 154, 156, 157, 159, 161, 162, 164, 165, 167, 169, 170, 172, 173, 175, 176, 178, 180, 181, 183, 184, 186, 188, 189, 191, 192, 194, 196, 197, 199, 200, 202,},
{ 101, 103, 104, 106, 108, 109, 111, 112, 114, 115, 117, 119, 120, 122, 123, 125, 127, 128, 130, 131, 133, 134, 136, 138, 139, 141, 142, 144, 146, 147, 149, 150, 152, 153, 155, 157, 158, 160, 161, 163, 165, 166, 168, 169, 171, 172, 174, 176, 177, 179, 180, 182, 184, 185, 187, 188, 190, 191, 193, 195, 196, 198, 199, 201,},
{ 101, 102, 104, 105, 107, 109, 110, 112, 113, 115, 116, 118, 120, 121, 123, 124, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 143, 145, 146, 148, 150, 151, 153, 154, 156, 157, 159, 161, 162, 164, 165, 167, 168, 170, 172, 173, 175, 176, 178, 179, 181, 183, 184, 186, 187, 189, 190, 192, 194, 195, 197, 198, 200,},
{ 100, 102, 103, 105, 107, 108, 110, 111, 113, 114, 116, 117, 119, 121, 122, 124, 125, 127, 128, 130, 132, 133, 135, 136, 138, 139, 141, 143, 144, 146, 147, 149, 150, 152, 154, 155, 157, 158, 160, 161, 163, 164, 166, 168, 169, 171, 172, 174, 175, 177, 179, 180, 182, 183, 185, 186, 188, 190, 191, 193, 194, 196, 197, 199,},
{ 100, 101, 103, 104, 106, 108, 109, 111, 112, 114, 115, 117, 118, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 136, 137, 139, 140, 142, 143, 145, 147, 148, 150, 151, 153, 154, 156, 157, 159, 161, 162, 164, 165, 167, 168, 170, 171, 173, 175, 176, 178, 179, 181, 182, 184, 185, 187, 189, 190, 192, 193, 195, 196, 198,},
{ 99, 101, 102, 104, 105, 107, 109, 110, 112, 113, 115, 116, 118, 119, 121, 123, 124, 126, 127, 129, 130, 132, 133, 135, 136, 138, 140, 141, 143, 144, 146, 147, 149, 150, 152, 154, 155, 157, 158, 160, 161, 163, 164, 166, 167, 169, 171, 172, 174, 175, 177, 178, 180, 181, 183, 185, 186, 188, 189, 191, 192, 194, 195, 197,},
{ 99, 100, 102, 103, 105, 106, 108, 110, 111, 113, 114, 116, 117, 119, 120, 122, 123, 125, 127, 128, 130, 131, 133, 134, 136, 137, 139, 140, 142, 143, 145, 147, 148, 150, 151, 153, 154, 156, 157, 159, 160, 162, 164, 165, 167, 168, 170, 171, 173, 174, 176, 177, 179, 181, 182, 184, 185, 187, 188, 190, 191, 193, 194, 196,},
{ 98, 100, 101, 103, 104, 106, 107, 109, 111, 112, 114, 115, 117, 118, 120, 121, 123, 124, 126, 127, 129, 130, 132, 134, 135, 137, 138, 140, 141, 143, 144, 146, 147, 149, 150, 152, 154, 155, 157, 158, 160, 161, 163, 164, 166, 167, 169, 170, 172, 173, 175, 177, 178, 180, 181, 183, 184, 186, 187, 189, 190, 192, 193, 195,},
{ 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, 113, 115, 116, 118, 119, 121, 122, 124, 125, 127, 128, 130, 131, 133, 134, 136, 137, 139, 141, 142, 144, 145, 147, 148, 150, 151, 153, 154, 156, 157, 159, 160, 162, 163, 165, 166, 168, 170, 171, 173, 174, 176, 177, 179, 180, 182, 183, 185, 186, 188, 189, 191, 192, 194,},
{ 97, 99, 100, 102, 103, 105, 106, 108, 109, 111, 112, 114, 115, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 138, 140, 141, 143, 144, 146, 147, 149, 150, 152, 153, 155, 157, 158, 160, 161, 163, 164, 166, 167, 169, 170, 172, 173, 175, 176, 178, 179, 181, 182, 184, 185, 187, 188, 190, 191, 193,},
{ 97, 98, 100, 101, 103, 104, 106, 107, 109, 110, 112, 113, 115, 116, 118, 119, 121, 122, 124, 125, 127, 128, 130, 132, 133, 135, 136, 138, 139, 141, 142, 144, 145, 147, 148, 150, 151, 153, 154, 156, 157, 159, 160, 162, 163, 165, 166, 168, 169, 171, 172, 174, 175, 177, 178, 180, 181, 183, 184, 186, 187, 189, 190, 192,},
{ 96, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 138, 140, 141, 143, 144, 146, 147, 149, 150, 152, 153, 155, 156, 158, 159, 161, 162, 164, 165, 167, 168, 170, 171, 173, 174, 176, 177, 179, 180, 182, 183, 185, 186, 188, 189, 191,},
{ 96, 97, 99, 100, 102, 103, 105, 106, 108, 109, 111, 112, 114, 115, 117, 118, 120, 121, 123, 124, 126, 127, 129, 130, 132, 133, 135, 136, 138, 139, 141, 142, 144, 145, 147, 148, 150, 151, 153, 154, 156, 157, 159, 160, 162, 163, 165, 166, 168, 169, 171, 172, 174, 175, 177, 178, 180, 181, 183, 184, 186, 187, 189, 190,},
{ 95, 97, 98, 100, 101, 103, 104, 106, 107, 109, 110, 112, 113, 115, 116, 118, 119, 121, 122, 124, 125, 127, 128, 129, 131, 132, 134, 135, 137, 138, 140, 141, 143, 144, 146, 147, 149, 150, 152, 153, 155, 156, 158, 159, 161, 162, 164, 165, 167, 168, 170, 171, 173, 174, 176, 177, 179, 180, 182, 183, 185, 186, 188, 189,},
{ 95, 96, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, 113, 114, 115, 117, 118, 120, 121, 123, 124, 126, 127, 129, 130, 132, 133, 135, 136, 138, 139, 141, 142, 144, 145, 147, 148, 150, 151, 152, 154, 155, 157, 158, 160, 161, 163, 164, 166, 167, 169, 170, 172, 173, 175, 176, 178, 179, 181, 182, 184, 185, 187, 188,},
{ 94, 96, 97, 99, 100, 102, 103, 105, 106, 108, 109, 110, 112, 113, 115, 116, 118, 119, 121, 122, 124, 125, 127, 128, 130, 131, 133, 134, 135, 137, 138, 140, 141, 143, 144, 146, 147, 149, 150, 152, 153, 155, 156, 158, 159, 161, 162, 163, 165, 166, 168, 169, 171, 172, 174, 175, 177, 178, 180, 181, 183, 184, 186, 187,},
{ 94, 95, 97, 98, 100, 101, 103, 104, 105, 107, 108, 110, 111, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 127, 129, 130, 132, 133, 135, 136, 138, 139, 141, 142, 144, 145, 146, 148, 149, 151, 152, 154, 155, 157, 158, 160, 161, 163, 164, 166, 167, 168, 170, 171, 173, 174, 176, 177, 179, 180, 182, 183, 185, 186,},
{ 93, 95, 96, 98, 99, 101, 102, 103, 105, 106, 108, 109, 111, 112, 114, 115, 117, 118, 119, 121, 122, 124, 125, 127, 128, 130, 131, 133, 134, 136, 137, 138, 140, 141, 143, 144, 146, 147, 149, 150, 152, 153, 154, 156, 157, 159, 160, 162, 163, 165, 166, 168, 169, 170, 172, 173, 175, 176, 178, 179, 181, 182, 184, 185,},
{ 93, 94, 96, 97, 99, 100, 101, 103, 104, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 130, 132, 133, 135, 136, 138, 139, 141, 142, 143, 145, 146, 148, 149, 151, 152, 154, 155, 157, 158, 159, 161, 162, 164, 165, 167, 168, 170, 171, 172, 174, 175, 177, 178, 180, 181, 183, 184,},
{ 92, 94, 95, 97, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, 112, 114, 115, 117, 118, 120, 121, 123, 124, 125, 127, 128, 130, 131, 133, 134, 135, 137, 138, 140, 141, 143, 144, 146, 147, 148, 150, 151, 153, 154, 156, 157, 159, 160, 161, 163, 164, 166, 167, 169, 170, 172, 173, 174, 176, 177, 179, 180, 182, 183,},
{ 92, 93, 95, 96, 97, 99, 100, 102, 103, 105, 106, 108, 109, 110, 112, 113, 115, 116, 118, 119, 120, 122, 123, 125, 126, 128, 129, 130, 132, 133, 135, 136, 138, 139, 140, 142, 143, 145, 146, 148, 149, 151, 152, 153, 155, 156, 158, 159, 161, 162, 163, 165, 166, 168, 169, 171, 172, 173, 175, 176, 178, 179, 181, 182,},
{ 91, 93, 94, 96, 97, 98, 100, 101, 103, 104, 106, 107, 108, 110, 111, 113, 114, 115, 117, 118, 120, 121, 123, 124, 125, 127, 128, 130, 131, 133, 134, 135, 137, 138, 140, 141, 143, 144, 145, 147, 148, 150, 151, 153, 154, 155, 157, 158, 160, 161, 163, 164, 165, 167, 168, 170, 171, 173, 174, 175, 177, 178, 180, 181,},
{ 91, 92, 94, 95, 96, 98, 99, 101, 102, 104, 105, 106, 108, 109, 111, 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 129, 130, 132, 133, 135, 136, 138, 139, 140, 142, 143, 145, 146, 147, 149, 150, 152, 153, 155, 156, 157, 159, 160, 162, 163, 164, 166, 167, 169, 170, 172, 173, 174, 176, 177, 179, 180,},
{ 90, 92, 93, 94, 96, 97, 99, 100, 102, 103, 104, 106, 107, 109, 110, 111, 113, 114, 116, 117, 118, 120, 121, 123, 124, 126, 127, 128, 130, 131, 133, 134, 135, 137, 138, 140, 141, 142, 144, 145, 147, 148, 149, 151, 152, 154, 155, 157, 158, 159, 161, 162, 164, 165, 166, 168, 169, 171, 172, 173, 175, 176, 178, 179,},
{ 90, 91, 93, 94, 95, 97, 98, 100, 101, 102, 104, 105, 107, 108, 109, 111, 112, 114, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 129, 130, 132, 133, 135, 136, 137, 139, 140, 142, 143, 144, 146, 147, 149, 150, 151, 153, 154, 156, 157, 158, 160, 161, 163, 164, 165, 167, 168, 170, 171, 172, 174, 175, 177, 178,},
{ 89, 91, 92, 93, 95, 96, 98, 99, 100, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 121, 123, 124, 126, 127, 128, 130, 131, 132, 134, 135, 137, 138, 139, 141, 142, 144, 145, 146, 148, 149, 151, 152, 153, 155, 156, 158, 159, 160, 162, 163, 165, 166, 167, 169, 170, 172, 173, 174, 176, 177,},
{ 89, 90, 92, 93, 94, 96, 97, 98, 100, 101, 103, 104, 105, 107, 108, 110, 111, 112, 114, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 129, 130, 132, 133, 135, 136, 137, 139, 140, 141, 143, 144, 146, 147, 148, 150, 151, 153, 154, 155, 157, 158, 159, 161, 162, 164, 165, 166, 168, 169, 171, 172, 173, 175, 176,},
{ 88, 90, 91, 92, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 108, 109, 110, 112, 113, 114, 116, 117, 119, 120, 121, 123, 124, 125, 127, 128, 130, 131, 132, 134, 135, 137, 138, 139, 141, 142, 143, 145, 146, 148, 149, 150, 152, 153, 154, 156, 157, 159, 160, 161, 163, 164, 165, 167, 168, 170, 171, 172, 174, 175,},
{ 88, 89, 90, 92, 93, 95, 96, 97, 99, 100, 101, 103, 104, 106, 107, 108, 110, 111, 112, 114, 115, 117, 118, 119, 121, 122, 123, 125, 126, 128, 129, 130, 132, 133, 134, 136, 137, 138, 140, 141, 143, 144, 145, 147, 148, 149, 151, 152, 154, 155, 156, 158, 159, 160, 162, 163, 165, 166, 167, 169, 170, 171, 173, 174,},
{ 87, 89, 90, 91, 93, 94, 95, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 110, 112, 113, 115, 116, 117, 119, 120, 121, 123, 124, 125, 127, 128, 130, 131, 132, 134, 135, 136, 138, 139, 140, 142, 143, 145, 146, 147, 149, 150, 151, 153, 154, 155, 157, 158, 160, 161, 162, 164, 165, 166, 168, 169, 170, 172, 173,},
{ 87, 88, 89, 91, 92, 94, 95, 96, 98, 99, 100, 102, 103, 104, 106, 107, 108, 110, 111, 113, 114, 115, 117, 118, 119, 121, 122, 123, 125, 126, 127, 129, 130, 131, 133, 134, 136, 137, 138, 140, 141, 142, 144, 145, 146, 148, 149, 150, 152, 153, 155, 156, 157, 159, 160, 161, 163, 164, 165, 167, 168, 169, 171, 172,},
{ 86, 88, 89, 90, 92, 93, 94, 96, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 111, 112, 113, 115, 116, 117, 119, 120, 121, 123, 124, 125, 127, 128, 129, 131, 132, 133, 135, 136, 137, 139, 140, 142, 143, 144, 146, 147, 148, 150, 151, 152, 154, 155, 156, 158, 159, 160, 162, 163, 164, 166, 167, 168, 170, 171,},
{ 86, 87, 88, 90, 91, 92, 94, 95, 96, 98, 99, 100, 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 117, 118, 119, 121, 122, 123, 125, 126, 127, 129, 130, 131, 133, 134, 135, 137, 138, 139, 141, 142, 143, 145, 146, 147, 149, 150, 151, 153, 154, 155, 157, 158, 159, 161, 162, 163, 165, 166, 167, 169, 170,},
{ 85, 87, 88, 89, 91, 92, 93, 95, 96, 97, 99, 100, 101, 103, 104, 105, 107, 108, 109, 111, 112, 113, 115, 116, 117, 119, 120, 121, 123, 124, 125, 127, 128, 129, 131, 132, 133, 135, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148, 149, 151, 152, 153, 155, 156, 157, 159, 160, 161, 163, 164, 165, 167, 168, 169,},
{ 85, 86, 87, 89, 90, 91, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 117, 118, 119, 121, 122, 123, 124, 126, 127, 128, 130, 131, 132, 134, 135, 136, 138, 139, 140, 142, 143, 144, 146, 147, 148, 150, 151, 152, 154, 155, 156, 158, 159, 160, 162, 163, 164, 166, 167, 168,},
{ 84, 86, 87, 88, 90, 91, 92, 93, 95, 96, 97, 99, 100, 101, 103, 104, 105, 107, 108, 109, 111, 112, 113, 115, 116, 117, 118, 120, 121, 122, 124, 125, 126, 128, 129, 130, 132, 133, 134, 136, 137, 138, 140, 141, 142, 143, 145, 146, 147, 149, 150, 151, 153, 154, 155, 157, 158, 159, 161, 162, 163, 165, 166, 167,},
{ 84, 85, 86, 88, 89, 90, 92, 93, 94, 96, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 116, 118, 119, 120, 122, 123, 124, 126, 127, 128, 130, 131, 132, 133, 135, 136, 137, 139, 140, 141, 143, 144, 145, 147, 148, 149, 150, 152, 153, 154, 156, 157, 158, 160, 161, 162, 164, 165, 166,},
{ 83, 85, 86, 87, 88, 90, 91, 92, 94, 95, 96, 98, 99, 100, 101, 103, 104, 105, 107, 108, 109, 111, 112, 113, 114, 116, 117, 118, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 133, 134, 135, 137, 138, 139, 140, 142, 143, 144, 146, 147, 148, 150, 151, 152, 153, 155, 156, 157, 159, 160, 161, 163, 164, 165,},
{ 83, 84, 85, 87, 88, 89, 91, 92, 93, 94, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 109, 110, 111, 112, 114, 115, 116, 118, 119, 120, 122, 123, 124, 125, 127, 128, 129, 131, 132, 133, 134, 136, 137, 138, 140, 141, 142, 144, 145, 146, 147, 149, 150, 151, 153, 154, 155, 156, 158, 159, 160, 162, 163, 164,},
{ 82, 84, 85, 86, 87, 89, 90, 91, 93, 94, 95, 96, 98, 99, 100, 102, 103, 104, 105, 107, 108, 109, 111, 112, 113, 114, 116, 117, 118, 120, 121, 122, 123, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 138, 139, 140, 141, 143, 144, 145, 147, 148, 149, 150, 152, 153, 154, 156, 157, 158, 159, 161, 162, 163,},
{ 82, 83, 84, 86, 87, 88, 89, 91, 92, 93, 95, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 109, 110, 111, 112, 114, 115, 116, 118, 119, 120, 121, 123, 124, 125, 126, 128, 129, 130, 132, 133, 134, 135, 137, 138, 139, 141, 142, 143, 144, 146, 147, 148, 149, 151, 152, 153, 155, 156, 157, 158, 160, 161, 162,},
{ 81, 83, 84, 85, 86, 88, 89, 90, 91, 93, 94, 95, 96, 98, 99, 100, 102, 103, 104, 105, 107, 108, 109, 110, 112, 113, 114, 116, 117, 118, 119, 121, 122, 123, 124, 126, 127, 128, 129, 131, 132, 133, 135, 136, 137, 138, 140, 141, 142, 143, 145, 146, 147, 149, 150, 151, 152, 154, 155, 156, 157, 159, 160, 161,},
{ 81, 82, 83, 85, 86, 87, 88, 90, 91, 92, 93, 95, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 109, 110, 111, 112, 114, 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 138, 139, 140, 141, 143, 144, 145, 146, 148, 149, 150, 151, 153, 154, 155, 156, 158, 159, 160,},
{ 80, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 100, 102, 103, 104, 105, 107, 108, 109, 110, 112, 113, 114, 115, 117, 118, 119, 120, 122, 123, 124, 125, 127, 128, 129, 130, 132, 133, 134, 135, 137, 138, 139, 140, 142, 143, 144, 145, 147, 148, 149, 150, 152, 153, 154, 155, 157, 158, 159,},
{ 80, 81, 82, 83, 85, 86, 87, 88, 90, 91, 92, 93, 95, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 108, 110, 111, 112, 113, 115, 116, 117, 118, 120, 121, 122, 123, 125, 126, 127, 128, 130, 131, 132, 133, 135, 136, 137, 138, 140, 141, 142, 143, 145, 146, 147, 148, 150, 151, 152, 153, 155, 156, 157, 158,},
{ 79, 80, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 100, 102, 103, 104, 105, 106, 108, 109, 110, 111, 113, 114, 115, 116, 118, 119, 120, 121, 123, 124, 125, 126, 128, 129, 130, 131, 132, 134, 135, 136, 137, 139, 140, 141, 142, 144, 145, 146, 147, 149, 150, 151, 152, 154, 155, 156, 157,},
{ 79, 80, 81, 82, 84, 85, 86, 87, 89, 90, 91, 92, 94, 95, 96, 97, 98, 100, 101, 102, 103, 105, 106, 107, 108, 110, 111, 112, 113, 114, 116, 117, 118, 119, 121, 122, 123, 124, 126, 127, 128, 129, 130, 132, 133, 134, 135, 137, 138, 139, 140, 142, 143, 144, 145, 146, 148, 149, 150, 151, 153, 154, 155, 156,},
{ 78, 79, 81, 82, 83, 84, 86, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 100, 101, 103, 104, 105, 106, 108, 109, 110, 111, 112, 114, 115, 116, 117, 119, 120, 121, 122, 123, 125, 126, 127, 128, 130, 131, 132, 133, 134, 136, 137, 138, 139, 141, 142, 143, 144, 145, 147, 148, 149, 150, 152, 153, 154, 155,},
{ 78, 79, 80, 81, 83, 84, 85, 86, 87, 89, 90, 91, 92, 94, 95, 96, 97, 98, 100, 101, 102, 103, 104, 106, 107, 108, 109, 111, 112, 113, 114, 115, 117, 118, 119, 120, 121, 123, 124, 125, 126, 128, 129, 130, 131, 132, 134, 135, 136, 137, 138, 140, 141, 142, 143, 145, 146, 147, 148, 149, 151, 152, 153, 154,},
{ 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 103, 104, 105, 106, 107, 109, 110, 111, 112, 113, 115, 116, 117, 118, 119, 121, 122, 123, 124, 126, 127, 128, 129, 130, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 144, 145, 146, 147, 148, 150, 151, 152, 153,},
{ 77, 78, 79, 80, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 94, 95, 96, 97, 98, 100, 101, 102, 103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122, 124, 125, 126, 127, 128, 130, 131, 132, 133, 134, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 148, 149, 150, 151, 152,},
{ 76, 77, 79, 80, 81, 82, 83, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 135, 136, 137, 138, 139, 141, 142, 143, 144, 145, 147, 148, 149, 150, 151,},
{ 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 107, 108, 109, 110, 111, 112, 114, 115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 127, 128, 129, 130, 131, 133, 134, 135, 136, 137, 138, 140, 141, 142, 143, 144, 146, 147, 148, 149, 150,},
{ 75, 76, 78, 79, 80, 81, 82, 83, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 105, 106, 107, 108, 109, 111, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122, 123, 125, 126, 127, 128, 129, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 145, 146, 147, 148, 149,},
{ 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 93, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, 123, 124, 125, 126, 127, 128, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 144, 145, 146, 147, 148,},
{ 74, 75, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 99, 100, 101, 102, 103, 104, 106, 107, 108, 109, 110, 111, 113, 114, 115, 116, 117, 118, 119, 121, 122, 123, 124, 125, 126, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, 139, 140, 142, 143, 144, 145, 146, 147,},
{ 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 93, 94, 96, 97, 98, 99, 100, 101, 103, 104, 105, 106, 107, 108, 109, 111, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122, 123, 124, 126, 127, 128, 129, 130, 131, 133, 134, 135, 136, 137, 138, 139, 141, 142, 143, 144, 145, 146,},
{ 73, 74, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 100, 101, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, 122, 124, 125, 126, 127, 128, 129, 130, 132, 133, 134, 135, 136, 137, 138, 140, 141, 142, 143, 144, 145,},
{ 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 103, 105, 106, 107, 108, 109, 110, 111, 113, 114, 115, 116, 117, 118, 119, 120, 122, 123, 124, 125, 126, 127, 128, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144,},
{ 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90, 91, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143,},
{ 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 104, 105, 107, 108, 109, 110, 111, 112, 113, 114, 115, 117, 118, 119, 120, 121, 122, 123, 124, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, 139, 140, 141, 142,},
{ 71, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 97, 98, 99, 100, 101, 102, 104, 105, 106, 107, 108, 109, 110, 111, 112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 124, 125, 126, 127, 128, 129, 130, 131, 132, 134, 135, 136, 137, 138, 139, 140, 141,},
{ 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 122, 123, 124, 125, 126, 127, 128, 129, 130, 132, 133, 134, 135, 136, 137, 138, 139, 140,},
{ 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139,},
{ 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,},
{ 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137,},
{ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136,},
{ 68, 69, 70, 71, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,},
{ 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,},
{ 67, 68, 69, 70, 71, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133,},
{ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132,},
{ 66, 67, 68, 69, 70, 71, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131,},
{ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,},
{ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,},
{ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128,},
{ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,},
{ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,},
{ 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,},
{ 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,},
{ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124,},
{ 62, 63, 64, 65, 66, 67, 68, 69, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123,},
{ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,},
{ 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,},
{ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120,},
{ 60, 61, 62, 63, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,},
{ 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,},
{ 59, 60, 61, 62, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,},
{ 58, 59, 60, 61, 62, 63, 64, 65, 66, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,},
{ 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,},
{ 57, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 98, 99, 100, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112, 113, 114,},
{ 57, 58, 59, 59, 60, 61, 62, 63, 64, 65, 66, 67, 67, 68, 69, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 79, 80, 81, 82, 82, 83, 84, 85, 86, 87, 88, 89, 90, 90, 91, 92, 93, 94, 95, 96, 97, 98, 98, 99, 100, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112, 113,},
{ 56, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65, 66, 67, 68, 69, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 83, 84, 85, 86, 87, 88, 89, 90, 91, 91, 92, 93, 94, 95, 96, 97, 98, 98, 99, 100, 101, 102, 103, 104, 105, 105, 106, 107, 108, 109, 110, 111, 112,},
{ 56, 57, 57, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 70, 71, 71, 72, 73, 74, 75, 76, 77, 78, 78, 79, 80, 81, 82, 83, 84, 84, 85, 86, 87, 88, 89, 90, 91, 91, 92, 93, 94, 95, 96, 97, 98, 98, 99, 100, 101, 102, 103, 104, 105, 105, 106, 107, 108, 109, 110, 111,},
{ 55, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 66, 67, 68, 69, 70, 71, 72, 73, 73, 74, 75, 76, 77, 78, 79, 79, 80, 81, 82, 83, 84, 85, 85, 86, 87, 88, 89, 90, 91, 92, 92, 93, 94, 95, 96, 97, 98, 98, 99, 100, 101, 102, 103, 104, 104, 105, 106, 107, 108, 109, 110,},
{ 55, 56, 56, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65, 66, 67, 68, 68, 69, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 79, 80, 80, 81, 82, 83, 84, 85, 86, 86, 87, 88, 89, 90, 91, 92, 92, 93, 94, 95, 96, 97, 98, 98, 99, 100, 101, 102, 103, 104, 104, 105, 106, 107, 108, 109,},
{ 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 86, 87, 88, 89, 90, 91, 92, 92, 93, 94, 95, 96, 97, 97, 98, 99, 100, 101, 102, 103, 103, 104, 105, 106, 107, 108,},
{ 54, 55, 55, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 66, 67, 68, 69, 70, 71, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 87, 88, 89, 90, 91, 92, 92, 93, 94, 95, 96, 97, 97, 98, 99, 100, 101, 102, 102, 103, 104, 105, 106, 107,},
{ 53, 54, 55, 56, 57, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65, 66, 67, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, 76, 77, 77, 78, 79, 80, 81, 82, 82, 83, 84, 85, 86, 87, 87, 88, 89, 90, 91, 92, 92, 93, 94, 95, 96, 97, 97, 98, 99, 100, 101, 102, 102, 103, 104, 105, 106,},
{ 53, 54, 54, 55, 56, 57, 58, 59, 59, 60, 61, 62, 63, 63, 64, 65, 66, 67, 68, 68, 69, 70, 71, 72, 73, 73, 74, 75, 76, 77, 77, 78, 79, 80, 81, 82, 82, 83, 84, 85, 86, 87, 87, 88, 89, 90, 91, 91, 92, 93, 94, 95, 96, 96, 97, 98, 99, 100, 101, 101, 102, 103, 104, 105,},
{ 52, 53, 54, 55, 56, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 69, 70, 71, 72, 73, 73, 74, 75, 76, 77, 78, 78, 79, 80, 81, 82, 82, 83, 84, 85, 86, 87, 87, 88, 89, 90, 91, 91, 92, 93, 94, 95, 96, 96, 97, 98, 99, 100, 100, 101, 102, 103, 104,},
{ 52, 53, 53, 54, 55, 56, 57, 57, 58, 59, 60, 61, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 78, 79, 80, 81, 82, 82, 83, 84, 85, 86, 87, 87, 88, 89, 90, 91, 91, 92, 93, 94, 95, 95, 96, 97, 98, 99, 99, 100, 101, 102, 103,},
{ 51, 52, 53, 54, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 62, 63, 64, 65, 66, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 78, 79, 80, 81, 82, 82, 83, 84, 85, 86, 86, 87, 88, 89, 90, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 98, 99, 100, 101, 102,},
{ 51, 52, 52, 53, 54, 55, 56, 56, 57, 58, 59, 59, 60, 61, 62, 63, 63, 64, 65, 66, 67, 67, 68, 69, 70, 71, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 79, 80, 81, 82, 82, 83, 84, 85, 86, 86, 87, 88, 89, 90, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 98, 99, 100, 101,},
{ 50, 51, 52, 53, 53, 54, 55, 56, 57, 57, 58, 59, 60, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 68, 69, 70, 71, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 79, 80, 81, 82, 82, 83, 84, 85, 86, 86, 87, 88, 89, 90, 90, 91, 92, 93, 93, 94, 95, 96, 97, 97, 98, 99, 100,},
{ 50, 51, 51, 52, 53, 54, 54, 55, 56, 57, 58, 58, 59, 60, 61, 61, 62, 63, 64, 65, 65, 66, 67, 68, 68, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 78, 79, 79, 80, 81, 82, 82, 83, 84, 85, 86, 86, 87, 88, 89, 89, 90, 91, 92, 93, 93, 94, 95, 96, 96, 97, 98, 99,},
{ 49, 50, 51, 52, 52, 53, 54, 55, 55, 56, 57, 58, 58, 59, 60, 61, 62, 62, 63, 64, 65, 65, 66, 67, 68, 68, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 78, 78, 79, 80, 81, 82, 82, 83, 84, 85, 85, 86, 87, 88, 88, 89, 90, 91, 92, 92, 93, 94, 95, 95, 96, 97, 98,},
{ 49, 50, 50, 51, 52, 53, 53, 54, 55, 56, 56, 57, 58, 59, 59, 60, 61, 62, 62, 63, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 78, 78, 79, 80, 81, 82, 82, 83, 84, 85, 85, 86, 87, 88, 88, 89, 90, 91, 91, 92, 93, 94, 94, 95, 96, 97,},
{ 48, 49, 50, 51, 51, 52, 53, 54, 54, 55, 56, 57, 57, 58, 59, 60, 60, 61, 62, 63, 63, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, 84, 84, 85, 86, 87, 87, 88, 89, 90, 90, 91, 92, 93, 93, 94, 95, 96,},
{ 48, 48, 49, 50, 51, 51, 52, 53, 54, 54, 55, 56, 57, 57, 58, 59, 60, 60, 61, 62, 63, 63, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, 84, 84, 85, 86, 87, 87, 88, 89, 90, 90, 91, 92, 93, 93, 94, 95,},
{ 47, 48, 49, 49, 50, 51, 52, 52, 53, 54, 55, 55, 56, 57, 58, 58, 59, 60, 61, 61, 62, 63, 63, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 78, 78, 79, 80, 80, 81, 82, 83, 83, 84, 85, 86, 86, 87, 88, 89, 89, 90, 91, 92, 92, 93, 94,},
{ 47, 47, 48, 49, 50, 50, 51, 52, 53, 53, 54, 55, 56, 56, 57, 58, 58, 59, 60, 61, 61, 62, 63, 64, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 77, 78, 79, 80, 80, 81, 82, 83, 83, 84, 85, 85, 86, 87, 88, 88, 89, 90, 91, 91, 92, 93,},
{ 46, 47, 48, 48, 49, 50, 51, 51, 52, 53, 53, 54, 55, 56, 56, 57, 58, 59, 59, 60, 61, 61, 62, 63, 64, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 72, 72, 73, 74, 74, 75, 76, 77, 77, 78, 79, 79, 80, 81, 82, 82, 83, 84, 85, 85, 86, 87, 87, 88, 89, 90, 90, 91, 92,},
{ 46, 46, 47, 48, 49, 49, 50, 51, 51, 52, 53, 54, 54, 55, 56, 56, 57, 58, 59, 59, 60, 61, 61, 62, 63, 64, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 71, 72, 73, 74, 74, 75, 76, 76, 77, 78, 79, 79, 80, 81, 81, 82, 83, 84, 84, 85, 86, 86, 87, 88, 89, 89, 90, 91,},
{ 45, 46, 47, 47, 48, 49, 49, 50, 51, 52, 52, 53, 54, 54, 55, 56, 57, 57, 58, 59, 59, 60, 61, 62, 62, 63, 64, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 71, 72, 73, 74, 74, 75, 76, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, 83, 84, 85, 86, 86, 87, 88, 88, 89, 90,},
{ 45, 45, 46, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 62, 62, 63, 64, 64, 65, 66, 66, 67, 68, 69, 69, 70, 71, 71, 72, 73, 73, 74, 75, 76, 76, 77, 78, 78, 79, 80, 80, 81, 82, 83, 83, 84, 85, 85, 86, 87, 87, 88, 89,},
{ 44, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 62, 62, 63, 64, 64, 65, 66, 66, 67, 68, 68, 69, 70, 71, 71, 72, 73, 73, 74, 75, 75, 76, 77, 77, 78, 79, 80, 80, 81, 82, 82, 83, 84, 84, 85, 86, 86, 87, 88,},
{ 44, 44, 45, 46, 46, 47, 48, 49, 49, 50, 51, 51, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 62, 62, 63, 64, 64, 65, 66, 66, 67, 68, 68, 69, 70, 70, 71, 72, 72, 73, 74, 75, 75, 76, 77, 77, 78, 79, 79, 80, 81, 81, 82, 83, 83, 84, 85, 85, 86, 87,},
{ 43, 44, 45, 45, 46, 47, 47, 48, 49, 49, 50, 51, 51, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 61, 62, 63, 64, 64, 65, 66, 66, 67, 68, 68, 69, 70, 70, 71, 72, 72, 73, 74, 74, 75, 76, 76, 77, 78, 78, 79, 80, 80, 81, 82, 82, 83, 84, 84, 85, 86,},
{ 43, 43, 44, 45, 45, 46, 47, 47, 48, 49, 49, 50, 51, 51, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 61, 62, 63, 63, 64, 65, 65, 66, 67, 67, 68, 69, 69, 70, 71, 71, 72, 73, 73, 74, 75, 75, 76, 77, 77, 78, 79, 79, 80, 81, 81, 82, 83, 83, 84, 85,},
{ 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 51, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 61, 62, 63, 63, 64, 65, 65, 66, 67, 67, 68, 69, 69, 70, 71, 71, 72, 73, 73, 74, 75, 75, 76, 77, 77, 78, 79, 79, 80, 81, 81, 82, 83, 83, 84,},
{ 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 61, 62, 63, 63, 64, 65, 65, 66, 67, 67, 68, 68, 69, 70, 70, 71, 72, 72, 73, 74, 74, 75, 76, 76, 77, 78, 78, 79, 80, 80, 81, 82, 82, 83,},
{ 41, 42, 43, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 61, 61, 62, 63, 63, 64, 64, 65, 66, 66, 67, 68, 68, 69, 70, 70, 71, 72, 72, 73, 73, 74, 75, 75, 76, 77, 77, 78, 79, 79, 80, 81, 81, 82,},
{ 41, 41, 42, 43, 43, 44, 45, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 59, 59, 60, 60, 61, 62, 62, 63, 64, 64, 65, 66, 66, 67, 67, 68, 69, 69, 70, 71, 71, 72, 73, 73, 74, 74, 75, 76, 76, 77, 78, 78, 79, 80, 80, 81,},
{ 40, 41, 42, 42, 43, 43, 44, 45, 45, 46, 47, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 58, 59, 60, 60, 61, 62, 62, 63, 64, 64, 65, 65, 66, 67, 67, 68, 69, 69, 70, 70, 71, 72, 72, 73, 74, 74, 75, 75, 76, 77, 77, 78, 79, 79, 80,},
{ 40, 40, 41, 42, 42, 43, 43, 44, 45, 45, 46, 47, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 53, 54, 55, 55, 56, 57, 57, 58, 58, 59, 60, 60, 61, 61, 62, 63, 63, 64, 65, 65, 66, 66, 67, 68, 68, 69, 70, 70, 71, 71, 72, 73, 73, 74, 75, 75, 76, 76, 77, 78, 78, 79,},
{ 39, 40, 40, 41, 42, 42, 43, 44, 44, 45, 45, 46, 47, 47, 48, 48, 49, 50, 50, 51, 52, 52, 53, 53, 54, 55, 55, 56, 56, 57, 58, 58, 59, 59, 60, 61, 61, 62, 63, 63, 64, 64, 65, 66, 66, 67, 67, 68, 69, 69, 70, 71, 71, 72, 72, 73, 74, 74, 75, 75, 76, 77, 77, 78,},
{ 39, 39, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 47, 47, 48, 48, 49, 50, 50, 51, 51, 52, 53, 53, 54, 54, 55, 56, 56, 57, 58, 58, 59, 59, 60, 61, 61, 62, 62, 63, 64, 64, 65, 65, 66, 67, 67, 68, 68, 69, 70, 70, 71, 71, 72, 73, 73, 74, 74, 75, 76, 76, 77,},
{ 38, 39, 39, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 47, 47, 48, 48, 49, 50, 50, 51, 51, 52, 53, 53, 54, 54, 55, 56, 56, 57, 57, 58, 59, 59, 60, 60, 61, 62, 62, 63, 63, 64, 65, 65, 66, 66, 67, 68, 68, 69, 69, 70, 71, 71, 72, 72, 73, 74, 74, 75, 75, 76,},
{ 38, 38, 39, 40, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 47, 47, 48, 48, 49, 50, 50, 51, 51, 52, 52, 53, 54, 54, 55, 55, 56, 57, 57, 58, 58, 59, 60, 60, 61, 61, 62, 63, 63, 64, 64, 65, 65, 66, 67, 67, 68, 68, 69, 70, 70, 71, 71, 72, 73, 73, 74, 74, 75,},
{ 37, 38, 38, 39, 40, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 47, 47, 48, 48, 49, 49, 50, 51, 51, 52, 52, 53, 54, 54, 55, 55, 56, 56, 57, 58, 58, 59, 59, 60, 61, 61, 62, 62, 63, 63, 64, 65, 65, 66, 66, 67, 68, 68, 69, 69, 70, 70, 71, 72, 72, 73, 73, 74,},
{ 37, 37, 38, 38, 39, 40, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 47, 47, 48, 48, 49, 49, 50, 51, 51, 52, 52, 53, 53, 54, 55, 55, 56, 56, 57, 57, 58, 59, 59, 60, 60, 61, 61, 62, 63, 63, 64, 64, 65, 65, 66, 67, 67, 68, 68, 69, 69, 70, 71, 71, 72, 72, 73,},
{ 36, 37, 37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 46, 47, 48, 48, 49, 49, 50, 50, 51, 52, 52, 53, 53, 54, 54, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 61, 61, 62, 62, 63, 63, 64, 65, 65, 66, 66, 67, 67, 68, 69, 69, 70, 70, 71, 71, 72,},
{ 36, 36, 37, 37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 49, 49, 50, 50, 51, 51, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 63, 63, 64, 64, 65, 65, 66, 66, 67, 68, 68, 69, 69, 70, 70, 71,},
{ 35, 36, 36, 37, 37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 61, 61, 62, 62, 63, 63, 64, 64, 65, 66, 66, 67, 67, 68, 68, 69, 69, 70,},
{ 35, 35, 36, 36, 37, 37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 64, 64, 65, 65, 66, 66, 67, 67, 68, 68, 69,},
{ 34, 35, 35, 36, 36, 37, 37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 62, 62, 63, 63, 64, 64, 65, 65, 66, 66, 67, 67, 68,},
{ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 63, 64, 64, 65, 65, 66, 66, 67,},
{ 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 63, 64, 64, 65, 65, 66,},
{ 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 63, 64, 64, 65,},
{ 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 63, 64,},
{ 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 63,},
{ 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62,},
{ 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61,},
{ 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60,},
{ 30, 30, 31, 31, 32, 32, 33, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59,},
{ 29, 30, 30, 31, 31, 32, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58,},
{ 29, 29, 30, 30, 31, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57,},
{ 28, 29, 29, 30, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 38, 39, 39, 40, 40, 41, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 53, 54, 54, 55, 55, 56, 56,},
{ 28, 28, 29, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 33, 34, 34, 35, 35, 36, 36, 36, 37, 37, 38, 38, 39, 39, 39, 40, 40, 41, 41, 42, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 46, 47, 47, 48, 48, 49, 49, 49, 50, 50, 51, 51, 52, 52, 52, 53, 53, 54, 54, 55, 55,},
{ 27, 28, 28, 29, 29, 29, 30, 30, 31, 31, 32, 32, 32, 33, 33, 34, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 39, 39, 40, 40, 40, 41, 41, 42, 42, 43, 43, 43, 44, 44, 45, 45, 46, 46, 46, 47, 47, 48, 48, 49, 49, 49, 50, 50, 51, 51, 52, 52, 52, 53, 53, 54, 54,},
{ 27, 27, 28, 28, 28, 29, 29, 30, 30, 31, 31, 31, 32, 32, 33, 33, 33, 34, 34, 35, 35, 36, 36, 36, 37, 37, 38, 38, 38, 39, 39, 40, 40, 41, 41, 41, 42, 42, 43, 43, 43, 44, 44, 45, 45, 46, 46, 46, 47, 47, 48, 48, 48, 49, 49, 50, 50, 51, 51, 51, 52, 52, 53, 53,},
{ 26, 27, 27, 27, 28, 28, 29, 29, 30, 30, 30, 31, 31, 32, 32, 32, 33, 33, 34, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 42, 42, 43, 43, 43, 44, 44, 45, 45, 46, 46, 46, 47, 47, 48, 48, 48, 49, 49, 50, 50, 50, 51, 51, 52, 52,},
{ 26, 26, 27, 27, 27, 28, 28, 29, 29, 29, 30, 30, 31, 31, 31, 32, 32, 33, 33, 33, 34, 34, 35, 35, 35, 36, 36, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 42, 42, 43, 43, 43, 44, 44, 45, 45, 45, 46, 46, 47, 47, 47, 48, 48, 49, 49, 49, 50, 50, 51, 51,},
{ 25, 26, 26, 26, 27, 27, 28, 28, 28, 29, 29, 30, 30, 30, 31, 31, 32, 32, 32, 33, 33, 34, 34, 34, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 42, 42, 43, 43, 43, 44, 44, 45, 45, 45, 46, 46, 47, 47, 47, 48, 48, 49, 49, 49, 50, 50,},
{ 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 29, 29, 29, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 34, 34, 34, 35, 35, 36, 36, 36, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45, 46, 46, 46, 47, 47, 48, 48, 48, 49, 49,},
{ 24, 25, 25, 25, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 36, 36, 36, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43, 44, 44, 44, 45, 45, 45, 46, 46, 47, 47, 47, 48, 48,},
{ 24, 24, 24, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 45, 45, 45, 46, 46, 46, 47, 47,},
{ 23, 24, 24, 24, 25, 25, 25, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45, 45, 46, 46,},
{ 23, 23, 23, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45,},
{ 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44,},
{ 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43,},
{ 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42,},
{ 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41,},
{ 20, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40,},
{ 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39,},
{ 19, 20, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38,},
{ 19, 19, 19, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 33, 34, 34, 34, 35, 35, 35, 35, 36, 36, 36, 37, 37, 37,},
{ 18, 19, 19, 19, 19, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 33, 33, 33, 33, 34, 34, 34, 35, 35, 35, 35, 36, 36, 36,},
{ 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33, 34, 34, 34, 34, 35, 35, 35,},
{ 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33, 33, 34, 34, 34,},
{ 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32, 32, 33, 33, 33,},
{ 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31, 32, 32, 32,},
{ 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30, 31, 31, 31, 31,},
{ 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 30, 30, 30, 30,},
{ 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29,},
{ 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 26, 27, 27, 27, 27, 28, 28, 28, 28,},
{ 14, 14, 14, 14, 15, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 26, 27, 27, 27, 27,},
{ 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 26, 26, 26, 26,},
{ 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25,},
{ 12, 12, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24,},
{ 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23,},
{ 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22,},
{ 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21,},
{ 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20,},
{ 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19,},
{ 9, 9, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18,},
{ 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17,},
{ 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16,},
{ 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,},
{ 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14,},
{ 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13,},
{ 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,},
{ 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,},
{ 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,},
{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,},
{ 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,},
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,},
{ 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,},
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,},
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,},
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,},
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,},
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,},
{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,},
};
#endif
const uint8_t ProbModelTables::m_RenormTable_32[32] =
{
6, 5, 4, 4,
3, 3, 3, 3,
2, 2, 2, 2,
2, 2, 2, 2,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1
};
#if JEM_TOOLS
const uint8_t ProbModelTables::m_RenormTable_128[128] =
{
7, 6, 5, 5,
4, 4, 4, 4,
3, 3, 3, 3,
3, 3, 3, 3,
2, 2, 2, 2,
2, 2, 2, 2,
2, 2, 2, 2,
2, 2, 2, 2,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
};
#endif
#if JEM_TOOLS
const uint16_t ProbModelTables::m_InistateToCount[128] =
{
614, 647, 681, 718, 756, 797, 839, 884, 932, 982, 1034, 1089, 1148, 1209, 1274, 1342,
1414, 1490, 1569, 1653, 1742, 1835, 1933, 2037, 2146, 2261, 2382, 2509, 2643, 2785, 2934, 3091,
3256, 3430, 3614, 3807, 4011, 4225, 4452, 4690, 4941, 5205, 5483, 5777, 6086, 6412, 6755, 7116,
7497, 7898, 8320, 8766, 9235, 9729, 10249, 10798, 11375, 11984, 12625, 13300, 14012, 14762, 15551, 16384,
16384, 17216, 18005, 18755, 19467, 20142, 20783, 21392, 21969, 22518, 23038, 23532, 24001, 24447, 24869, 25270,
25651, 26012, 26355, 26681, 26990, 27284, 27562, 27826, 28077, 28315, 28542, 28756, 28960, 29153, 29337, 29511,
29676, 29833, 29982, 30124, 30258, 30385, 30506, 30621, 30730, 30834, 30932, 31025, 31114, 31198, 31277, 31353,
31425, 31493, 31558, 31619, 31678, 31733, 31785, 31835, 31883, 31928, 31970, 32011, 32049, 32086, 32120, 32153
};
#endif
void BinProbModel_Std::init( int qp, int initId )
{
int slope = ( ( initId >> 4 ) * 5 ) - 45;
int offset = ( ( initId & 15 ) << 3 ) - 16;
int inistate = ( ( slope * qp ) >> 4 ) + offset;
if( inistate >= 64 )
{
m_State = ( std::min( 62, inistate - 64 ) << 1 ) + 1;
}
else
{
m_State = ( std::min( 62, 63 - inistate ) << 1 );
}
}
#if JEM_TOOLS
void BinProbModel_JMP::init( int qp, int initId )
{
int slope = ( ( initId >> 4 ) * 5 ) - 45;
int offset = ( ( initId & 15 ) << 3 ) - 16;
int inistate = ( ( slope * qp ) >> 4 ) + offset;
m_P0 = m_P1 = m_InistateToCount[ inistate < 1 ? 1 : inistate > 126 ? 126 : inistate ];
}
void BinProbModel_JAW::init( int qp, int initId )
{
int slope = ( ( initId >> 4 ) * 5 ) - 45;
int offset = ( ( initId & 15 ) << 3 ) - 16;
int inistate = ( ( slope * qp ) >> 4 ) + offset;
m_P0 = m_InistateToCount[ inistate < 1 ? 1 : inistate > 126 ? 126 : inistate ];
m_Log2WindowSize0 = m_DefaultLog2WindowSize0;
}
void BinProbModel_JMPAW::init( int qp, int initId )
{
int slope = ( ( initId >> 4 ) * 5 ) - 45;
int offset = ( ( initId & 15 ) << 3 ) - 16;
int inistate = ( ( slope * qp ) >> 4 ) + offset;
m_P0 = m_P1 = m_InistateToCount[ inistate < 1 ? 1 : inistate > 126 ? 126 : inistate ];
m_Log2WindowSize0 = m_DefaultLog2WindowSize0;
}
#endif
CtxSet::CtxSet( std::initializer_list<CtxSet> ctxSets )
{
uint16_t minOffset = std::numeric_limits<uint16_t>::max();
uint16_t maxOffset = 0;
for( auto iter = ctxSets.begin(); iter != ctxSets.end(); iter++ )
{
minOffset = std::min<uint16_t>( minOffset, (*iter).Offset );
maxOffset = std::max<uint16_t>( maxOffset, (*iter).Offset+(*iter).Size );
}
Offset = minOffset;
Size = maxOffset - minOffset;
}
const std::vector<uint8_t>& ContextSetCfg::getInitTable( unsigned initId )
{
CHECK( initId >= (unsigned)sm_InitTables.size(),
"Invalid initId (" << initId << "), only " << sm_InitTables.size() << " tables defined." );
return sm_InitTables[initId];
}
CtxSet ContextSetCfg::addCtxSet( std::initializer_list<std::initializer_list<uint8_t>> initSet2d )
{
const std::size_t startIdx = sm_InitTables[0].size();
const std::size_t numValues = ( *initSet2d.begin() ).size();
std::size_t setId = 0;
for( auto setIter = initSet2d.begin(); setIter != initSet2d.end() && setId < sm_InitTables.size(); setIter++, setId++ )
{
const std::initializer_list<uint8_t>& initSet = *setIter;
std::vector<uint8_t>& initTable = sm_InitTables[setId];
CHECK( initSet.size() != numValues,
"Number of init values do not match for all sets (" << initSet.size() << " != " << numValues << ")." );
initTable.resize( startIdx + numValues );
std::size_t elemId = startIdx;
for( auto elemIter = ( *setIter ).begin(); elemIter != ( *setIter ).end(); elemIter++, elemId++ )
{
initTable[elemId] = *elemIter;
}
}
return CtxSet( (uint16_t)startIdx, (uint16_t)numValues );
}
#define CNU 154 // dummy initialization value for unused context models 'Context model Not Used'
std::vector<std::vector<uint8_t>> ContextSetCfg::sm_InitTables( NUMBER_OF_SLICE_TYPES );
const CtxSet ContextSetCfg::SplitFlag = ContextSetCfg::addCtxSet
({
{ 107, 139, 126, 255, 0,},
{ 107, 139, 126, 255, 0,},
{ 139, 141, 157, 255, 0,},
});
const CtxSet ContextSetCfg::BTSplitFlag = ContextSetCfg::addCtxSet
({
{ 107, 139, 126, 154, 154, 154, 154, 154, 154, 154, 154, 154,},
{ 107, 139, 126, 154, 154, 154, 154, 154, 154, 154, 154, 154,},
{ 139, 141, 157, 154, 154, 154, 154, 154, 154, 154, 154, 154,},
});
const CtxSet ContextSetCfg::SkipFlag = ContextSetCfg::addCtxSet
({
{ 197, 185, 201,},
{ 197, 185, 201,},
{ CNU, CNU, CNU,},
});
const CtxSet ContextSetCfg::MergeFlag = ContextSetCfg::addCtxSet
({
{ 154,},
{ 110,},
{ CNU,},
});
const CtxSet ContextSetCfg::MergeIdx = ContextSetCfg::addCtxSet
({
{ 137, CNU, CNU, CNU, CNU,},
{ 122, CNU, CNU, CNU, CNU,},
{ CNU, CNU, CNU, CNU, CNU,},
});
const CtxSet ContextSetCfg::PartSize = ContextSetCfg::addCtxSet
({
{ 154, 139, 154, 154,},
{ 154, 139, 154, 154,},
{ 184, CNU, CNU, CNU,},
});
const CtxSet ContextSetCfg::PredMode = ContextSetCfg::addCtxSet
({
{ 134,},
{ 149,},
{ CNU,},
});
const CtxSet ContextSetCfg::IPredMode[] =
{
ContextSetCfg::addCtxSet
({
#if INTRA67_3MPM
{ 183 },
{ 154 },
{ 184 },
#else
#if JVET_B0051_NON_MPM_MODE
{ 183, CNU, CNU, CNU, 184 },
{ 154, CNU, CNU, CNU, 184 },
{ 184, CNU, CNU, CNU, 184 },
#else
{ 183, CNU, CNU, CNU, },
{ 154, CNU, CNU, CNU, },
{ 184, CNU, CNU, CNU, },
#endif
#endif
}),
ContextSetCfg::addCtxSet
({
{ 139, 152, 139, 154, 154, 154, 154, 154, 154, 154, 154, 154, },
{ 139, 152, 139, 154, 154, 154, 154, 154, 154, 154, 154, 154, },
{ 139, 63, 139, 154, 154, 154, 154, 154, 154, 154, 154, 154, },
}),
};
const CtxSet ContextSetCfg::PdpcFlag = ContextSetCfg::addCtxSet
({
{ 107,},
{ 107,},
{ 139,},
});
const CtxSet ContextSetCfg::DeltaQP = ContextSetCfg::addCtxSet
({
{ 154, 154, 154,},
{ 154, 154, 154,},
{ 154, 154, 154,},
});
const CtxSet ContextSetCfg::InterDir = ContextSetCfg::addCtxSet
({
{ 95, 79, 63, 31, 31,},
{ 95, 79, 63, 31, 31,},
{ CNU, CNU, CNU, CNU, CNU,},
});
const CtxSet ContextSetCfg::RefPic = ContextSetCfg::addCtxSet
({
{ 153, 153,},
{ 153, 153,},
{ CNU, CNU,},
});
#if JEM_TOOLS || JVET_K_AFFINE
const CtxSet ContextSetCfg::AffineFlag = ContextSetCfg::addCtxSet
({
{ 197, 185, 201,},
{ 197, 185, 201,},
{ CNU, CNU, CNU,},
});
#if JVET_K0337_AFFINE_6PARA
const CtxSet ContextSetCfg::AffineType = ContextSetCfg::addCtxSet
({
{ 92, },
{ 77, },
{ CNU, },
});
#endif
#endif
#if JVET_K0248_GBI
const CtxSet ContextSetCfg::GBiIdx = ContextSetCfg::addCtxSet
({
// 4 ctx for 1st bin; 1 ctx for each of rest bins
{ 95, 79, 63, 31, 31, 31, 31,},
{ 95, 79, 63, 31, 31, 31, 31,},
{ CNU, CNU, CNU, CNU, CNU, CNU, CNU,},
});
#endif
const CtxSet ContextSetCfg::Mvd = ContextSetCfg::addCtxSet
({
{ 169, 198,},
{ 140, 198,},
{ CNU, CNU,},
});
const CtxSet ContextSetCfg::TransSubdivFlag = ContextSetCfg::addCtxSet
({
{ 224, 167, 122, 122, 122},
{ 124, 138, 94, 94, 94},
{ 153, 138, 138, 138, 138},
});
const CtxSet ContextSetCfg::QtRootCbf = ContextSetCfg::addCtxSet
({
{ 79,},
{ 79,},
{ CNU,},
});
const CtxSet ContextSetCfg::QtCbf[] =
{
ContextSetCfg::addCtxSet
({
{ 153, 111, },
{ 153, 111, },
{ 111, 141, },
}),
ContextSetCfg::addCtxSet
({
{ 149, 92, 167, 154, 154, },
{ 149, 107, 167, 154, 154, },
{ 94, 138, 182, 154, 154, },
}),
#if JVET_K0072
ContextSetCfg::addCtxSet
({
{ 149, 149, },
{ 149, 149, },
{ 94, 94, },
}),
#endif
};
const CtxSet ContextSetCfg::SigCoeffGroup[] =
{
ContextSetCfg::addCtxSet
({
{ 121, 140, },
{ 121, 140, },
{ 91, 171, },
}),
ContextSetCfg::addCtxSet
({
{ 61, 154, },
{ 61, 154, },
{ 134, 141, },
}),
ContextSetCfg::addCtxSet
({
{ 122, 143, },
{ 78, 111, },
{ 135, 155, },
}),
ContextSetCfg::addCtxSet
({
{ 91, 141, },
{ 60, 140, },
{ 104, 139, },
}),
};
const CtxSet ContextSetCfg::SigFlag[] =
{
#if JVET_K0072
ContextSetCfg::addCtxSet
({
{ 106, 167, 182, 124, 139, 169, 134, 167, 197, 183, 183, 184, 209, 198, 168, 168, 183, 170, CNU, CNU, },
{ 135, 152, 167, 153, 168, 140, 149, 182, 153, 183, 154, 155, 180, 198, 197, 183, 169, 170, CNU, CNU, },
{ 121, 138, 124, 139, 125, 111, 135, 139, 154, 140, 155, 127, 107, 185, 169, 170, 156, 143, CNU, CNU, },
}),
ContextSetCfg::addCtxSet
({
{ 177, 196, 153, 124, 198, 183, 166, 213, 226, 198, 198, 156, },
{ 134, 168, 168, 154, 169, 199, 166, 214, 227, 229, 185, 142, },
{ 149, 168, 153, 111, 140, 126, 182, 200, 111, 143, 142, 158, },
}),
ContextSetCfg::addCtxSet
({
{ 181, 127, 173, 201, 187, 173, 226, 173, 188, 202, 173, 188, 196, 223, 237, 223, 221, 223, CNU, CNU, },
{ 123, 142, 202, 157, 157, 188, 138, 158, 203, 173, 158, 174, 182, 223, 223, 223, 206, 237, CNU, CNU, },
{ 108, 157, 173, 158, 218, 189, 123, 159, 159, 174, 189, 204, 79, 223, 223, 207, 253, 191, CNU, CNU, },
}),
ContextSetCfg::addCtxSet
({
{ 210, 170, 143, 143, 201, 244, 182, 223, 223, 223, 159, 223, },
{ 167, 155, 158, 186, 127, 158, 197, 223, 223, 223, 206, 237, },
{ 137, 158, 157, 187, 204, 159, 185, 223, 238, 220, 253, 237, },
}),
ContextSetCfg::addCtxSet
({
{ 137, 142, 159, 158, 187, 159, 241, 174, 174, 159, 159, 203, 210, 223, 223, 223, 223, 223, CNU, CNU, },
{ 123, 157, 174, 143, 143, 203, 138, 159, 189, 159, 173, 174, 196, 223, 223, 223, 223, 223, CNU, CNU, },
{ 107, 143, 218, 173, 218, 189, 63, 219, 189, 175, 189, 204, 63, 223, 223, 223, 253, 191, CNU, CNU, },
}),
ContextSetCfg::addCtxSet
({
{ 196, 199, 143, 172, 158, 203, 196, 223, 223, 223, 223, 223, },
{ 167, 155, 159, 157, 157, 158, 182, 223, 223, 223, 223, 223, },
{ 181, 159, 143, 232, 143, 173, 169, 237, 223, 223, 238, 253, },
}),
#else
ContextSetCfg::addCtxSet
({
{ 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 140, },
{ 155, 154, 139, 153, 139, 123, 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 140, },
{ 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 141, },
}),
ContextSetCfg::addCtxSet
({
{ 170, 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 140, },
{ 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183, 140, 151, 183, 140, 140, },
{ 140, 139, 182, 182, 152, 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 111, },
}),
ContextSetCfg::addCtxSet
({
{ 107, 139, 154, 140, 140, 141, 108, 154, 125, 155, 126, 127, 139, 155, 155, 141, 156, 143, 107, 139, 154, 140, 140, 141, 108, 154, 125, 155, 126, 127, 139, 155, 155, 141, 156, 143, 107, 139, 154, 140, 140, 141, 108, 154, 125, 155, 126, 127, 139, 155, 155, 141, 156, 143, },
{ 121, 167, 153, 139, 154, 140, 137, 168, 139, 154, 169, 155, 167, 169, 169, 184, 199, 156, 121, 167, 153, 139, 154, 140, 137, 168, 139, 154, 169, 155, 167, 169, 169, 184, 199, 156, 121, 167, 153, 139, 154, 140, 137, 168, 139, 154, 169, 155, 167, 169, 169, 184, 199, 156, },
{ 152, 139, 154, 154, 169, 155, 182, 154, 169, 184, 155, 141, 168, 214, 199, 170, 170, 171, 152, 139, 154, 154, 169, 155, 182, 154, 169, 184, 155, 141, 168, 214, 199, 170, 170, 171, 152, 139, 154, 154, 169, 155, 182, 154, 169, 184, 155, 141, 168, 214, 199, 170, 170, 171, },
}),
ContextSetCfg::addCtxSet
({
{ 137, 154, 154, 155, 155, 156, 124, 185, 156, 171, 142, 158, },
{ 136, 153, 139, 154, 125, 140, 122, 154, 184, 185, 171, 157, },
{ 167, 154, 169, 140, 155, 141, 153, 171, 185, 156, 171, 172, },
}),
#endif
};
#if JVET_K0072
const CtxSet ContextSetCfg::ParFlag[] =
{
ContextSetCfg::addCtxSet
({
{ 162, 134, 136, 167, 153, 138, 135, 167, 182, 168, 168, 150, 182, 153, 168, 110, 180, 168, 139, 168, 154, },
{ 133, 163, 151, 167, 138, 168, 149, 152, 153, 153, 124, 150, 153, 153, 168, 139, 166, 168, 168, 139, 139, },
{ 134, 120, 152, 123, 153, 153, 136, 123, 153, 168, 154, 152, 153, 153, 124, 139, 123, 168, 139, 154, 139, },
}),
ContextSetCfg::addCtxSet
({
{ 57, 192, 194, 225, 153, 139, 209, 168, 213, 123, 95, },
{ 147, 164, 137, 153, 124, 153, 210, 183, 183, 154, 139, },
{ 134, 121, 182, 183, 138, 183, 198, 154, 154, 124, 154, },
}),
};
const CtxSet ContextSetCfg::GtxFlag[] =
{
ContextSetCfg::addCtxSet
({
{ 59, 57, 59, 133, 164, 165, 117, 147, 134, 150, 137, 133, 163, 121, 166, 167, 163, 135, 136, 181, 139, },
{ 45, 57, 58, 44, 149, 91, 73, 89, 105, 91, 122, 74, 105, 121, 122, 138, 119, 106, 107, 152, 139, },
{ 135, 43, 119, 90, 76, 107, 74, 75, 106, 77, 93, 105, 91, 122, 93, 94, 150, 136, 123, 153, 125, },
}),
ContextSetCfg::addCtxSet
({
{ 133, 3, 14, 120, 135, 91, 179, 103, 194, 94, 111, },
{ 118, 102, 134, 135, 122, 123, 163, 120, 122, 153, 169, },
{ 195, 88, 74, 105, 152, 138, 120, 90, 107, 139, 184, },
}),
ContextSetCfg::addCtxSet
({
{ 3, 3, 103, 119, 91, 151, 3, 148, 194, 152, 138, 147, 164, 166, 167, 168, 133, 180, 196, 139, 169, },
{ 3, 3, 118, 120, 106, 152, 3, 119, 121, 122, 153, 118, 135, 166, 138, 139, 148, 151, 182, 168, 184, },
{ 132, 102, 104, 121, 92, 93, 104, 106, 122, 123, 94, 105, 137, 153, 139, 95, 121, 123, 139, 154, 126, },
}),
ContextSetCfg::addCtxSet
({
{ 3, 3, 176, 193, 137, 181, 161, 137, 183, 155, 111, },
{ 3, 3, 134, 137, 123, 124, 147, 167, 169, 199, 156, },
{ 147, 73, 164, 151, 107, 109, 120, 152, 140, 185, 111, },
}),
};
#endif
const CtxSet ContextSetCfg::LastX[] =
{
ContextSetCfg::addCtxSet
({
{ 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 126, 111, 111, 79, CNU, CNU, CNU, CNU, CNU, CNU, },
{ 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 111, 111, 95, 94, CNU, CNU, CNU, CNU, CNU, CNU, },
{ 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 143, 127, 111, 79, CNU, CNU, CNU, CNU, CNU, CNU, },
}),
ContextSetCfg::addCtxSet
({
{ 108, 123, 93, 154, },
{ 108, 123, 108, 154, },
{ 108, 123, 63, 154, },
}),
};
const CtxSet ContextSetCfg::LastY[] =
{
ContextSetCfg::addCtxSet
({
{ 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 126, 111, 111, 79, CNU, CNU, CNU, CNU, CNU, CNU, },
{ 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 111, 111, 95, 94, CNU, CNU, CNU, CNU, CNU, CNU, },
{ 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 143, 127, 111, 79, CNU, CNU, CNU, CNU, CNU, CNU, },
}),
ContextSetCfg::addCtxSet
({
{ 108, 123, 93, 154, },
{ 108, 123, 108, 154, },
{ 108, 123, 63, 154, },
}),
};
#if JVET_K0072
#else
const CtxSet ContextSetCfg::GreaterOneFlag[] =
{
ContextSetCfg::addCtxSet
({
{ 154, 196, 167, 167, },
{ 154, 196, 196, 167, },
{ 140, 92, 137, 138, },
}),
ContextSetCfg::addCtxSet
({
{ 154, 152, 167, 182, },
{ 154, 152, 167, 182, },
{ 140, 152, 138, 139, },
}),
ContextSetCfg::addCtxSet
({
{ 182, 134, 149, 136, },
{ 182, 134, 149, 136, },
{ 153, 74, 149, 92, },
}),
ContextSetCfg::addCtxSet
({
{ 153, 121, 136, 122, },
{ 153, 121, 136, 137, },
{ 139, 107, 122, 152, },
}),
ContextSetCfg::addCtxSet
({
{ 169, 208, 166, 167, },
{ 169, 194, 166, 167, },
{ 140, 179, 166, 182, },
}),
ContextSetCfg::addCtxSet
({
{ 154, 152, 167, 182, },
{ 154, 167, 137, 182, },
{ 140, 227, 122, 197, },
}),
ContextSetCfg::addCtxSet
({
{ 121, 135, 123, 124, 139, 125, 92, 124, 154, 125, 155, 138, 169, 155, 170, 156, },
{ 165, 75, 152, 153, 139, 154, 121, 138, 139, 154, 140, 167, 183, 169, 170, 156, },
{ 196, 105, 152, 153, 139, 154, 136, 138, 139, 169, 140, 196, 183, 169, 170, 171, },
}),
ContextSetCfg::addCtxSet
({
{ 166, 152, 140, 170, 171, 157, },
{ 193, 181, 169, 170, 171, 172, },
{ 195, 181, 169, 170, 156, 157, },
}),
};
const CtxSet ContextSetCfg::GreaterTwoFlag = ContextSetCfg::addCtxSet
({
{ 107, 167, 91, 107, 107, 167,},
{ 107, 167, 91, 122, 107, 167,},
{ 138, 153, 136, 167, 152, 152,},
});
#endif
const CtxSet ContextSetCfg::MVPIdx = ContextSetCfg::addCtxSet
({
{ 168,},
{ 168,},
{ CNU,},
});
const CtxSet ContextSetCfg::SaoMergeFlag = ContextSetCfg::addCtxSet
({
{ 153,},
{ 153,},
{ 153,},
});
const CtxSet ContextSetCfg::SaoTypeIdx = ContextSetCfg::addCtxSet
({
{ 160,},
{ 185,},
{ 200,},
});
#if JEM_TOOLS && !JVET_K0371_ALF
const CtxSet ContextSetCfg::AlfCUCtrlFlags = ContextSetCfg::addCtxSet
({
{ CNU, CNU, CNU,},
{ CNU, CNU, CNU,},
{ CNU, CNU, CNU,},
});
const CtxSet ContextSetCfg::AlfUvlcSCModel = ContextSetCfg::addCtxSet
({
{ 154, 140,},
{ 140, 110,},
{ 139, 139,},
});
#endif
const CtxSet ContextSetCfg::TransformSkipFlag = ContextSetCfg::addCtxSet
({
{ 139, 139,},
{ 139, 139,},
{ 139, 139,},
});
const CtxSet ContextSetCfg::TransquantBypassFlag = ContextSetCfg::addCtxSet
({
{ 154,},
{ 154,},
{ 154,},
});
#if JEM_TOOLS
const CtxSet ContextSetCfg::NSSTIdx = ContextSetCfg::addCtxSet
({
{ 107, 107, 107, 107, 107,},
{ 107, 107, 107, 107, 107,},
{ 139, 139, 139, 139, 139,},
});
#endif
const CtxSet ContextSetCfg::RdpcmFlag = ContextSetCfg::addCtxSet
({
{ 139, 139,},
{ 139, 139,},
{ CNU, CNU,},
});
const CtxSet ContextSetCfg::RdpcmDir = ContextSetCfg::addCtxSet
({
{ 139, 139,},
{ 139, 139,},
{ CNU, CNU,},
});
#if JEM_TOOLS || JVET_K1000_SIMPLIFIED_EMT
const CtxSet ContextSetCfg::EMTTuIndex = ContextSetCfg::addCtxSet
({
{ CNU, CNU, CNU, CNU,},
{ CNU, CNU, CNU, CNU,},
{ CNU, CNU, CNU, CNU,},
});
const CtxSet ContextSetCfg::EMTCuFlag = ContextSetCfg::addCtxSet
({
{ CNU, CNU, CNU, CNU, CNU, CNU,},
{ CNU, CNU, CNU, CNU, CNU, CNU,},
{ CNU, CNU, CNU, CNU, CNU, CNU,},
});
#endif
const CtxSet ContextSetCfg::CrossCompPred = ContextSetCfg::addCtxSet
({
{ 154, 154, 154, 154, 154, 154, 154, 154, 154, 154,},
{ 154, 154, 154, 154, 154, 154, 154, 154, 154, 154,},
{ 154, 154, 154, 154, 154, 154, 154, 154, 154, 154,},
});
const CtxSet ContextSetCfg::ChromaQpAdjFlag = ContextSetCfg::addCtxSet
({
{ 154,},
{ 154,},
{ 154,},
});
const CtxSet ContextSetCfg::ChromaQpAdjIdc = ContextSetCfg::addCtxSet
({
{ 154,},
{ 154,},
{ 154,},
});
#if JVET_K0357_AMVR
const CtxSet ContextSetCfg::ImvFlag = ContextSetCfg::addCtxSet
({
{ 197, 185, 201, 185,},
{ 197, 185, 201, 185,},
{ CNU, CNU, CNU, CNU,},
});
#endif
#if JEM_TOOLS
const CtxSet ContextSetCfg::LICFlag = ContextSetCfg::addCtxSet
({
{ 154,},
{ 154,},
{ CNU,},
});
const CtxSet ContextSetCfg::ObmcFlag = ContextSetCfg::addCtxSet
({
{ 201,},
{ 201,},
{ CNU,},
});
const CtxSet ContextSetCfg::FrucFlag = ContextSetCfg::addCtxSet
({
{ 197, 185, 201,},
{ 197, 185, 201,},
{ CNU, CNU, CNU,},
});
const CtxSet ContextSetCfg::FrucMode = ContextSetCfg::addCtxSet
({
{ 197, 185, 201,},
{ 197, 185, 201,},
{ CNU, CNU, CNU,},
});
#endif
#if JVET_K0371_ALF
const CtxSet ContextSetCfg::ctbAlfFlag =
{
ContextSetCfg::addCtxSet
( {
{ 100, 100, 100, 100, 100, 100, 100, 100, 100 },
{ 153, 153, 153, 153, 153, 153, 153, 153, 153 },
{ 200, 200, 200, 200, 200, 200, 200, 200, 200 },
} )
};
#endif
const unsigned ContextSetCfg::NumberOfContexts = (unsigned)ContextSetCfg::sm_InitTables[0].size();
// combined sets
const CtxSet ContextSetCfg::Sao = { ContextSetCfg::SaoMergeFlag, ContextSetCfg::SaoTypeIdx };
template <class BinProbModel>
CtxStore<BinProbModel>::CtxStore()
: m_CtxBuffer ()
, m_Ctx ( nullptr )
{}
template <class BinProbModel>
CtxStore<BinProbModel>::CtxStore( bool dummy )
: m_CtxBuffer ( ContextSetCfg::NumberOfContexts )
, m_Ctx ( m_CtxBuffer.data() )
{}
template <class BinProbModel>
CtxStore<BinProbModel>::CtxStore( const CtxStore<BinProbModel>& ctxStore )
: m_CtxBuffer ( ctxStore.m_CtxBuffer )
, m_Ctx ( m_CtxBuffer.data() )
{}
template <class BinProbModel>
void CtxStore<BinProbModel>::init( int qp, int initId )
{
const std::vector<uint8_t>& initTable = ContextSetCfg::getInitTable( initId );
CHECK( m_CtxBuffer.size() != initTable.size(),
"Size of init table (" << initTable.size() << ") does not match size of context buffer (" << m_CtxBuffer.size() << ")." );
int clippedQP = Clip3( 0, MAX_QP, qp );
for( std::size_t k = 0; k < m_CtxBuffer.size(); k++ )
{
m_CtxBuffer[k].init( clippedQP, initTable[k] );
}
}
template <class BinProbModel>
void CtxStore<BinProbModel>::setWinSizes( const std::vector<uint8_t>& log2WindowSizes )
{
CHECK( m_CtxBuffer.size() != log2WindowSizes.size(),
"Size of window size table (" << log2WindowSizes.size() << ") does not match size of context buffer (" << m_CtxBuffer.size() << ")." );
for( std::size_t k = 0; k < m_CtxBuffer.size(); k++ )
{
m_CtxBuffer[k].setLog2WindowSize( log2WindowSizes[k] );
}
}
template <class BinProbModel>
void CtxStore<BinProbModel>::loadPStates( const std::vector<uint16_t>& probStates )
{
CHECK( m_CtxBuffer.size() != probStates.size(),
"Size of prob states table (" << probStates.size() << ") does not match size of context buffer (" << m_CtxBuffer.size() << ")." );
for( std::size_t k = 0; k < m_CtxBuffer.size(); k++ )
{
m_CtxBuffer[k].setState( probStates[k] );
}
}
template <class BinProbModel>
void CtxStore<BinProbModel>::savePStates( std::vector<uint16_t>& probStates ) const
{
probStates.resize( m_CtxBuffer.size(), uint16_t(0) );
for( std::size_t k = 0; k < m_CtxBuffer.size(); k++ )
{
probStates[k] = m_CtxBuffer[k].getState();
}
}
template class CtxStore<BinProbModel_Std>;
#if JEM_TOOLS
template class CtxStore<BinProbModel_JMP>;
template class CtxStore<BinProbModel_JAW>;
template class CtxStore<BinProbModel_JMPAW>;
#endif
Ctx::Ctx() : m_BPMType( BPM_Undefined ) {}
Ctx::Ctx( const BinProbModel_Std* dummy ) : m_BPMType( BPM_Std ), m_CtxStore_Std ( true ) {}
#if JEM_TOOLS
Ctx::Ctx( const BinProbModel_JMP* dummy ) : m_BPMType( BPM_JMP ), m_CtxStore_JMP ( true ) {}
Ctx::Ctx( const BinProbModel_JAW* dummy ) : m_BPMType( BPM_JAW ), m_CtxStore_JAW ( true ) {}
Ctx::Ctx( const BinProbModel_JMPAW* dummy ) : m_BPMType( BPM_JMPAW ), m_CtxStore_JMPAW( true ) {}
#endif
Ctx::Ctx( const Ctx& ctx )
: m_BPMType ( ctx.m_BPMType )
, m_CtxStore_Std ( ctx.m_CtxStore_Std )
#if JEM_TOOLS
, m_CtxStore_JMP ( ctx.m_CtxStore_JMP )
, m_CtxStore_JAW ( ctx.m_CtxStore_JAW )
, m_CtxStore_JMPAW ( ctx.m_CtxStore_JMPAW )
#endif
{
::memcpy( m_GRAdaptStats, ctx.m_GRAdaptStats, sizeof( unsigned ) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS );
}
#if JEM_TOOLS
CtxWSizeStore::CtxWSizeStore()
: m_isInitialized ( false )
, m_readWriteBuffer ()
, m_codeId2ctxId ()
{
}
void CtxWSizeStore::checkInit( const SPS* sps )
{
if( !m_isInitialized )
{
#if JEM_ADAPTIVE_WINDOW_MECHANISM
const int readWriteBufferSize = 384;
#else
const int readWriteBufferSize = Ctx::NumberOfContexts;
#endif
m_readWriteBuffer.resize( readWriteBufferSize, 0 );
xInitMappingTable ( sps );
xSetAllInvalid ();
m_isInitialized = true;
}
}
void CtxWSizeStore::updateState( const Slice* slice, const bool enc )
{
#if JEM_ADAPTIVE_WINDOW_MECHANISM
#else // bug fix : corrected handling of random access points
if ( slice->getPendingRasInit() )
{
xSetAllInvalid();
}
CHECK( slice->getRapPicFlag() && !enc && slice->getCabacWinUpdateMode() == 2, "reusing of cabac window sizes not possible at random access point" );
#endif
if( !enc && slice->getCabacWinUpdateMode() == 1 )
{
xApplyReadWriteBuffer( slice );
}
}
bool CtxWSizeStore::validWinSizes( const Slice* slice ) const
{
return m_winSizes[slice->getSliceType()][slice->getSliceQpBase()].isValid();
}
const std::vector<uint8_t>* CtxWSizeStore::getWinSizes( const Slice* slice ) const
{
if( !slice->getCabacWinUpdateMode() )
{
return 0;
}
const CtxWSizeSet& set = m_winSizes[slice->getSliceType()][slice->getSliceQpBase()];
CHECK( !set.isValid(), "win size buffer is invalid" );
return &set.getWinSizeBuffer();
}
void CtxWSizeStore::xSetAllInvalid()
{
for( unsigned sliceType = 0; sliceType < NUMBER_OF_SLICE_TYPES; sliceType++ )
{
CtxWSizeSet* winSizes = m_winSizes[sliceType];
for( unsigned QP = 0; QP <= MAX_QP; QP++ )
{
winSizes[QP].setInvalid();
}
}
}
void CtxWSizeStore::xApplyReadWriteBuffer( const Slice* slice )
{
const uint8_t defWinSize = Ctx::getDefaultWindowSize( slice->getSPS()->getSpsNext().getCABACEngineMode() );
const uint8_t minWinSize = 4;
const uint8_t threshold = uint8_t( defWinSize - minWinSize + 1 );
CtxWSizeSet& set = m_winSizes[slice->getSliceType()][slice->getSliceQpBase()];
std::vector<uint8_t>& winBuffer = set.getWinSizeBuffer();
winBuffer.resize( 0 );
winBuffer.resize( Ctx::NumberOfContexts, 0 );
for( std::size_t readId = 0; readId < m_readWriteBuffer.size(); readId++ )
{
uint8_t level = m_readWriteBuffer[readId];
if( level )
{
uint8_t winSize = minWinSize + ( level < threshold ? level - 1 : level );
winBuffer[m_codeId2ctxId[readId]] = winSize;
}
}
set.setValidOnly();
}
void CtxWSizeStore::xSetReadWriteBuffer( const Slice* slice )
{
const uint8_t defWinSize = Ctx::getDefaultWindowSize( slice->getSPS()->getSpsNext().getCABACEngineMode() );
const uint8_t minWinSize = 4;
CtxWSizeSet& set = m_winSizes[slice->getSliceType()][slice->getSliceQpBase()];
CHECK( !set.isValid(), "requested adap. window statistics are invalid" );
std::vector<uint8_t>& winBuffer = set.getWinSizeBuffer();
for( std::size_t codeId = 0; codeId < m_readWriteBuffer.size(); codeId++ )
{
uint8_t level = 0;
int ctxId = m_codeId2ctxId[codeId];
if( ctxId >= 0 )
{
uint8_t winSize = winBuffer[ctxId];
if( winSize != defWinSize )
{
level = 1 + winSize - minWinSize - ( winSize < defWinSize ? 0 : 1 );
}
}
m_readWriteBuffer[codeId] = level;
}
}
void addCtxSetToMapping( std::vector<int>& mapping, const CtxSet& ctxSet, unsigned startId, unsigned numCtx )
{
int ctxOffset = ctxSet(startId);
int numActualCtx = std::min<int>( (int)numCtx, (int)ctxSet.Size );
for( int n = 0; n < numActualCtx; n++ )
{
mapping.push_back( ctxOffset + n );
}
for( int n = numActualCtx; n < (int)numCtx; n++ )
{
mapping.push_back( -1 );
}
}
void addDummySetToMapping( std::vector<int>& mapping, unsigned numCtx )
{
for( int n = 0; n < (int)numCtx; n++ )
{
mapping.push_back( -1 );
}
}
void CtxWSizeStore::xInitMappingTable( const SPS* sps )
{
#if JEM_ADAPTIVE_WINDOW_MECHANISM
m_codeId2ctxId.reserve( std::max<std::size_t>( m_readWriteBuffer.size(), std::size_t(Ctx::NumberOfContexts) ) );
const SPSNext& spsNext = sps->getSpsNext();
unsigned numCtxSplitFlag = ( spsNext.getUseLargeCTU() ? 5 : 3 ); // hard-wired in JEM
unsigned numCtxMergeIdx = ( true /* COM16_C806_GEN_MRG_IMPROVEMENT */ ? 5 : 1 );
#if INTRA67_3MPM
unsigned numCtxIPredLuma = 1;
#else
unsigned numCtxIPredLuma = ( spsNext.getUseIntra65Ang() ? ( false /*JVET_B0051_NON_MPM_MODE */ ? 12 : 9 ) : 1 ); // hard-wired in JEM
#endif
unsigned numCtxIPredChroma = ( true /* JVET_E0077_ENHANCED_LM */ ? 8 : 2 ) + ( spsNext.getUseMDMS() ? 4 : 0 );
unsigned numCtxTransSubdiv = ( spsNext.getUseLargeCTU() || spsNext.getUseQTBT() ? 4 : 3 ); // hard-wired in JEM
unsigned numCtxLastXY = ( spsNext.getUseLargeCTU() || spsNext.getUseQTBT() ? 25 : 15 ); // hard-wired in JEM
unsigned numCtxEmtCUFlag = ( spsNext.getUseLargeCTU() || spsNext.getUseQTBT() ? 6 : 4 ); // hard-wired in JEM
#if JVET_K0357_AMVR
unsigned numImvCtx = ( spsNext.getImvMode() > 1 ? 4 : 3 );
#endif
#if JVET_K0248_GBI
unsigned numGBiCtx = ( GBI_NUM + 2 );
#endif
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SplitFlag, 0, numCtxSplitFlag );
if( spsNext.getUseQTBT() ) // hard-wired in JEM
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::BTSplitFlag, 0, 6 );
}
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SkipFlag, 0, 3 );
if( false /* VCEG_AZ05_INTRA_MPI */ )
{
// dummy placeholder
}
if( true /* COM16_C1046_PDPC_INTRA */ )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::PdpcFlag, 0, 2 );
}
if( true /* VCEG_AZ05_ROT_TR || COM16_C1044_NSST */ )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::NSSTIdx, 0, 7 );
}
addCtxSetToMapping ( m_codeId2ctxId, Ctx::MergeFlag, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::MergeIdx, 0, numCtxMergeIdx );
#if JEM_TOOLS
if( true /* VCEG_AZ07_FRUC_MERGE */ )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::FrucFlag, 0, 3 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::FrucMode, 0, 3 );
}
#endif
addCtxSetToMapping ( m_codeId2ctxId, Ctx::PartSize, 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::PredMode, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::IPredMode[0], 0, numCtxIPredLuma );
if( spsNext.getUseMDMS() ) // hard wired in JEM
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::IPredMode[1], 0, numCtxIPredChroma );
}
else
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::IPredMode[1], 1, numCtxIPredChroma );
}
addCtxSetToMapping ( m_codeId2ctxId, Ctx::DeltaQP, 0, 3 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::InterDir, 0, 5 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::RefPic, 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::Mvd, 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::QtCbf[0], 0, 5 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::QtCbf[1], 0, 5 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::TransSubdivFlag, 0, numCtxTransSubdiv );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::QtRootCbf, 0, 1 );
#if JVET_K0072
#else
if( spsNext.getAltResiCompId() == 0 ) // hard-wired in JEM
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigCoeffGroup[0], 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigCoeffGroup[1], 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigFlag[0], 0, 28 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigFlag[1], 0, 16 );
}
else if( spsNext.getAltResiCompId() == 1 ) // hard-wired in JEM
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigCoeffGroup[2], 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigCoeffGroup[3], 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigFlag[2], 0, 54 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SigFlag[3], 0, 12 );
}
#endif
addCtxSetToMapping ( m_codeId2ctxId, Ctx::LastX[0], 0, numCtxLastXY );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::LastX[1], 0, numCtxLastXY );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::LastY[0], 0, numCtxLastXY );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::LastY[1], 0, numCtxLastXY );
#if JVET_K0072
#else
if( spsNext.getAltResiCompId() == 0 ) // hard-wired in JEM
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[0], 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[1], 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[2], 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[3], 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[4], 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[5], 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterTwoFlag, 0, 6 );
}
else if( spsNext.getAltResiCompId() == 1 ) // hard-wired in JEM
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[6], 0, 16 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GreaterOneFlag[7], 0, 6 );
}
#endif
addCtxSetToMapping ( m_codeId2ctxId, Ctx::MVPIdx, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SaoMergeFlag, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::SaoTypeIdx, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::TransformSkipFlag, 0, 2 );
if( false /* VCEG_AZ08_KLT_COMMON */ )
{
// dummy placeholder -- MTT contexts, not used in JEM compatibility modus
}
addCtxSetToMapping ( m_codeId2ctxId, Ctx::TransquantBypassFlag, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::RdpcmFlag, 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::RdpcmDir, 0, 2 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::CrossCompPred, 0, 10 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::ChromaQpAdjFlag, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::ChromaQpAdjIdc, 0, 1 );
#if JEM_TOOLS
if( true /* COM16_C806_OBMC */ )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::ObmcFlag, 0, 1 );
}
#if JVET_K0357_AMVR
if( true /* VCEG_AZ07_IMV */ )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::ImvFlag, 0, numImvCtx );
}
#endif
if( spsNext.getLICEnabled() ) // hard-wired in JEM
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::LICFlag, 0, 1 );
}
#endif
#if JVET_K0248_GBI
if (true)
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::GBiIdx, 0, numGBiCtx );
}
#endif
#if !JVET_K0371_ALF
if( true /* ALF_HM3_REFACTOR */ )
{
if( spsNext.getGALFEnabled() )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::AlfCUCtrlFlags, 0, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::AlfUvlcSCModel, 0, 2 );
}
else
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::AlfCUCtrlFlags, 0, 3 );
addDummySetToMapping( m_codeId2ctxId, 1 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::AlfUvlcSCModel, 0, 2 );
addDummySetToMapping( m_codeId2ctxId, 3 );
}
}
#endif
if( true /* COM16_C806_EMT */ )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::EMTTuIndex, 0, 4 );
addCtxSetToMapping ( m_codeId2ctxId, Ctx::EMTCuFlag, 0, numCtxEmtCUFlag );
}
#if JEM_TOOLS
if( true /* COM16_C1016_AFFINE */ )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::AffineFlag, 0, 3 );
}
#endif
if( spsNext.getUseQTBT() )
{
addCtxSetToMapping ( m_codeId2ctxId, Ctx::BTSplitFlag, 6, Ctx::BTSplitFlag.Size-6 );
}
m_codeId2ctxId.resize ( m_readWriteBuffer.size(), -1 );
#else
m_codeId2ctxId.resize ( Ctx::NumberOfContexts );
for( std::size_t n = 0; n < Ctx::NumberOfContexts; n++ )
{
m_codeId2ctxId[n] = (int)n;
}
#endif
}
#endif
|
// Copyright © 2011, Université catholique de Louvain
// 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.
//
// 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.
#ifndef MOZART_REFERENCE_H
#define MOZART_REFERENCE_H
#include "mozartcore.hh"
#ifndef MOZART_GENERATOR
namespace mozart {
///////////////
// Reference //
///////////////
#include "Reference-implem.hh"
}
#endif // MOZART_GENERATOR
#endif // MOZART_REFERENCE_H
|
/* Copyright 2017 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 <algorithm>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "tensorflow/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"
namespace toco {
namespace {
void RenameArray(Model* model, const string& oldname,
const string& desired_newname) {
const string& newname = AvailableArrayName(*model, desired_newname);
auto& arrays = model->GetMutableArrayMap();
arrays[newname] = std::move(arrays[oldname]);
arrays.erase(oldname);
for (const auto& op : model->operators) {
for (string& input : op->inputs) {
if (input == oldname) {
input = newname;
}
}
for (string& output : op->outputs) {
if (output == oldname) {
output = newname;
}
}
}
}
} // namespace
// Reorder the elements of an input_array according to the input_axes_order and
// output_axes_order. Then adjust the shapes of the input and output arrays
// accordingly. Note that input_array must have a buffer (that is, it is a
// constant array).
template <typename T, ArrayDataType DataType>
void ReorderAxes(AxesOrder input_axes_order, AxesOrder output_axes_order,
const Array& input_array, Array* output_array) {
DCHECK(input_array.buffer->type == DataType);
DCHECK(!output_array->buffer);
const auto& input_data = input_array.GetBuffer<DataType>().data;
auto& output_data = output_array->GetMutableBuffer<DataType>().data;
output_data.resize(RequiredBufferSizeForShape(output_array->shape()));
// TODO(b/62904716) Shapes should be used directly.
Shape input_shape = input_array.shape();
Shape output_shape = output_array->shape();
if (AxesCount(input_axes_order) == 2) {
UnextendShape(&input_shape, 2);
UnextendShape(&output_shape, 2);
}
ShuffleArray(input_shape, input_axes_order, output_axes_order, output_shape,
input_data.data(), output_data.data());
if (input_array.minmax) {
output_array->GetOrCreateMinMax() = input_array.GetMinMax();
}
if (input_array.narrow_range) {
output_array->narrow_range = true;
}
}
::tensorflow::Status ResolveReorderAxes::Run(Model* model, std::size_t op_index,
bool* modified) {
*modified = false;
auto it = model->operators.begin() + op_index;
auto* op = it->get();
if (op->type != OperatorType::kReorderAxes) {
return ::tensorflow::Status::OK();
}
auto* reorder_op = static_cast<ReorderAxesOperator*>(op);
// Intentionally copies, not references.
const string input_array_name = reorder_op->inputs[0];
const string output_array_name = reorder_op->outputs[0];
auto& input_array = model->GetArray(input_array_name);
auto& output_array = model->GetArray(output_array_name);
if (!input_array.buffer) {
return ::tensorflow::Status::OK();
}
// Yield until output dims have been resolved.
if (!output_array.has_shape()) {
return ::tensorflow::Status::OK();
}
// Reorder the input array dims and buffer data
if (input_array.buffer->type == ArrayDataType::kFloat) {
ReorderAxes<float, ArrayDataType::kFloat>(reorder_op->input_axes_order,
reorder_op->output_axes_order,
input_array, &output_array);
} else if (input_array.buffer->type == ArrayDataType::kUint8) {
// TODO(benoitjacob): This path seems unused.
// ReorderAxes is only used when importing from
// TensorFlow GraphDef, which does not support quantized nodes.
ReorderAxes<uint8, ArrayDataType::kUint8>(reorder_op->input_axes_order,
reorder_op->output_axes_order,
input_array, &output_array);
} else {
LOG(FATAL) << "Cannot ReorderAxes unless input buffer is float or uint8.";
}
AddMessageF("Reordered axes for array %s", input_array_name);
DeleteOpAndArraysIfUnused(model, op);
RenameArray(model, output_array_name, input_array_name);
*modified = true;
return ::tensorflow::Status::OK();
}
} // namespace toco
|
/* Copyright 2017 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/compiler/xla/client/client.h"
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/debug_options_flags.h"
#include "tensorflow/compiler/xla/execution_options_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace xla {
Client::Client(ServiceInterface* stub) : stub_(stub) {}
Client::~Client() = default;
StatusOr<Literal> Client::Transfer(const GlobalData& data,
const Shape* shape_with_layout) {
TransferToClientRequest request;
*request.mutable_data() = data.handle();
if (shape_with_layout != nullptr) {
*request.mutable_shape_with_layout() = shape_with_layout->ToProto();
}
TransferToClientResponse response;
VLOG(1) << "making transfer request";
VLOG(3) << "TransferToClientRequest: {" << request.DebugString() << "}";
Status s = stub_->TransferToClient(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
VLOG(3) << "TransferToClientResponse: {" << response.DebugString() << "}";
if (!response.has_literal()) {
return FailedPrecondition(
"server provided response without a literal in "
"TransferToClient request");
}
return Literal::CreateFromProto(*response.mutable_literal());
}
StatusOr<std::unique_ptr<GlobalData>> Client::TransferToServer(
const LiteralSlice& literal, const DeviceHandle* device_handle) {
TransferToServerRequest request;
*request.mutable_literal() = literal.ToProto();
if (device_handle) {
*request.mutable_device_handle() = *device_handle;
}
TransferToServerResponse response;
VLOG(1) << "making transfer to server request";
VLOG(3) << "TransferToServerRequest: {" << request.DebugString() << "}";
Status s = stub_->TransferToServer(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
VLOG(3) << "TransferToServerResponse: {" << response.DebugString() << "}";
if (!response.has_data()) {
return FailedPrecondition(
"server provided response without a data handle in "
"TransferToServer request");
}
return absl::make_unique<GlobalData>(stub_, response.data());
}
Status Client::TransferToInfeed(const LiteralSlice& literal, int64 replica_id,
const DeviceHandle* device_handle) {
TransferToInfeedRequest request;
*request.mutable_literal() = literal.ToProto();
if (device_handle) {
*request.mutable_device_handle() = *device_handle;
}
request.set_replica_id(replica_id);
TransferToInfeedResponse response;
VLOG(1) << "making transfer to infeed request";
VLOG(3) << "TransferToInfeedRequest: {" << request.DebugString() << "}";
Status s = stub_->TransferToInfeed(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
VLOG(3) << "TransferToInfeedResponse: {" << response.DebugString() << "}";
return Status::OK();
}
StatusOr<Literal> Client::TransferFromOutfeed(
const Shape* shape_with_layout, int64 replica_id,
const DeviceHandle* device_handle) {
TransferFromOutfeedRequest request;
if (device_handle) {
*request.mutable_device_handle() = *device_handle;
}
request.set_replica_id(replica_id);
if (shape_with_layout != nullptr) {
*request.mutable_shape_with_layout() = shape_with_layout->ToProto();
}
TransferFromOutfeedResponse response;
VLOG(1) << "making transfer from outfeed request";
VLOG(3) << "TransferFromOutfeedRequest: {" << request.DebugString() << "}";
Status s = stub_->TransferFromOutfeed(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
VLOG(3) << "TransferFromOutfeedResponse: {" << response.DebugString() << "}";
if (!response.has_literal()) {
return FailedPrecondition(
"server provided response without a literal in "
"TransferToClient request");
}
return Literal::CreateFromProto(response.literal());
}
Status Client::ResetDevice() {
ResetDeviceRequest request;
ResetDeviceResponse response;
VLOG(1) << "making reset device request";
VLOG(3) << "ResetDeviceRequest: {" << request.DebugString() << "}";
Status s = stub_->ResetDevice(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
VLOG(3) << "ResetDeviceResponse: {" << response.DebugString() << "}";
return Status::OK();
}
StatusOr<Literal> Client::ExecuteAndTransfer(
const XlaComputation& computation, absl::Span<GlobalData* const> arguments,
const ExecutionOptions* execution_options,
ExecutionProfile* execution_profile) {
TF_ASSIGN_OR_RETURN(
std::unique_ptr<GlobalData> data,
Execute(computation, arguments, execution_options, execution_profile));
absl::optional<Shape> shape_with_output_layout;
if (execution_options && execution_options->has_shape_with_output_layout()) {
shape_with_output_layout =
Shape(execution_options->shape_with_output_layout());
}
return Transfer(*data, shape_with_output_layout.has_value()
? &(*shape_with_output_layout)
: nullptr);
}
StatusOr<Literal> Client::ComputeConstant(const XlaComputation& computation,
const Layout* output_layout) const {
ComputeConstantGraphRequest request;
*request.mutable_computation() = computation.proto();
if (output_layout != nullptr) {
*request.mutable_output_layout() = output_layout->ToProto();
}
ComputeConstantResponse response;
VLOG(2) << "making compute-constant-graph request";
Status s = stub_->ComputeConstantGraph(&request, &response);
VLOG(2) << "done with request";
if (!s.ok()) {
return s;
}
VLOG(3) << "ComputeConstant: {" << response.DebugString() << "}";
if (!response.has_literal()) {
return InternalError(
"no computed literal in the provided response in ComputeConstantGraph "
"request");
}
return Literal::CreateFromProto(response.literal());
}
StatusOr<XlaComputation> Client::LoadSnapshot(const HloSnapshot& module) {
TF_RET_CHECK(module.has_hlo() && module.hlo().has_hlo_module());
return XlaComputation(module.hlo().hlo_module());
}
StatusOr<ExecutionHandle> Client::Compile(
const XlaComputation& computation, absl::Span<const Shape> argument_shapes,
const ExecutionOptions* execution_options) {
CompileRequest request;
*request.mutable_computation() = computation.proto();
if (execution_options == nullptr) {
*request.mutable_execution_options() = CreateDefaultExecutionOptions();
} else {
*request.mutable_execution_options() = *execution_options;
}
if (request.execution_options().device_handles_size() > 1) {
return InvalidArgument(
"Compiling with multiple device handles is not supported. Use "
"'Execute' instead.");
}
// The argument shapes affect how the computation is compiled.
for (const auto& arg_shape : argument_shapes) {
*request.add_input_shape_with_layout() = arg_shape.ToProto();
}
CompileResponse response;
VLOG(1) << "making compile request: " << request.ShortDebugString();
Status s = stub_->Compile(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
TF_RET_CHECK(response.has_handle());
return response.handle();
}
StatusOr<std::unique_ptr<GlobalData>> Client::Execute(
const ExecutionHandle& handle, absl::Span<GlobalData* const> arguments,
ExecutionProfile* execution_profile) {
ExecuteRequest request;
*request.mutable_handle() = handle;
for (GlobalData* argument : arguments) {
CHECK(argument != nullptr) << "Argument pointers must not be null.";
*request.add_arguments() = argument->handle();
}
ExecuteResponse response;
VLOG(1) << "making execute request: " << request.ShortDebugString();
Status s = stub_->Execute(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
if (execution_profile != nullptr) {
*execution_profile = response.profile();
}
return absl::make_unique<GlobalData>(stub_, response.output());
}
StatusOr<std::unique_ptr<GlobalData>> Client::Execute(
const XlaComputation& computation, absl::Span<GlobalData* const> arguments,
const ExecutionOptions* execution_options,
ExecutionProfile* execution_profile) {
// Create an ExecutionOptions if necessary, or set its DeviceHandles.
absl::optional<ExecutionOptions> options_storage;
if (!execution_options || execution_options->device_handles().empty()) {
if (execution_options) {
options_storage.emplace(*execution_options);
} else {
options_storage.emplace(CreateDefaultExecutionOptions());
}
execution_options = &*options_storage;
TF_ASSIGN_OR_RETURN(auto device_handles,
GetDeviceHandles(/*device_count=*/1));
TF_RET_CHECK(!device_handles.empty());
*options_storage->add_device_handles() = std::move(device_handles[0]);
}
std::vector<XlaComputationInstance> computation_instances = {
XlaComputationInstance{
computation,
std::vector<GlobalData*>(arguments.begin(), arguments.end()),
*execution_options, execution_profile}};
// Instead of invoking Compile() and Execute(), invoke
// Service::ExecuteParallel() to execute our one computation. Compile()
// caches the executable forever, which isn't what we want.
VLOG(1) << "Making ExecuteParallel request: "
<< execution_options->DebugString();
TF_ASSIGN_OR_RETURN(auto results, ExecuteParallel(computation_instances));
VLOG(1) << "ExecuteParallel request done.";
// The result selection is a bit hacky, but better than assuming it is
// device 0.
//
// TODO(b/118493728): Allow Execute to return one result per computation.
for (int64 i = 0; i < results.size(); i++) {
TF_ASSIGN_OR_RETURN(const Shape& shape, GetShape(*results[i]));
if (!ShapeUtil::IsEmptyTuple(shape)) {
VLOG(3) << "Fetching result from device " << i << ": "
<< ShapeUtil::HumanString(shape);
return std::move(results[i]);
}
}
TF_RET_CHECK(!results.empty());
VLOG(1) << "Defaulting to device 0 result";
return std::move(results[0]);
}
StatusOr<std::vector<std::unique_ptr<GlobalData>>> Client::ExecuteParallel(
absl::Span<const XlaComputationInstance> computations) {
ExecuteGraphParallelRequest request;
for (const XlaComputationInstance& computation : computations) {
ExecuteGraphRequest single_request;
*single_request.mutable_computation() = computation.computation.proto();
for (GlobalData* argument : computation.arguments) {
*single_request.add_arguments() = argument->handle();
}
*single_request.mutable_execution_options() = computation.execution_options;
*request.add_requests() = single_request;
}
ExecuteParallelResponse response;
VLOG(1) << "making execute-graph-parallel request: "
<< request.ShortDebugString();
Status s = stub_->ExecuteGraphParallel(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
std::vector<std::unique_ptr<GlobalData>> outputs;
for (size_t i = 0; i < response.responses_size(); ++i) {
outputs.push_back(
absl::make_unique<GlobalData>(stub_, response.responses(i).output()));
if (i < computations.size() &&
computations[i].execution_profile != nullptr) {
*computations[i].execution_profile = response.responses(i).profile();
}
}
return std::move(outputs);
}
StatusOr<std::vector<DeviceHandle>> Client::GetDeviceHandles(
int64 device_count) {
if (device_count < 1) {
return InvalidArgument("device_count must be greater than 0");
}
GetDeviceHandlesRequest request;
request.set_device_count(device_count);
GetDeviceHandlesResponse response;
VLOG(1) << "making get device request: " << request.ShortDebugString();
Status s = stub_->GetDeviceHandles(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
std::vector<DeviceHandle> device_handles;
for (const DeviceHandle& device_handle : response.device_handles()) {
device_handles.push_back(device_handle);
}
return device_handles;
}
Status Client::Unregister(const GlobalData& data) {
UnregisterRequest request;
*request.add_data() = data.handle();
UnregisterResponse response;
VLOG(1) << "making unregister request";
Status s = stub_->Unregister(&request, &response);
VLOG(1) << "done with request";
return s;
}
StatusOr<std::vector<std::unique_ptr<GlobalData>>> Client::DeconstructTuple(
const GlobalData& data) {
DeconstructTupleRequest request;
*request.mutable_tuple_handle() = data.handle();
DeconstructTupleResponse response;
VLOG(1) << "making DestructTuple request";
Status s = stub_->DeconstructTuple(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
std::vector<std::unique_ptr<GlobalData>> handles;
for (auto& handle : response.element_handles()) {
handles.push_back(absl::make_unique<GlobalData>(stub_, handle));
}
return std::move(handles);
}
StatusOr<ComputationStats> Client::GetComputationStats(
const XlaComputation& computation,
const DebugOptions& debug_options) const {
ComputationGraphStatsRequest request;
// TODO(b/74197823): Find a way to avoid the copy of the hlo proto.
*request.mutable_computation() = computation.proto();
*request.mutable_debug_options() = debug_options;
ComputationStatsResponse response;
VLOG(1) << "making computation graph stats request";
Status s = stub_->GetComputationGraphStats(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
CHECK(response.has_stats());
return response.stats();
}
StatusOr<std::unique_ptr<ProgramShape>> Client::GetComputationShape(
const XlaComputation& computation) {
TF_ASSIGN_OR_RETURN(const auto& result, computation.GetProgramShape());
return absl::make_unique<ProgramShape>(result);
}
StatusOr<Shape> Client::GetShape(const GlobalData& data) {
GetShapeRequest request;
*request.mutable_data() = data.handle();
GetShapeResponse response;
VLOG(1) << "making get shape request";
Status s = stub_->GetShape(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
return Shape(response.shape());
}
StatusOr<string> Client::ExecutionStatsAsString(
const XlaComputation& computation, const ExecutionProfile& profile) {
TF_ASSIGN_OR_RETURN(
auto computation_stats,
GetComputationStats(computation, GetDebugOptionsFromFlags()));
int64 total_flops =
computation_stats.flop_count() + computation_stats.transcendental_count();
if (profile.compute_time_ns() > 0) {
int64 nanoseconds = profile.compute_time_ns();
int64 cycle_count = profile.compute_cycle_count();
double gflops = total_flops / nanoseconds;
return absl::StrCat(
"[Execution Statistics] flop count: ", computation_stats.flop_count(),
", transcendental count: ", computation_stats.transcendental_count(),
", compute execution time: ", nanoseconds, " nsec",
", compute cycles: ", cycle_count, ", performance: ", gflops,
"gflop/s");
}
return string("[Execution Statistics] not available.");
}
StatusOr<ChannelHandle> Client::CreateChannelHandleByType(
ChannelHandle::ChannelType type) {
CreateChannelHandleRequest request;
request.set_channel_type(type);
CreateChannelHandleResponse response;
VLOG(1) << "making create channel handle request";
Status s = stub_->CreateChannelHandle(&request, &response);
VLOG(1) << "done with request";
if (!s.ok()) {
return s;
}
return response.channel();
}
StatusOr<ChannelHandle> Client::CreateChannelHandle() {
return CreateChannelHandleByType(ChannelHandle::DEVICE_TO_DEVICE);
}
StatusOr<ChannelHandle> Client::CreateHostToDeviceChannelHandle() {
return CreateChannelHandleByType(ChannelHandle::HOST_TO_DEVICE);
}
StatusOr<ChannelHandle> Client::CreateDeviceToHostChannelHandle() {
return CreateChannelHandleByType(ChannelHandle::DEVICE_TO_HOST);
}
} // namespace xla
|
class Solution {
public:
/**
* @param matrix: the given matrix
* @return: The list of grid coordinates
*/
vector<vector<int>> pacificAtlantic(vector<vector<int>> &matrix) {
// write your code here
int m = matrix.size();
if (m == 0) {
return {};
}
int n = matrix[0].size();
vector<vector<int>> visitedTimes(m, vector<int>(n));
bfs(matrix, visitedTimes, true);
bfs(matrix, visitedTimes, false);
vector<vector<int>> result;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (visitedTimes[i][j] == 2) {
result.push_back({i, j});
}
}
}
return result;
}
private:
void bfs(vector<vector<int>>& matrix, vector<vector<int>>& visitedTimes, bool pacific) {
int m = matrix.size();
int n = matrix[0].size();
queue<pair<int, int>> Q;
vector<vector<bool>> visited(m, vector<bool>(n));
if (pacific) {
for (int j = 0; j < n; ++j) {
Q.emplace(0, j);
visited[0][j] = true;
++visitedTimes[0][j];
}
for (int i = 1; i < m; ++i) {
Q.emplace(i, 0);
visited[i][0] = true;
++visitedTimes[i][0];
}
}
else {
for (int i = 0; i < m; ++i) {
Q.emplace(i, n - 1);
visited[i][n - 1] = true;
++visitedTimes[i][n - 1];
}
for (int j = 0; j < n - 1; ++j) {
Q.emplace(m - 1, j);
visited[m - 1][j] = true;
++visitedTimes[m - 1][j];
}
}
vector<int> dr = {-1, 1, 0, 0};
vector<int> dc = {0, 0, -1, 1};
while (!Q.empty()) {
int r = Q.front().first;
int c = Q.front().second;
Q.pop();
for (int k = 0; k < dr.size(); ++k) {
int nr = r + dr[k];
int nc = c + dc[k];
if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc] && matrix[nr][nc] >= matrix[r][c]) {
Q.emplace(nr, nc);
visited[nr][nc] = true;
++visitedTimes[nr][nc];
}
}
}
}
};
|
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author raver119@gmail.com
//
#include <execution/AffinityManager.h>
#include <execution/ContextBuffers.h>
namespace sd {
ContextBuffers::ContextBuffers() { _deviceId = AffinityManager::currentDeviceId(); }
ContextBuffers::~ContextBuffers() {
// no-op
}
ContextBuffers::ContextBuffers(void* rPointer, void* sPointer, void* aPointer, bool isOwner) {
_reductionPointer = rPointer;
_scalarPointer = sPointer;
_allocationPointer = aPointer;
_allocated = isOwner;
}
ContextBuffers::ContextBuffers(const ContextBuffers& other) {
//
}
void ContextBuffers::initialize() {
// no-op
}
void* ContextBuffers::reductionBuffer() { return _reductionPointer; }
void* ContextBuffers::scalarBuffer() { return _scalarPointer; }
void* ContextBuffers::allocationBuffer() { return _allocationPointer; }
void ContextBuffers::setReductionBuffer(void* pointer) { _reductionPointer = pointer; }
void ContextBuffers::setScalarBuffer(void* pointer) { _scalarPointer = pointer; }
void ContextBuffers::setAllocationBuffer(void* pointer) { _allocationPointer = pointer; }
void ContextBuffers::triggerOwnership(bool isOwner) { _allocated = isOwner; }
int ContextBuffers::deviceId() { return _deviceId; }
void* ContextBuffers::execStream() { return _execStream; }
void* ContextBuffers::specialStream() { return _specialStream; }
bool ContextBuffers::isInitialized() { return true; }
void ContextBuffers::release() {
//
}
ContextBuffers& ContextBuffers::operator=(const ContextBuffers& other) { return *this; }
ContextBuffers& ContextBuffers::operator=(ContextBuffers&& other) { return *this; }
sd::ErrorReference* ContextBuffers::errorReference() { return &_errorReference; }
} // namespace sd
|
// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// +build
#define SYZ_EXECUTOR
#include "common_akaros.h"
#include "executor_posix.h"
#include "executor.h"
#include "syscalls_akaros.h"
uint32_t output;
int main(int argc, char** argv)
{
if (argc == 2 && strcmp(argv[1], "version") == 0) {
puts(GOOS " " GOARCH " " SYZ_REVISION " " GIT_REVISION);
return 0;
}
use_temporary_dir();
install_segv_handler();
setup_control_pipes();
receive_handshake();
reply_handshake();
for (;;) {
receive_execute(true);
char cwdbuf[128] = "/syz-tmpXXXXXX";
mkdtemp(cwdbuf);
int pid = fork();
if (pid < 0)
fail("fork failed");
if (pid == 0) {
close(kInPipeFd);
close(kOutPipeFd);
if (chdir(cwdbuf))
fail("chdir failed");
execute_one();
doexit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
int res = waitpid(pid, &status, WNOHANG);
if (res == pid)
break;
sleep_ms(10);
uint64_t now = current_time_ms();
if (now - start < 3 * 1000)
continue;
kill(pid, SIGKILL);
while (waitpid(pid, &status, 0) != pid) {
}
break;
}
status = WEXITSTATUS(status);
if (status == kFailStatus)
fail("child failed");
if (status == kErrorStatus)
error("child errored");
remove_dir(cwdbuf);
reply_execute(0);
}
return 0;
}
long execute_syscall(call_t* c, long a0, long a1, long a2, long a3, long a4, long a5, long a6, long a7, long a8)
{
return syscall(c->sys_nr, a0, a1, a2, a3, a4, a5, a6, a7, a8);
}
void cover_open()
{
}
void cover_enable(thread_t* th)
{
}
void cover_reset(thread_t* th)
{
}
uint64_t read_cover_size(thread_t* th)
{
return 0;
}
uint32_t* write_output(uint32_t v)
{
return &output;
}
void write_completed(uint32_t completed)
{
}
|
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include "Profile.hpp"
namespace audio
{
class ProfileRoutingBluetoothHSP : public Profile
{
public:
ProfileRoutingBluetoothHSP(Volume volume, Gain gain)
: Profile("Routing Bluetooth HSP",
Type::RoutingBluetoothHSP,
audio::codec::Configuration{
.sampleRate_Hz = 8000,
.bitWidth = 16,
.flags = static_cast<uint32_t>(
audio::codec::Flags::InputLeft) | // microphone use left audio channel
static_cast<uint32_t>(audio::codec::Flags::OutputMono),
.outputVolume = static_cast<float>(volume),
.inputGain = static_cast<float>(gain),
.inputPath = audio::codec::InputPath::None,
.outputPath = audio::codec::OutputPath::None},
AudioDevice::Type::BluetoothHSP)
{}
};
} // namespace audio
|
// Copyright (c) 2014 Grant Mercer
//
// 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)
/// \file parallel/algorithms/count.hpp
#if !defined(HPX_PARALLEL_DETAIL_COUNT_JUNE_17_2014_1154AM)
#define HPX_PARALLEL_DETAIL_COUNT_JUNE_17_2014_1154AM
#include <hpx/hpx_fwd.hpp>
#include <hpx/util/move.hpp>
#include <hpx/util/unwrapped.hpp>
#include <hpx/parallel/config/inline_namespace.hpp>
#include <hpx/parallel/execution_policy.hpp>
#include <hpx/parallel/algorithms/detail/algorithm_result.hpp>
#include <hpx/parallel/algorithms/detail/dispatch.hpp>
#include <hpx/parallel/util/partitioner.hpp>
#include <hpx/parallel/util/loop.hpp>
#include <boost/range/functions.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/utility/enable_if.hpp>
#include <algorithm>
#include <iterator>
#include <type_traits>
namespace hpx { namespace parallel { HPX_INLINE_NAMESPACE(v1)
{
///////////////////////////////////////////////////////////////////////////
// count
namespace detail
{
/// \cond NOINTERNAL
template <typename Value>
struct count
: public detail::algorithm<count<Value>, Value>
{
typedef Value difference_type;
count()
: count::algorithm("count")
{}
template <typename ExPolicy, typename Iter, typename T>
static difference_type
sequential(ExPolicy const&, Iter first, Iter last, T const& value)
{
return std::count(first, last, value);
}
template <typename ExPolicy, typename Iter, typename T>
static typename detail::algorithm_result<ExPolicy, difference_type>::type
parallel(ExPolicy const& policy, Iter first, Iter last,
T const& value)
{
if (first == last)
return detail::algorithm_result<ExPolicy, difference_type>::get(0);
return util::partitioner<ExPolicy, difference_type>::call(
policy, first, std::distance(first, last),
[value](Iter part_begin, std::size_t part_size) -> difference_type
{
difference_type ret = 0;
util::loop_n(part_begin, part_size,
[&value, &ret](Iter const& curr)
{
if (value == *curr)
++ret;
});
return ret;
},
hpx::util::unwrapped(
[](std::vector<difference_type>&& results)
{
return util::accumulate_n(
boost::begin(results), boost::size(results),
difference_type(0), std::plus<difference_type>());
}));
}
};
template <typename ExPolicy, typename InIter, typename T>
inline typename detail::algorithm_result<
ExPolicy, typename std::iterator_traits<InIter>::difference_type
>::type
count_(ExPolicy && policy, InIter first, InIter last, T const& value,
std::false_type)
{
typedef typename std::iterator_traits<InIter>::iterator_category
category;
typedef typename boost::mpl::or_<
parallel::is_sequential_execution_policy<ExPolicy>,
boost::is_same<std::input_iterator_tag, category>
>::type is_seq;
typedef typename std::iterator_traits<InIter>::difference_type
difference_type;
return detail::count<difference_type>().call(
std::forward<ExPolicy>(policy), is_seq(), first, last, value);
}
// forward declare the segmented version of this algorithm
template <typename ExPolicy, typename InIter, typename T>
typename detail::algorithm_result<
ExPolicy, typename std::iterator_traits<InIter>::difference_type
>::type
count_(ExPolicy&& policy, InIter first, InIter last, T const& value,
std::true_type);
/// \endcond
}
/// Returns the number of elements in the range [first, last) satisfying
/// a specific criteria. This version counts the elements that are equal to
/// the given \a value.
///
/// \note Complexity: Performs exactly \a last - \a first comparisons.
///
/// \tparam ExPolicy The type of the execution policy to use (deduced).
/// It describes the manner in which the execution
/// of the algorithm may be parallelized and the manner
/// in which it executes the comparisons.
/// \tparam InIter The type of the source iterators used (deduced).
/// This iterator type must meet the requirements of an
/// input iterator.
/// \tparam T The type of the value to search for (deduced).
///
/// \param policy The execution policy to use for the scheduling of
/// the iterations.
/// \param first Refers to the beginning of the sequence of elements
/// the algorithm will be applied to.
/// \param last Refers to the end of the sequence of elements the
/// algorithm will be applied to.
/// \param value The value to search for.
///
/// The comparisons in the parallel \a count algorithm invoked with
/// an execution policy object of type \a sequential_execution_policy
/// execute in sequential order in the calling thread.
///
/// \note The comparisons in the parallel \a count algorithm invoked with
/// an execution policy object of type \a parallel_execution_policy or
/// \a parallel_task_execution_policy are permitted to execute in an unordered
/// fashion in unspecified threads, and indeterminately sequenced
/// within each thread.
///
/// \returns The \a count algorithm returns a
/// \a hpx::future<difference_type> if the execution policy is of
/// type
/// \a sequential_task_execution_policy or
/// \a parallel_task_execution_policy and
/// returns \a difference_type otherwise (where \a difference_type
/// is defined by \a std::iterator_traits<InIter>::difference_type.
/// The \a count algorithm returns the number of elements
/// satisfying the given criteria.
///
template <typename ExPolicy, typename InIter, typename T>
inline typename boost::enable_if<
is_execution_policy<ExPolicy>,
typename detail::algorithm_result<ExPolicy,
typename std::iterator_traits<InIter>::difference_type
>::type
>::type
count(ExPolicy && policy, InIter first, InIter last, T const& value)
{
typedef typename std::iterator_traits<InIter>::iterator_category
category;
BOOST_STATIC_ASSERT_MSG(
(boost::is_base_of<std::input_iterator_tag, category>::value),
"Required at least input iterator.");
typedef hpx::traits::segmented_iterator_traits<InIter> iterator_traits;
typedef typename iterator_traits::is_segmented_iterator is_segmented;
return detail::count_(
std::forward<ExPolicy>(policy), first, last, value,
is_segmented());
}
///////////////////////////////////////////////////////////////////////////
// count_if
namespace detail
{
/// \cond NOINTERNAL
template <typename Value>
struct count_if
: public detail::algorithm<count_if<Value>, Value>
{
typedef Value difference_type;
count_if()
: count_if::algorithm("count_if")
{}
template <typename ExPolicy, typename Iter, typename Pred>
static difference_type
sequential(ExPolicy const&, Iter first, Iter last, Pred && op)
{
return std::count_if(first, last, std::forward<Pred>(op));
}
template <typename ExPolicy, typename Iter, typename Pred>
static typename detail::algorithm_result<ExPolicy, difference_type>::type
parallel(ExPolicy const& policy, Iter first, Iter last, Pred && op)
{
if (first == last)
return detail::algorithm_result<ExPolicy, difference_type>::get(0);
return util::partitioner<ExPolicy, difference_type>::call(
policy, first, std::distance(first, last),
[op](Iter part_begin, std::size_t part_size) -> difference_type
{
difference_type ret = 0;
util::loop_n(part_begin, part_size,
[&op, &ret](Iter const& curr)
{
if (op(*curr))
++ret;
});
return ret;
},
hpx::util::unwrapped(
[](std::vector<difference_type> && results)
{
return util::accumulate_n(
boost::begin(results), boost::size(results),
difference_type(0), std::plus<difference_type>());
}));
}
};
template <typename ExPolicy, typename InIter, typename F>
typename detail::algorithm_result<
ExPolicy, typename std::iterator_traits<InIter>::difference_type
>::type
count_if_(ExPolicy && policy, InIter first, InIter last, F && f,
std::false_type)
{
typedef typename std::iterator_traits<InIter>::iterator_category
category;
typedef typename boost::mpl::or_<
parallel::is_sequential_execution_policy<ExPolicy>,
boost::is_same<std::input_iterator_tag, category>
>::type is_seq;
typedef typename std::iterator_traits<InIter>::difference_type
difference_type;
return detail::count_if<difference_type>().call(
std::forward<ExPolicy>(policy), is_seq(),
first, last, std::forward<F>(f));
}
// forward declare the segmented version of this algorithm
template <typename ExPolicy, typename InIter, typename F>
typename detail::algorithm_result<
ExPolicy, typename std::iterator_traits<InIter>::difference_type
>::type
count_if_(ExPolicy && policy, InIter first, InIter last, F && f,
std::true_type);
/// \endcond
}
/// Returns the number of elements in the range [first, last) satisfying
/// a specific criteria. This version counts elements for which predicate
/// \a f returns true.
///
/// \note Complexity: Performs exactly \a last - \a first applications of
/// the predicate.
///
/// \tparam ExPolicy The type of the execution policy to use (deduced).
/// It describes the manner in which the execution
/// of the algorithm may be parallelized and the manner
/// in which it executes the comparisons.
/// \tparam InIter The type of the source iterators used (deduced).
/// This iterator type must meet the requirements of an
/// input iterator.
/// \tparam F The type of the function/function object to use
/// (deduced). Unlike its sequential form, the parallel
/// overload of \a count_if requires \a F to meet the
/// requirements of \a CopyConstructible.
///
/// \param policy The execution policy to use for the scheduling of
/// the iterations.
/// \param first Refers to the beginning of the sequence of elements
/// the algorithm will be applied to.
/// \param last Refers to the end of the sequence of elements the
/// algorithm will be applied to.
/// \param f Specifies the function (or function object) which
/// will be invoked for each of the elements in the
/// sequence specified by [first, last).This is an
/// unary predicate which returns \a true for the
/// required elements. The signature of this predicate
/// should be equivalent to:
/// \code
/// bool pred(const Type &a);
/// \endcode \n
/// The signature does not need to have const&, but
/// the function must not modify the objects passed to
/// it. The type \a Type must be such that an object of
/// type \a InIter can be dereferenced and then
/// implicitly converted to Type.
///
/// \note The assignments in the parallel \a count_if algorithm invoked with
/// an execution policy object of type \a sequential_execution_policy
/// execute in sequential order in the calling thread.
/// \note The assignments in the parallel \a count_if algorithm invoked with
/// an execution policy object of type \a parallel_execution_policy or
/// \a parallel_task_execution_policy are permitted to execute in an unordered
/// fashion in unspecified threads, and indeterminately sequenced
/// within each thread.
///
/// \returns The \a count_if algorithm returns
/// \a hpx::future<difference_type> if the execution policy is of
/// type
/// \a sequential_task_execution_policy or
/// \a parallel_task_execution_policy and
/// returns \a difference_type otherwise (where \a difference_type
/// is defined by \a std::iterator_traits<InIter>::difference_type.
/// The \a count algorithm returns the number of elements
/// satisfying the given criteria.
///
template <typename ExPolicy, typename InIter, typename F>
inline typename boost::enable_if<
is_execution_policy<ExPolicy>,
typename detail::algorithm_result<ExPolicy,
typename std::iterator_traits<InIter>::difference_type
>::type
>::type
count_if(ExPolicy && policy, InIter first, InIter last, F && f)
{
typedef typename std::iterator_traits<InIter>::iterator_category
category;
BOOST_STATIC_ASSERT_MSG(
(boost::is_base_of<std::input_iterator_tag, category>::value),
"Required at least input iterator.");
typedef hpx::traits::segmented_iterator_traits<InIter> iterator_traits;
typedef typename iterator_traits::is_segmented_iterator is_segmented;
return detail::count_if_(
std::forward<ExPolicy>(policy), first, last, std::forward<F>(f),
is_segmented());
}
}}}
#endif
|
#include "luavmstate.h"
#include "cgt/assert.h"
#include "cgt/logmanager.h"
#include "core/tools/stringutils.h"
namespace campvis {
MetatableLuaTable::MetatableLuaTable(std::shared_ptr<LuaTable> parent, std::string fieldName)
: LuaTable(parent->_luaVmState)
, _parent(parent)
, _fieldName(fieldName)
{
}
MetatableLuaTable::~MetatableLuaTable() {}
bool MetatableLuaTable::isValid() {
bool toReturn = false;
LuaStateMutexType::scoped_lock lock(_luaVmState.getMutex());
lua_State* L = _luaVmState.rawState();
_parent->pushField(_fieldName);
if (!lua_getmetatable(_luaVmState.rawState(), -1)) {
lua_pop(L, 1);
toReturn = true;
}
_parent->popRecursive();
return toReturn;
}
void MetatableLuaTable::callInstanceMethod(const std::string& name) {
LuaStateMutexType::scoped_lock lock(_luaVmState.getMutex());
cgtAssert(false, "Method not verified, use with care!");
// recursively push this metatable onto stack, so that we can refer to it later
_parent->pushField(_fieldName);
// push the function onto the stack
lua_getfield(_luaVmState.rawState(), -1, name.c_str());
// push the metatable onto the stack again (now non-recusively)
if (!lua_getmetatable(_luaVmState.rawState(), -2))
cgtAssert(false, "This should not happen, Lua stack is corrupted!");
// call the function
_luaVmState.callLuaFunc(1, 0);
// clean up the stack
lua_pop(_luaVmState.rawState(), 1);
_parent->popRecursive();
}
void MetatableLuaTable::pushField(const std::string& name) {
LuaStateMutexType::scoped_lock lock(_luaVmState.getMutex());
lua_State* L = _luaVmState.rawState();
// load the parent field first
_parent->pushField(_fieldName);
// now load the metatable
if (! lua_getmetatable(L, -1))
cgtAssert(false, "This should not happen!");
// now load the field
auto it = _valueMap.find(name);
if (it != _valueMap.end()) {
lua_State* L = _luaVmState.rawState();
if (it->second.keyIsNumber)
lua_pushnumber(L, StringUtils::fromString<double>(name));
else
lua_pushstring(L, name.c_str());
lua_gettable(L, -2);
}
else {
cgtAssert(false, "Field not in valueMap, this should not happen.");
}
}
void MetatableLuaTable::popRecursive() {
LuaStateMutexType::scoped_lock lock(_luaVmState.getMutex());
lua_pop(_luaVmState.rawState(), 2);
_parent->popRecursive();
}
void MetatableLuaTable::populateValueMap() {
_valueMap.clear();
LuaStateMutexType::scoped_lock lock(_luaVmState.getMutex());
lua_State* L = _luaVmState.rawState();
// load this metatable onto stack
_parent->pushField(_fieldName);
if (! lua_getmetatable(L, -1))
cgtAssert(false, "This should not happen!");
iterateOverTableAndPopulateValueMap(L);
lua_pop(L, 1);
_parent->popRecursive();
}
LuaTable* MetatableLuaTable::getParentTable() {
return _parent.get();
}
}
|
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
#include "pch.h"
#if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
#endif
#include "AboutPage.xaml.h"
void ::Webserver_UWP_WRL::AboutPage::InitializeComponent()
{
if (_contentLoaded)
{
return;
}
_contentLoaded = true;
::Windows::Foundation::Uri^ resourceLocator = ref new ::Windows::Foundation::Uri(L"ms-appx:///AboutPage.xaml");
::Windows::UI::Xaml::Application::LoadComponent(this, resourceLocator, ::Windows::UI::Xaml::Controls::Primitives::ComponentResourceLocation::Application);
}
void ::Webserver_UWP_WRL::AboutPage::Connect(int __connectionId, ::Platform::Object^ __target)
{
__connectionId; // unreferenced
__target; // unreferenced
_contentLoaded = true;
}
::Windows::UI::Xaml::Markup::IComponentConnector^ ::Webserver_UWP_WRL::AboutPage::GetBindingConnector(int __connectionId, ::Platform::Object^ __target)
{
__connectionId; // unreferenced
__target; // unreferenced
return nullptr;
}
|
// Copyright (c) 2016, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef TEXT_VIEW_TEXT_VIEW_HPP // {
#define TEXT_VIEW_TEXT_VIEW_HPP
#include <iterator>
#include <string>
#include <utility>
#include <range/v3/range_traits.hpp>
#include <range/v3/utility/concepts.hpp>
#include <range/v3/utility/iterator_concepts.hpp>
#include <range/v3/utility/iterator_traits.hpp>
#include <text_view_detail/adl_customization.hpp>
#include <text_view_detail/advance_to.hpp>
#include <text_view_detail/basic_view.hpp>
#include <text_view_detail/concepts.hpp>
#include <text_view_detail/default_encoding.hpp>
#include <text_view_detail/error_policy.hpp>
#include <text_view_detail/itext_iterator.hpp>
#include <text_view_detail/itext_sentinel.hpp>
#include <text_view_detail/subobject.hpp>
namespace std {
namespace experimental {
inline namespace text {
template<typename ET, typename VT, typename TEP = text_default_error_policy,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
ranges::View<VT>(),
TextErrorPolicy<TEP>())>
class basic_text_view
: private text_detail::subobject<typename ET::state_type>,
public ranges::view_base
{
using base_type = text_detail::subobject<typename ET::state_type>;
public:
using encoding_type = ET;
using view_type = VT;
using error_policy = TEP;
using state_type = typename ET::state_type;
using code_unit_iterator =
ranges::iterator_t<
typename std::add_const<view_type>::type>;
using code_unit_sentinel =
ranges::sentinel_t<
typename std::add_const<view_type>::type>;
using iterator = itext_iterator<ET, VT, TEP>;
using sentinel = itext_sentinel<ET, VT, TEP>;
// The default constructor produces a text view with a singular range. An
// object produced with this constructor may only be assigned to or
// destroyed.
basic_text_view() = default;
// Overload to initialize a text view from an object of the underlying code
// unit view type and an explicitly specified initial encoding state.
basic_text_view(
state_type state,
view_type view)
:
base_type{std::move(state)},
view{std::move(view)}
{}
// Overload to initialize a text view from an object of the underlying code
// unit view type and an implicit initial encoding state.
basic_text_view(
view_type view)
:
base_type{encoding_type::initial_state()},
view{std::move(view)}
{}
// Overload to initialize a text view from an InputIterator and Sentinel
// pair, and an explicitly specified initial encoding state. This overload
// requires that view_type be constructible from a code_unit_iterator pair.
CONCEPT_REQUIRES(
ranges::Constructible<
view_type,
code_unit_iterator&&,
code_unit_sentinel&&>())
basic_text_view(
state_type state,
code_unit_iterator first,
code_unit_sentinel last)
:
base_type{std::move(state)},
view{std::move(first), std::move(last)}
{}
// Overload to initialize a text view from an InputIterator and Sentinel
// pair, and an implicit initial encoding state. This overload requires
// that view_type be constructible from a code_unit_iterator pair.
CONCEPT_REQUIRES(
ranges::Constructible<
view_type,
code_unit_iterator&&,
code_unit_sentinel&&>())
basic_text_view(
code_unit_iterator first,
code_unit_sentinel last)
:
base_type{encoding_type::initial_state()},
view{std::move(first), std::move(last)}
{}
// Overload to initialize a text view from an InputIterator and count pair,
// and an explicitly specified initial encoding state. This overload
// requires that view_type be constructible from a code_unit_iterator pair.
CONCEPT_REQUIRES(
ranges::Constructible<
view_type,
code_unit_iterator,
code_unit_iterator>())
basic_text_view(
state_type state,
code_unit_iterator first,
ranges::difference_type_t<code_unit_iterator> n)
:
base_type{std::move(state)},
view{first, std::next(first, n)}
{}
// Overload to initialize a text view from an InputIterator and count pair,
// and an implicit initial encoding state. This overload requires that
// view_type be constructible from a code_unit_iterator pair.
CONCEPT_REQUIRES(
ranges::Constructible<
view_type,
code_unit_iterator,
code_unit_iterator>())
basic_text_view(
code_unit_iterator first,
ranges::difference_type_t<code_unit_iterator> n)
:
base_type{encoding_type::initial_state()},
view{first, std::next(first, n)}
{}
// Overload to initialize a text view with an explicitly specified initial
// encoding state and a basic_string specialization. This overload requires
// that view_type be constructible from a code_unit_iterator pair, that
// code_unit_iterator be constructible from a const code unit pointer, and
// that the difference type (likely ptrdiff_t) for code_unit_iterator be
// constructible from the basic_string size_type. This overload enables
// construction with basic_string specializations when view_type requires
// pointers to contiguous memory (as is the case for text_view, wtext_view,
// etc...). When this overload is not enabled, construction with a
// basic_string specialization will be handled by the constructor below
// and the basic_string specialization will be treated as any other type
// that models Range (in which case, code_unit_iterator must be
// constructible from the basic_string const_iterator type). Since
// iterators into the provided basic_string object will be held, the
// basic_string reference must reference an object with a lifetime that
// exceeds the lifetime of the basic_text_view object being constructed.
template<typename charT, typename traits, typename Allocator,
CONCEPT_REQUIRES_(
ranges::Constructible<code_unit_iterator, const charT *>(),
ranges::ConvertibleTo< // Allow narrowing conversions.
ranges::difference_type_t<code_unit_iterator>,
typename basic_string<charT, traits, Allocator>::size_type>(),
ranges::Constructible<
view_type, code_unit_iterator, code_unit_sentinel>())>
basic_text_view(
state_type state,
const basic_string<charT, traits, Allocator> &str)
:
basic_text_view{std::move(state),
str.c_str(),
ranges::difference_type_t<
code_unit_iterator>(str.size())}
{}
// Overload to initialize a text view with an implicitly specified initial
// encoding state and a basic_string specialization. See the above comments
// for the similar overload that accepts an explicitly specified initial
// state.
template<typename charT, typename traits, typename Allocator,
CONCEPT_REQUIRES_(
ranges::Constructible<code_unit_iterator, const charT *>(),
ranges::ConvertibleTo< // Allow narrowing conversions.
ranges::difference_type_t<code_unit_iterator>,
typename basic_string<charT, traits, Allocator>::size_type>(),
ranges::Constructible<
view_type, code_unit_iterator, code_unit_sentinel>())>
basic_text_view(
const basic_string<charT, traits, Allocator> &str)
:
basic_text_view{str.c_str(),
ranges::difference_type_t<
code_unit_iterator>(str.size())}
{}
// Overload to initialize a text view with an explicitly specified initial
// encoding state and an InputIterator and Sentinel extracted from a
// supplied InputRange. The underlying view type must be constructible from
// the iterator type of the range type. Since iterators into the provided
// InputRange object will be held, the specified range must be a reference
// to an object with a lifetime that exceeds the lifetime of the
// basic_text_view object being constructed.
template<typename RT,
CONCEPT_REQUIRES_(
ranges::InputRange<RT>(),
ranges::Constructible<
code_unit_iterator,
ranges::iterator_t<const RT>>(),
ranges::Constructible<
view_type,
code_unit_iterator,
code_unit_sentinel>())>
basic_text_view(
state_type state,
const RT &range)
:
basic_text_view(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range))
{}
// Overload to initialize a text view with an implicitly specified initial
// encoding state and an InputIterator and Sentinel extracted from a
// supplied InputRange. See the above comments for the similar overload
// that accepts an explicitly specified initial state.
template<typename RT,
CONCEPT_REQUIRES_(
ranges::InputRange<RT>(),
ranges::Constructible<
code_unit_iterator,
ranges::iterator_t<const RT>>(),
ranges::Constructible<
view_type,
code_unit_iterator,
code_unit_sentinel>())>
basic_text_view(
const RT &range)
:
basic_text_view(text_detail::adl_begin(range),
text_detail::adl_end(range))
{}
// Overload to initialize a text view from a text iterator pair.
// The initial encoding state is inferred from the first iterator.
CONCEPT_REQUIRES(
ranges::Constructible<
code_unit_iterator,
decltype(std::declval<iterator>().base())>(),
ranges::Constructible<
view_type,
code_unit_iterator,
code_unit_iterator>())
basic_text_view(
iterator first,
iterator last)
:
basic_text_view{first.state(), first.base(), last.base()}
{}
// Overload to initialize a text view from a text iterator/sentinel pair.
// The initial encoding state is inferred from the first iterator.
CONCEPT_REQUIRES(
ranges::Constructible<
code_unit_iterator,
decltype(std::declval<iterator>().base())>(),
ranges::Constructible<
view_type,
code_unit_iterator,
code_unit_sentinel>())
basic_text_view(
iterator first,
sentinel last)
:
basic_text_view{first.state(), first.base(), last.base()}
{}
const view_type& base() const noexcept {
return view;
}
const state_type& initial_state() const noexcept {
return base_type::get();
}
iterator begin() const {
return iterator{initial_state(), &view, text_detail::adl_begin(view)};
}
CONCEPT_REQUIRES(
std::is_empty<state_type>::value &&
ranges::Iterator<code_unit_sentinel>())
iterator end() const
{
// Use the (empty) initial state to construct the end iterator.
return iterator{ET::initial_state(), &view, text_detail::adl_end(view)};
}
CONCEPT_REQUIRES(
! std::is_empty<state_type>::value ||
! ranges::Iterator<code_unit_sentinel>())
sentinel end() const
{
return sentinel{text_detail::adl_end(view)};
}
private:
view_type view;
};
using text_view = basic_text_view<
execution_character_encoding,
text_detail::basic_view<const char*>>;
using wtext_view = basic_text_view<
execution_wide_character_encoding,
text_detail::basic_view<const wchar_t*>>;
// FIXME: If P0482 were to be adopted, replace char with char8_t.
using u8text_view = basic_text_view<
char8_character_encoding,
text_detail::basic_view<const char*>>;
using u16text_view = basic_text_view<
char16_character_encoding,
text_detail::basic_view<const char16_t*>>;
using u32text_view = basic_text_view<
char32_character_encoding,
text_detail::basic_view<const char32_t*>>;
/*
* make_text_view
*/
// Overload to construct a text view for an explicitly specified encoding type
// and error policy from an InputIterator and Sentinel pair, and an explicitly
// specified initial encoding state.
template<typename ET, typename TEP, typename IT, typename ST,
typename VT = text_detail::basic_view<IT, ST>,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
TextErrorPolicy<TEP>(),
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ST last)
-> basic_text_view<ET, VT, TEP>
{
return basic_text_view<ET, VT, TEP>{std::move(state),
std::move(first),
std::move(last)};
}
// Overload to construct a text view for an explicitly specified encoding type
// and an implicitly specified error policy from an InputIterator and Sentinel
// pair, and an explicitly specified initial encoding state.
template<typename ET, typename IT, typename ST,
typename VT = text_detail::basic_view<IT, ST>,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ST last)
-> basic_text_view<ET, VT>
{
return basic_text_view<ET, VT>{std::move(state),
std::move(first),
std::move(last)};
}
// Overload to construct a text view for an implicitly assumed encoding type
// and explicitly specified error policy from an InputIterator and Sentinel
// pair, and an explicitly specified initial encoding state.
template<typename TEP, typename IT, typename ST, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ST last)
-> decltype(text::make_text_view<ET, TEP>(std::move(state),
std::move(first),
std::move(last)))
{
return text::make_text_view<ET, TEP>(std::move(state),
std::move(first),
std::move(last));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and error policy from an InputIterator and Sentinel pair, and an explicitly
// specified initial encoding state.
template<typename IT, typename ST, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ST last)
-> decltype(text::make_text_view<ET>(std::move(state),
std::move(first),
std::move(last)))
{
return text::make_text_view<ET>(std::move(state),
std::move(first),
std::move(last));
}
// Overload to construct a text view for an explicitly specified encoding type
// and error policy from an InputIterator and Sentinel pair, and an implicit
// initial encoding state.
template<typename ET, typename TEP, typename IT, typename ST,
typename VT = text_detail::basic_view<IT, ST>,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
TextErrorPolicy<TEP>(),
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
IT first,
ST last)
-> basic_text_view<ET, VT, TEP>
{
return basic_text_view<ET, VT, TEP>{std::move(first),
std::move(last)};
}
// Overload to construct a text view for an explicitly specified encoding type
// and an implicitly specified error policy from an InputIterator and Sentinel
// pair, and an implicit initial encoding state.
template<typename ET, typename IT, typename ST,
typename VT = text_detail::basic_view<IT, ST>,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
IT first,
ST last)
-> basic_text_view<ET, VT>
{
return basic_text_view<ET, VT>{std::move(first),
std::move(last)};
}
// Overload to construct a text view for an implicitly assumed encoding type
// and explicitly specified error policy from an InputIterator and Sentinel
// pair, and an implicit initial encoding state.
template<typename TEP, typename IT, typename ST, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
IT first,
ST last)
-> decltype(text::make_text_view<ET, TEP>(std::move(first),
std::move(last)))
{
return text::make_text_view<ET, TEP>(std::move(first),
std::move(last));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and error policy from an InputIterator and Sentinel pair, and an implicit
// initial encoding state.
template<typename IT, typename ST, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
ranges::InputIterator<IT>(),
ranges::Sentinel<ST, IT>())>
auto make_text_view(
IT first,
ST last)
-> decltype(text::make_text_view<ET>(std::move(first),
std::move(last)))
{
return text::make_text_view<ET>(std::move(first),
std::move(last));
}
// Overload to construct a text view for an explicitly specified encoding type
// and error policy from a ForwardIterator and count pair, and an explicitly
// specified initial encoding state.
template<typename ET, typename TEP, typename IT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
TextErrorPolicy<TEP>(),
ranges::ForwardIterator<IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET, TEP>(std::move(state),
std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET, TEP>(std::move(state),
std::move(first),
std::move(last));
}
// Overload to construct a text view for an explicitly specified encoding type
// and implicitly assumed error policy from a ForwardIterator and count pair,
// and an explicitly specified initial encoding state.
template<typename ET, typename IT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
ranges::ForwardIterator<IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET>(std::move(state),
std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET>(std::move(state),
std::move(first),
std::move(last));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and explicitly specified error policy from a ForwardIterator and count pair,
// and an explicitly specified initial encoding state.
template<typename TEP, typename IT, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
ranges::ForwardIterator<IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET, TEP>(std::move(state),
std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET, TEP>(std::move(state),
std::move(first),
std::move(last));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and error policy from a ForwardIterator and count pair, and an explicitly
// specified initial encoding state.
template<typename IT, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
ranges::ForwardIterator<IT>())>
auto make_text_view(
typename ET::state_type state,
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET>(std::move(state),
std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET>(std::move(state),
std::move(first),
std::move(last));
}
// Overload to construct a text view for an explicitly specified encoding type
// and error policy from a ForwardIterator and count pair, and an implicit
// initial encoding state.
template<typename ET, typename TEP, typename IT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
TextErrorPolicy<TEP>(),
ranges::ForwardIterator<IT>())>
auto make_text_view(
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET, TEP>(std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET, TEP>(std::move(first),
std::move(last));
}
// Overload to construct a text view for an explicitly specified encoding type
// and implicitly assumed error policy from a ForwardIterator and count pair,
// and an implicit initial encoding state.
template<typename ET, typename IT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
ranges::ForwardIterator<IT>())>
auto make_text_view(
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET>(std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET>(std::move(first),
std::move(last));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and explicitly specified error policy from a ForwardIterator and count pair,
// and an implicit initial encoding state.
template<typename TEP, typename IT, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
ranges::ForwardIterator<IT>())>
auto make_text_view(
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET, TEP>(std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET, TEP>(std::move(first),
std::move(last));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and error policy from a ForwardIterator and count pair, and an implicit
// initial encoding state.
template<typename IT, typename ET =
default_encoding_type_t<ranges::value_type_t<IT>>,
CONCEPT_REQUIRES_(
ranges::ForwardIterator<IT>())>
auto make_text_view(
IT first,
ranges::difference_type_t<IT> n)
-> decltype(text::make_text_view<ET>(std::move(first),
std::move(std::next(first, n))))
{
auto last = std::next(first, n);
return text::make_text_view<ET>(std::move(first),
std::move(last));
}
// Overload to construct a text view for an explicitly specified encoding type
// and error policy from an InputRange const reference and an explicitly
// specified initial encoding state.
template<typename ET, typename TEP, typename RT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
TextErrorPolicy<TEP>(),
ranges::InputRange<RT>())>
auto make_text_view(
typename ET::state_type state,
const RT &range)
-> decltype(text::make_text_view<ET, TEP>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET, TEP>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view for an explicitly specified encoding type
// and implicitly assumed error policy from an InputRange const reference and
// an explicitly specified initial encoding state.
template<typename ET, typename RT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
ranges::InputRange<RT>())>
auto make_text_view(
typename ET::state_type state,
const RT &range)
-> decltype(text::make_text_view<ET>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and explicitly specified error policy from an InputRange const reference
// and an explicitly specified initial encoding state.
template<typename TEP, typename RT, typename ET =
default_encoding_type_t<ranges::range_value_type_t<RT>>,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
ranges::InputRange<RT>())>
auto make_text_view(
typename ET::state_type state,
const RT &range)
-> decltype(text::make_text_view<ET, TEP>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET, TEP>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and error policy from an InputRange const reference and an explicitly
// specified initial encoding state.
template<typename RT, typename ET =
default_encoding_type_t<ranges::range_value_type_t<RT>>,
CONCEPT_REQUIRES_(
ranges::InputRange<RT>())>
auto make_text_view(
typename ET::state_type state,
const RT &range)
-> decltype(text::make_text_view<ET>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET>(std::move(state),
text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view for an explicitly specified encoding type
// and error policy from an InputRange const reference and an implicit initial
// encoding state.
template<typename ET, typename TEP, typename RT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
TextErrorPolicy<TEP>(),
ranges::InputRange<RT>())>
auto make_text_view(
const RT &range)
-> decltype(text::make_text_view<ET, TEP>(text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET, TEP>(text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view for an explicitly specified encoding type
// and implicitly assumed error policy from an InputRange const reference and
// an implicit initial encoding state.
template<typename ET, typename RT,
CONCEPT_REQUIRES_(
TextEncoding<ET>(),
ranges::InputRange<RT>())>
auto make_text_view(
const RT &range)
-> decltype(text::make_text_view<ET>(text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET>(text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and explicitly specified error policy from an InputRange const reference
// and an implicit initial encoding state.
template<typename TEP, typename RT, typename ET =
default_encoding_type_t<ranges::range_value_type_t<RT>>,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
ranges::InputRange<RT>())>
auto make_text_view(
const RT &range)
-> decltype(text::make_text_view<ET, TEP>(text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET, TEP>(text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view for an implicitly assumed encoding type
// and error policy from an InputRange const reference and an implicit initial
// encoding state.
template<typename RT, typename ET =
default_encoding_type_t<ranges::range_value_type_t<RT>>,
CONCEPT_REQUIRES_(
ranges::InputRange<RT>())>
auto make_text_view(
const RT &range)
-> decltype(text::make_text_view<ET>(text_detail::adl_begin(range),
text_detail::adl_end(range)))
{
return text::make_text_view<ET>(text_detail::adl_begin(range),
text_detail::adl_end(range));
}
// Overload to construct a text view with an explicitly specified error policy
// from a text iterator and sentinel pair. The initial encoding state is
// inferred from the first iterator.
template<typename TEP, typename TIT, typename TST, typename ET =
encoding_type_t<TIT>,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
TextInputIterator<TIT>(),
TextSentinel<TST, TIT>())>
auto make_text_view(
TIT first,
TST last)
-> decltype(text::make_text_view<ET, TEP>(first.state(),
first.base(),
last.base()))
{
return text::make_text_view<ET, TEP>(first.state(),
first.base(),
last.base());
}
// Overload to construct a text view with an implicitly assumed error policy
// from a text iterator and sentinel pair. The initial encoding state is
// inferred from the first iterator.
template<typename TIT, typename TST, typename ET = encoding_type_t<TIT>,
CONCEPT_REQUIRES_(
TextInputIterator<TIT>(),
TextSentinel<TST, TIT>())>
auto make_text_view(
TIT first,
TST last)
-> decltype(text::make_text_view<ET>(first.state(), first.base(), last.base()))
{
return text::make_text_view<ET>(first.state(), first.base(), last.base());
}
// Overload to construct a text view with an explicitly specified error policy
// from an existing text view.
template<typename TEP, typename TVT,
CONCEPT_REQUIRES_(
TextErrorPolicy<TEP>(),
TextView<TVT>())>
auto make_text_view(
TVT tv)
-> decltype(text::make_text_view<TEP>(text_detail::adl_begin(tv),
text_detail::adl_end(tv)))
{
return text::make_text_view<TEP>(text_detail::adl_begin(tv),
text_detail::adl_end(tv));
}
// Overload to construct a text view with an implicitly assumed error policy
// from an existing text view.
template<typename TVT,
CONCEPT_REQUIRES_(
TextView<TVT>())>
TVT make_text_view(
TVT tv)
{
return tv;
}
} // inline namespace text
} // namespace experimental
} // namespace std
#endif // } TEXT_VIEW_TEXT_VIEW_HPP
|
#include <iostream>
using namespace std;
int main()
{
cout << 123 << endl;
return 0;
}
|
//
// IDownloader.hpp
// G3M
//
// Created by Diego Gomez Deck on 27/07/12.
//
#ifndef G3M_IDownloader
#define G3M_IDownloader
class URL;
class G3MContext;
class IBufferDownloadListener;
class IImageDownloadListener;
class TimeInterval;
class FrameTasksExecutor;
#include <string>
class IDownloader {
public:
virtual ~IDownloader() {
}
virtual void initialize(const G3MContext* context,
FrameTasksExecutor* frameTasksExecutor) = 0;
virtual void onResume(const G3MContext* context) = 0;
virtual void onPause(const G3MContext* context) = 0;
virtual void onDestroy(const G3MContext* context) = 0;
virtual void start() = 0;
virtual void stop() = 0;
virtual long long requestBuffer(const URL& url,
long long priority,
const TimeInterval& timeToCache,
bool readExpired,
IBufferDownloadListener* listener,
bool deleteListener,
const std::string& tag) = 0;
virtual long long requestImage(const URL& url,
long long priority,
const TimeInterval& timeToCache,
bool readExpired,
IImageDownloadListener* listener,
bool deleteListener,
const std::string& tag) = 0;
long long requestBuffer(const URL& url,
long long priority,
const TimeInterval& timeToCache,
bool readExpired,
IBufferDownloadListener* listener,
bool deleteListener) {
return requestBuffer(url,
priority,
timeToCache,
readExpired,
listener,
deleteListener,
"" /* default tag */ );
}
long long requestImage(const URL& url,
long long priority,
const TimeInterval& timeToCache,
bool readExpired,
IImageDownloadListener* listener,
bool deleteListener) {
return requestImage(url,
priority,
timeToCache,
readExpired,
listener,
deleteListener,
"" /* default tag */ );
}
virtual bool cancelRequest(long long requestID) = 0;
virtual void cancelRequestsTagged(const std::string& tag) = 0;
virtual const std::string statistics() = 0;
};
#endif
|
#include "re2/re2.h"
#include "Foundational/data_source/iwstring_data_source.h"
#include "gfp.h"
int
count_tdts_in_file(iwstring_data_source & input,
const IWString & identifier_tag)
{
IWString tmp;
tmp << '^' << identifier_tag;
re2::StringPiece string_piece(tmp.data(), tmp.length());
re2::RE2 pcn(string_piece);
int rc = input.grep(pcn);
if (0 == rc)
{
cerr << "No occurrences of " << pcn.pattern () << "' in input\n";
return 0;
}
return rc;
}
|
#include "builtin/thread.hpp"
#include "builtin/lookuptable.hpp"
#include "builtin/tuple.hpp"
#include "builtin/list.hpp"
#include "builtin/class.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/symbol.hpp"
#include "builtin/float.hpp"
#include "builtin/channel.hpp"
#include "builtin/nativemethod.hpp"
#include "builtin/fiber.hpp"
#include "builtin/location.hpp"
#include "objectmemory.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"
#include "call_frame.hpp"
#include "environment.hpp"
#include "instruments/tooling.hpp"
#include "vm/object_utils.hpp"
#include "vm.hpp"
#include "on_stack.hpp"
#include "ontology.hpp"
#include "windows_compat.h"
#include <sys/time.h>
/* HACK: returns a value that should identify a native thread
* for debugging threading issues. The winpthreads library
* defines pthread_t to be a structure not a pointer.
*/
intptr_t thread_debug_self() {
#ifdef RBX_WINDOWS
return (intptr_t)(pthread_self()).p;
#else
return (intptr_t)pthread_self();
#endif
}
static intptr_t thread_debug_id(pthread_t thr) {
#ifdef RBX_WINDOWS
return (intptr_t)thr.p;
#else
return (intptr_t)thr;
#endif
}
namespace rubinius {
void Thread::init(STATE) {
GO(thread).set(ontology::new_class(state, "Thread", G(object)));
G(thread)->set_object_type(state, Thread::type);
}
Thread* Thread::create(STATE, VM* target, Object* self, Run runner,
bool main_thread)
{
Thread* thr = state->new_object<Thread>(G(thread));
thr->thread_id(state, Fixnum::from(target->thread_id()));
thr->alive(state, cTrue);
thr->sleep(state, cFalse);
thr->control_channel(state, nil<Channel>());
thr->locals(state, LookupTable::create(state));
thr->recursive_objects(state, LookupTable::create(state));
thr->vm_ = target;
thr->klass(state, as<Class>(self));
thr->runner_ = runner;
thr->init_lock_.init();
target->thread.set(thr);
if(!main_thread) thr->init_lock_.lock();
return thr;
}
Object* send_run(STATE) {
return state->vm()->thread.get()->send(state, NULL, state->symbol("__run__"));
}
Thread* Thread::allocate(STATE, Object* self) {
VM* vm = state->shared().new_vm();
Thread* thread = Thread::create(state, vm, self, send_run);
return thread;
}
Thread* Thread::current(STATE) {
return state->vm()->thread.get();
}
Object* Thread::unlock_locks(STATE, GCToken gct) {
std::list<ObjectHeader*>& los = vm_->locked_objects();
for(std::list<ObjectHeader*>::iterator i = los.begin();
i != los.end();
++i) {
(*i)->unlock_for_terminate(state, gct);
}
los.clear();
return cNil;
}
Object* Thread::locals_aref(STATE, Symbol* key) {
/*
* If we're not trying to set values on the current thread,
* we will set thread locals anyway and not use fiber locals.
*/
if(state->vm() != vm()) {
return locals()->aref(state, key);
}
Fiber* fib = state->vm()->current_fiber.get();
if(fib->nil_p() || fib->root_p()) {
return locals()->aref(state, key);
}
if(try_as<LookupTable>(fib->locals())) {
return fib->locals()->aref(state, key);
}
return cNil;
}
Object* Thread::locals_store(STATE, Symbol* key, Object* value) {
/*
* If we're not trying to set values on the current thread,
* we will set thread locals anyway and not use fiber locals.
*/
if(state->vm() != vm()) {
return locals()->store(state, key, value);
}
Fiber* fib = state->vm()->current_fiber.get();
if(fib->nil_p() || fib->root_p()) {
return locals()->store(state, key, value);
}
if(fib->locals()->nil_p()) {
fib->locals(state, LookupTable::create(state));
}
return fib->locals()->store(state, key, value);
}
Array* Thread::locals_keys(STATE) {
/*
* If we're not trying to set values on the current thread,
* we will set thread locals anyway and not use fiber locals.
*/
if(state->vm() != vm()) {
return locals()->all_keys(state);
}
Fiber* fib = state->vm()->current_fiber.get();
if(fib->nil_p() || fib->root_p()) {
return locals()->all_keys(state);
}
if(try_as<LookupTable>(fib->locals())) {
return fib->locals()->all_keys(state);
}
return Array::create(state, 0);
}
Object* Thread::locals_has_key(STATE, Symbol* key) {
/*
* If we're not trying to set values on the current thread,
* we will set thread locals anyway and not use fiber locals.
*/
if(state->vm() != vm()) {
return locals()->has_key(state, key);
}
Fiber* fib = state->vm()->current_fiber.get();
if(fib->nil_p() || fib->root_p()) {
return locals()->has_key(state, key);
}
if(try_as<LookupTable>(fib->locals())) {
return fib->locals()->has_key(state, key);
}
return cFalse;
}
void* Thread::in_new_thread(void* ptr) {
VM* vm = reinterpret_cast<VM*>(ptr);
State state_obj(vm), *state = &state_obj;
int calculate_stack = 0;
NativeMethod::init_thread(state);
VM::set_current(vm);
state->set_call_frame(0);
vm->shared.gc_dependent(state);
if(cDebugThreading) {
std::cerr << "[THREAD " << vm->thread_id()
<< " (" << (unsigned int)thread_debug_self() << ") started thread]\n";
}
vm->set_root_stack(reinterpret_cast<uintptr_t>(&calculate_stack), THREAD_STACK_SIZE);
vm->thread->init_lock_.unlock();
vm->shared.tool_broker()->thread_start(state);
Object* ret = vm->thread->runner_(state);
vm->shared.tool_broker()->thread_stop(state);
if(!ret) {
if(vm->thread_state()->raise_reason() == cExit) {
vm->shared.env()->halt_and_exit(state);
}
}
vm->thread->init_lock_.lock();
GCTokenImpl gct;
std::list<ObjectHeader*>& los = vm->locked_objects();
for(std::list<ObjectHeader*>::iterator i = los.begin();
i != los.end();
++i) {
(*i)->unlock_for_terminate(state, gct);
}
NativeMethod::cleanup_thread(state);
vm->thread->alive(state, cFalse);
vm->thread->cleanup();
vm->thread->init_lock_.unlock();
// Clear the call_frame, so that if we wait for GC going independent,
// the GC doesn't see pointers into now-unallocated CallFrames
vm->set_call_frame(0);
vm->shared.gc_independent(state);
vm->shared.clear_critical(state);
VM::discard(state, vm);
if(cDebugThreading) {
std::cerr << "[LOCK thread " << vm->thread_id() << " exited]\n";
}
return 0;
}
Object* Thread::fork(STATE) {
pthread_attr_t attrs;
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, THREAD_STACK_SIZE);
pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
int error = pthread_create(&vm_->os_thread(), &attrs, in_new_thread, (void*)vm_);
if(error) {
Exception::thread_error(state, strerror(error));
}
return cNil;
}
int Thread::fork_attached(STATE) {
pthread_attr_t attrs;
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, THREAD_STACK_SIZE);
return pthread_create(&vm_->os_thread(), &attrs, in_new_thread, (void*)vm_);
}
Object* Thread::pass(STATE, CallFrame* calling_environment) {
atomic::pause();
return cNil;
}
Array* Thread::list(STATE) {
return state->shared().vm_threads(state);
}
Object* Thread::priority(STATE) {
pthread_t id = vm_->os_thread();
int _policy;
struct sched_param params;
if(pthread_getschedparam(id, &_policy, ¶ms) == 0) {
return Fixnum::from(params.sched_priority);
}
return cNil;
}
Object* Thread::raise(STATE, GCToken gct, Exception* exc) {
init_lock_.lock();
Thread* self = this;
OnStack<2> os(state, self, exc);
VM* vm = self->vm_;
if(!vm) {
self->init_lock_.unlock();
return cNil;
}
vm->register_raise(state, exc);
vm->wakeup(state, gct);
self->init_lock_.unlock();
return exc;
}
Object* Thread::set_priority(STATE, Fixnum* new_priority) {
return new_priority;
}
Thread* Thread::wakeup(STATE, GCToken gct) {
init_lock_.lock();
Thread* self = this;
OnStack<1> os(state, self);
VM* vm = self->vm_;
if(alive() == cFalse || !vm) {
self->init_lock_.unlock();
return force_as<Thread>(Primitives::failure());
}
vm->wakeup(state, gct);
self->init_lock_.unlock();
return self;
}
Tuple* Thread::context(STATE) {
thread::SpinLock::LockGuard lg(init_lock_);
VM* vm = vm_;
if(!vm) return nil<Tuple>();
CallFrame* cf = vm->saved_call_frame()->top_ruby_frame();
VariableScope* scope = cf->promote_scope(state);
return Tuple::from(state, 3, Fixnum::from(cf->ip()), cf->cm, scope);
}
Array* Thread::mri_backtrace(STATE, GCToken gct, CallFrame* calling_environment) {
thread::SpinLock::LockGuard lg(init_lock_);
VM* vm = vm_;
if(!vm) return nil<Array>();
StopTheWorld stop(state, gct, calling_environment);
CallFrame* cf = vm->saved_call_frame();
return Location::mri_backtrace(state, cf);
}
void Thread::cleanup() {
vm_ = NULL;
}
void Thread::init_lock() {
init_lock_.init();
}
Object* Thread::join(STATE, GCToken gct, CallFrame* calling_environment) {
state->set_call_frame(calling_environment);
init_lock_.lock();
VM* vm = vm_;
if(!vm) {
init_lock_.unlock();
return cTrue;
}
pthread_t id = vm->os_thread();
if(cDebugThreading) {
std::cerr << "[THREAD joining " << thread_debug_id(id) << "]\n";
}
init_lock_.unlock();
state->gc_independent(gct);
void* val;
int err = pthread_join(id, &val);
state->gc_dependent();
switch(err) {
case 0:
break;
case EDEADLK:
std::cerr << "Join deadlock: " << thread_debug_id(id) << "/" << thread_debug_self() << "\n";
break;
case EINVAL:
std::cerr << "Invalid thread id: " << thread_debug_id(id) << "\n";
break;
case ESRCH:
// This means that the thread finished execution and detached
// itself. We treat this as having joined it.
break;
}
return cTrue;
}
Object* Thread::set_critical(STATE, Object* obj) {
if(CBOOL(obj)) {
state->shared().set_critical(state);
return cTrue;
} else {
state->shared().clear_critical(state);
return cFalse;
}
}
}
|
#ifndef CAFFE_CLASS_BALANCED_SIGMOID_CROSS_ENTROPY_ATTENTION_LOSS_LAYER_HPP_
#define CAFFE_CLASS_BALANCED_SIGMOID_CROSS_ENTROPY_ATTENTION_LOSS_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/layers/loss_layer.hpp"
#include "caffe/layers/sigmoid_layer.hpp"
namespace caffe {
//By Guoxia Wang 2018/03/15
template <typename Dtype>
class ClassBalancedSigmoidCrossEntropyAttentionLossLayer : public LossLayer<Dtype> {
public:
explicit ClassBalancedSigmoidCrossEntropyAttentionLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param),
sigmoid_output_(new Blob<Dtype>()) {
LayerParameter param_t = param;
param_t.clear_loss_weight();
sigmoid_layer_.reset(new SigmoidLayer<Dtype>(param_t));
}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "ClassBalancedSigmoidCrossEntropyAttentionLoss"; }
virtual inline int ExactNumTopBlobs() const { return -1; }
protected:
/// @copydoc ClassBalancedSigmoidCrossEntropyAttentionLossLayer
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
/// Read the normalization mode parameter and compute the normalizer based
/// on the blob size. If normalization_mode is VALID, the count of valid
/// outputs will be read from valid_count, unless it is -1 in which case
/// all outputs are assumed to be valid.
virtual Dtype get_normalizer(
LossParameter_NormalizationMode normalization_mode, int valid_count);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
/// The internal SigmoidLayer used to map predictions to probabilities.
shared_ptr<SigmoidLayer<Dtype> > sigmoid_layer_;
/// sigmoid_output stores the output of the SigmoidLayer.
shared_ptr<Blob<Dtype> > sigmoid_output_;
/// bottom vector holder to call the underlying SigmoidLayer::Forward
vector<Blob<Dtype>*> sigmoid_bottom_vec_;
/// top vector holder to call the underlying SigmoidLayer::Forward
vector<Blob<Dtype>*> sigmoid_top_vec_;
Dtype alpha_, gamma_, valid_num_, beta_;
Blob<Dtype> scaler_;
bool has_ignore_label_;
/// The label indicating that an instance should be ignored.
int ignore_label_;
/// How to normalize the loss.
LossParameter_NormalizationMode normalization_;
Dtype normalizer_;
int outer_num_, inner_num_;
};
} // namespace caffe
#endif // CAFFE_CLASS_BALANCED_SIGMOID_CROSS_ENTROPY_ATTENTION_LOSS_LAYER_HPP_
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by GS <sgazeos@gmail.com> 31.01.2018
//
#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_zero_fraction)
#include <ops/declarable/CustomOperations.h>
namespace sd {
namespace ops {
CUSTOM_OP_IMPL(zero_fraction, 1, 1, false, 0, 0) {
auto input = INPUT_VARIABLE(0);
auto output = OUTPUT_VARIABLE(0);
REQUIRE_TRUE(output->isScalar(), 0, "Rank output should be scalar");
if(input->isEmpty()){
output->p<double>(0, std::numeric_limits<double>::quiet_NaN());
return Status::OK();
}
int numZeros = 0;
// for (int e = 0; e < input->lengthOf(); e++)
// if ((*input)(e) == T(0))
// numZeros++;
auto countZero = input->reduceNumber(reduce::CountZero);
//nd4j_printf("Zero count is %f for %i elements.", countZero.e<double>(0), input->lengthOf());
//countZero /= double(input->lengthOf());
output->p<double>(0, countZero.e<Nd4jLong>(0) / double(input->lengthOf())); //printIndexedBuffer("Zero count");
return Status::OK();
}
DECLARE_SHAPE_FN(zero_fraction) {
return SHAPELIST(ConstantShapeHelper::getInstance()->scalarShapeInfo(sd::DataType::DOUBLE));
}
DECLARE_TYPES(zero_fraction) {
getOpDescriptor()
->setAllowedInputTypes(sd::DataType::ANY)
->setAllowedOutputTypes({ALL_FLOATS});
}
}
}
#endif
|
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2020, the Ginkgo authors
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 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.
******************************<GINKGO LICENSE>*******************************/
#include "core/components/prefix_sum.hpp"
namespace gko {
namespace kernels {
namespace reference {
template <typename IndexType>
void prefix_sum(std::shared_ptr<const ReferenceExecutor> exec,
IndexType *counts, size_type num_entries)
{
IndexType partial_sum{};
for (IndexType i = 0; i < num_entries; ++i) {
auto nnz = counts[i];
counts[i] = partial_sum;
partial_sum += nnz;
}
}
GKO_INSTANTIATE_FOR_EACH_INDEX_TYPE(GKO_DECLARE_PREFIX_SUM_KERNEL);
// explicitly instantiate for size_type as well, as this is used in the SellP
// format
template void prefix_sum<size_type>(
std::shared_ptr<const ReferenceExecutor> exec, size_type *counts,
size_type num_entries);
} // namespace reference
} // namespace kernels
} // namespace gko
|
// Given a string, find the length of the longest substring without repeating characters.
// Example 1:
// Input: "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
// solution: map or set
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty()) return 0;
int maxcount = 1;
int i = 0;
int temppointer = 0;
unordered_map<char, int> hashmap;
while (i < s.length()) {
if (hashmap.find(s[i]) != hashmap.end()) {
if (temppointer > hashmap[s[i]]) {
maxcount = max(maxcount, i - temppointer + 1);
} else {
temppointer = hashmap[s[i]] + 1;
}
hashmap[s[i]] = i;
i++;
} else {
hashmap[s[i]] = i;
maxcount = max(maxcount, i - temppointer + 1);
i++;
}
}
return maxcount;
}
};
|
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The Easynodecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "masternode.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "protocol.h"
// Keep track of the active Masternode
CActiveMasternode activeMasternode;
void CActiveMasternode::ManageState(CConnman& connman)
{
LogPrint("masternode", "CActiveMasternode::ManageState -- Start\n");
if(!fMasterNode) {
LogPrint("masternode", "CActiveMasternode::ManageState -- Not a masternode, returning\n");
return;
}
if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus());
return;
}
if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) {
nState = ACTIVE_MASTERNODE_INITIAL;
}
LogPrint("masternode", "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
if(eType == MASTERNODE_UNKNOWN) {
ManageStateInitial(connman);
}
if(eType == MASTERNODE_REMOTE) {
ManageStateRemote();
}
SendMasternodePing(connman);
}
std::string CActiveMasternode::GetStateString() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL: return "INITIAL";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW";
case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE";
case ACTIVE_MASTERNODE_STARTED: return "STARTED";
default: return "UNKNOWN";
}
}
std::string CActiveMasternode::GetStatus() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations);
case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason;
case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started";
default: return "Unknown";
}
}
std::string CActiveMasternode::GetTypeString() const
{
std::string strType;
switch(eType) {
case MASTERNODE_REMOTE:
strType = "REMOTE";
break;
default:
strType = "UNKNOWN";
break;
}
return strType;
}
bool CActiveMasternode::SendMasternodePing(CConnman& connman)
{
if(!fPingerEnabled) {
LogPrint("masternode", "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString());
return false;
}
if(!mnodeman.Has(outpoint)) {
strNotCapableReason = "Masternode not in masternode list";
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason);
return false;
}
CMasternodePing mnp(outpoint);
mnp.nSentinelVersion = nSentinelVersion;
mnp.fSentinelIsCurrent =
(abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_WATCHDOG_MAX_SECONDS);
if(!mnp.Sign(keyMasternode, pubKeyMasternode)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n");
return false;
}
// Update lastPing for our masternode in Masternode list
if(mnodeman.IsMasternodePingedWithin(outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n");
return false;
}
mnodeman.SetMasternodeLastPing(outpoint, mnp);
LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", outpoint.ToStringShort());
mnp.Relay(connman);
return true;
}
bool CActiveMasternode::UpdateSentinelPing(int version)
{
nSentinelVersion = version;
nSentinelPingTime = GetAdjustedTime();
return true;
}
void CActiveMasternode::ManageStateInitial(CConnman& connman)
{
LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
// Check that our local network configuration is correct
if (!fListen) {
// listen option is probably overwritten by smth else, no good
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// First try to find whatever local address is specified by externalip option
bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);
if(!fFoundLocal) {
bool empty = true;
// If we have some peers, let's try to find our local address from one of them
connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) {
empty = false;
if (pnode->addr.IsIPv4())
fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);
return !fFoundLocal;
});
// nothing and no live connections, can't do anything for now
if (empty) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
}
if(!fFoundLocal) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(service.GetPort() != mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
} else if(service.GetPort() == mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
if(!connman.ConnectNode(CAddress(service, NODE_NETWORK), NULL, true)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// Default to REMOTE
eType = MASTERNODE_REMOTE;
LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
}
void CActiveMasternode::ManageStateRemote()
{
LogPrint("masternode", "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n",
GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString());
mnodeman.CheckMasternode(pubKeyMasternode, true);
masternode_info_t infoMn;
if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) {
if(infoMn.nProtocolVersion != PROTOCOL_VERSION) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Invalid protocol version";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(service != infoMn.addr) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently.";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState));
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(nState != ACTIVE_MASTERNODE_STARTED) {
LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n");
outpoint = infoMn.vin.prevout;
service = infoMn.addr;
fPingerEnabled = true;
nState = ACTIVE_MASTERNODE_STARTED;
}
}
else {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode not in masternode list";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
}
}
|
#include <malloc.h>
#include <string.h>
#include "texheap.h"
void TexHeap::Create(int page_cap_x, int page_cap_y, int numtex, const TexDesc* texdesc, int page_user_bytes)
{
allocs = 0;
cap_x = page_cap_x;
cap_y = page_cap_y;
user = page_user_bytes;
head = 0;
tail = 0;
// item_w = alloc_w;
// item_h = alloc_h;
// ifmt = internal_format;
num = numtex;
memcpy(tex, texdesc, num * sizeof(TexDesc));
}
void TexHeap::Destroy()
{
if (!head)
return;
int cap = cap_x * cap_y;
TexPage* p = head;
while (p!=tail)
{
TexPage* n = p->next;
glDeleteTextures(num, p->tex);
for (int i = 0; i < cap; i++)
free(p->alloc[i]);
free(p);
p = n;
}
cap = allocs % cap;
glDeleteTextures(num, p->tex);
for (int i = 0; i < cap; i++)
free(p->alloc[i]);
free(p);
}
TexAlloc* TexHeap::Alloc(const TexData data[])
{
int cap = cap_x * cap_y;
TexPage* page = tail;
if (allocs % cap == 0)
{
int alloc_bytes = sizeof(TexPage) + sizeof(TexAlloc*)*(cap - 1);
int page_bytes = alloc_bytes + user;
page = (TexPage*)malloc(page_bytes);
if (!page)
return 0;
page->user = (char*)page + alloc_bytes;
memset(page->user, 0, user);
page->heap = this;
page->prev = tail;
page->next = 0;
if (tail)
tail->next = page;
else
head = page;
tail = page;
glCreateTextures(GL_TEXTURE_2D, num, page->tex);
for (int t = 0; t < num; t++)
{
glTextureStorage2D(page->tex[t], 1, tex[t].ifmt, cap_x * tex[t].item_w, cap_y * tex[t].item_h);
glTextureParameteri(page->tex[t], GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureParameteri(page->tex[t], GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTextureParameteri(page->tex[t], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(page->tex[t], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
}
int on_page = allocs % cap;
TexAlloc* a = (TexAlloc*)malloc(sizeof(TexAlloc));
page->alloc[on_page] = a;
a->page = page;
a->x = on_page % cap_x;
a->y = on_page / cap_x;
allocs++;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for (int t = 0; t < num; t++)
{
glTextureSubImage2D(page->tex[t], 0, a->x * tex[t].item_w, a->y * tex[t].item_h,
tex[t].item_w, tex[t].item_h, data[t].format, data[t].type, data[t].data);
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
return a;
}
void TexAlloc::Free()
{
TexHeap* h = page->heap;
int cap = h->cap_x * h->cap_y;
int on_page = y * h->cap_x + x;
// not last alloc on last page?
if (page != h->tail || on_page != (h->allocs-1) % cap)
{
TexAlloc* last = h->tail->alloc[(h->allocs-1) % cap];
for (int t = 0; t < h->num; t++)
{
glCopyImageSubData(
last->page->tex[t], GL_TEXTURE_2D, 0, last->x * h->tex[t].item_w, last->y * h->tex[t].item_h, 0,
page->tex[t], GL_TEXTURE_2D, 0, x * h->tex[t].item_w, y * h->tex[t].item_h, 0,
h->tex[t].item_w, h->tex[t].item_h, 1);
}
page->alloc[on_page] = last;
last->page = page;
last->x = x;
last->y = y;
}
h->allocs--;
free(this);
// now check if we can delete last page
if (h->allocs % cap == 0)
{
glDeleteTextures(h->num, h->tail->tex);
if (h->tail->prev)
h->tail->prev->next = 0;
else
h->head = 0;
h->tail = h->tail->prev;
free(h->tail);
}
}
void TexAlloc::Update(int first, int count, const TexData data[])
{
TexHeap* h = page->heap;
int end = first + count;
end = h->num < end ? h->num : end;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for (int t = first; t < end; t++)
{
glTextureSubImage2D(page->tex[t], 0, x * h->tex[t].item_w, y * h->tex[t].item_h,
h->tex[t].item_w, h->tex[t].item_h, data[t-first].format, data[t-first].type, data[t-first].data);
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2019 The MktCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet.h"
#include <QDebug>
#include <QFont>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
struct AddressTableEntry {
enum Type {
Sending,
Receiving,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {}
};
struct AddressTableEntryLessThan {
bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry& a, const QString& b) const
{
return a.address < b;
}
bool operator()(const QString& a, const AddressTableEntry& b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet* wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel* parent;
AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) {
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry* index(int idx)
{
if (idx >= 0 && idx < cachedAddressTable.size()) {
return &cachedAddressTable[idx];
} else {
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case Label:
if (rec->label.isEmpty() && role == Qt::DisplayRole) {
return tr("(no label)");
} else {
return rec->label;
}
case Address:
return rec->address;
}
} else if (role == Qt::FontRole) {
QFont font;
if (index.column() == Address) {
font = GUIUtil::bitcoinAddressFont();
}
return font;
} else if (role == TypeRole) {
switch (rec->type) {
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default:
break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if (role == Qt::EditRole) {
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
if (index.column() == Label) {
// Do nothing, if old label == new label
if (rec->label == value.toString()) {
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if (index.column() == Address) {
CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if (boost::get<CNoDestination>(&newAddress)) {
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if (newAddress == curAddress) {
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if (wallet->mapAddressBook.count(newAddress)) {
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if (rec->type == AddressTableEntry::Sending) {
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole && section < columns.size()) {
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return 0;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if (rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column() == Label)) {
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
AddressTableEntry* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
} else {
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString& address,
const QString& label,
bool isMine,
const QString& purpose,
int status)
{
// Update address book model from MktCoin core
priv->updateEntry(address, label, isMine, purpose, status);
}
QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if (type == Send) {
if (!walletModel->validateAddress(address)) {
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) {
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
} else if (type == Receive) {
// Generate a new address to associate with given label
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey)) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if (!wallet->GetKeyFromPool(newKey)) {
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CBitcoinAddress(newKey.GetID()).ToString();
} else {
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent)
{
Q_UNUSED(parent);
AddressTableEntry* rec = priv->index(row);
if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) {
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString& address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end()) {
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString& address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if (lst.isEmpty()) {
return -1;
} else {
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex()));
}
|
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#ifndef DOMAINEXTERNALSYSTEMS_EXTERNALPROGRAMSTATUS_ENUM_H_
#define DOMAINEXTERNALSYSTEMS_EXTERNALPROGRAMSTATUS_ENUM_H_
#include <DomainExternalSystems/enumExternalProgramStatusData.hh>
#include <string>
#include <iostream>
#include <locale>
// SmartUtils used in from_xml method
#include "smartKnuthMorrisPratt.hh"
namespace DomainExternalSystems {
class ExternalProgramStatus {
private:
DomainExternalSystemsIDL::ExternalProgramStatus value;
public:
enum ENUM_ExternalProgramStatus {
ENUM_VALUE_UNDEFINED = 0,
UNKOWN = 1,
NOTRUNNING = 2,
RUNNING = 3,
ABORTED = 4,
FINSHED = 5,
PAUSED = 6
};
// default constructor
ExternalProgramStatus() {
value = ENUM_VALUE_UNDEFINED;
}
// copy constructor for enum type
ExternalProgramStatus(ENUM_ExternalProgramStatus e) {
value = static_cast<int>(e);
}
// copy constructor for IDL type (which is typically int)
ExternalProgramStatus(DomainExternalSystemsIDL::ExternalProgramStatus e) {
value = e;
}
//const DomainExternalSystemsIDL::ExternalProgramStatus& get() const { return value; }
// ENUM operator
operator ENUM_ExternalProgramStatus() const {
return static_cast<ENUM_ExternalProgramStatus>(value);
}
// compare operator
bool operator == (const ENUM_ExternalProgramStatus t) const {
return this->value == t;
}
std::string to_string(const bool &use_fqn=true) const {
std::string result = "";
if(use_fqn == true) {
result = "ExternalProgramStatus::";
}
switch (value) {
case UNKOWN:
result += "UNKOWN";
break;
case NOTRUNNING:
result += "NOTRUNNING";
break;
case RUNNING:
result += "RUNNING";
break;
case ABORTED:
result += "ABORTED";
break;
case FINSHED:
result += "FINSHED";
break;
case PAUSED:
result += "PAUSED";
break;
default:
result += "ENUM_VALUE_UNDEFINED";
break;
};
return result;
}
static ExternalProgramStatus from_string(const std::string &value) {
std::string input = value;
std::locale l;
for(auto &c: input) {
// convert all characters to lower case (so string comparison works regardless of small/capital letters)
c = std::tolower(c,l);
}
std::string base_name = "externalprogramstatus::";
if(input.compare(0, base_name.length(), base_name) == 0) {
// remove basename from comparing the actual enumeration
input.erase(0,base_name.length());
}
if(input == "unkown"){
return ExternalProgramStatus(UNKOWN);
}
if(input == "notrunning"){
return ExternalProgramStatus(NOTRUNNING);
}
if(input == "running"){
return ExternalProgramStatus(RUNNING);
}
if(input == "aborted"){
return ExternalProgramStatus(ABORTED);
}
if(input == "finshed"){
return ExternalProgramStatus(FINSHED);
}
if(input == "paused"){
return ExternalProgramStatus(PAUSED);
}
// default (if none of the preceding options match)
return ExternalProgramStatus();
}
// helper method to easily implement output stream
void to_ostream(std::ostream &os = std::cout) const {
os << to_string();
}
// convert to xml stream
void to_xml(std::ostream &os, const std::string &indent = "") const {
os << indent << "<value>" << value << "</value>";
}
// restore from xml stream
void from_xml(std::istream &is) {
static const Smart::KnuthMorrisPratt kmp_value("<value>");
if(kmp_value.search(is)) {
is >> value;
}
}
};
inline std::ostream &operator<<(std::ostream &os, const ExternalProgramStatus &e)
{
e.to_ostream(os);
return os;
}
};
#endif
|
// TC: O(N) SC: O(N)
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution
{
public:
//Function to find if there is a celebrity in the party or not.
int celebrity(vector<vector<int> >& M, int n)
{
stack<int> s;
// push all
for(int i = 0 ; i < n ; i++)
s.push(i);
// fine tune potential candidate
while(s.size() > 1){
int a = s.top();
s.pop();
int b = s.top();
s.pop();
if(M[a][b] ==1)
s.push(b);
else
s.push(a);
}
// This candidate is the potential candidate for the celerbrity
int candidate = s.top();
// now check rows first
int rowcnt = 0;
for(int i = 0; i < n ; i++){
if(M[candidate][i] == 0)
rowcnt++;
}
// now check column of the candidate
int colcnt = 0;
for(int i = 0; i < n ; i++){
if(M[i][candidate] == 1)
colcnt++;
}
// last check
if(rowcnt == n && colcnt == n-1)
return candidate;
else
return -1;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<vector<int> > M( n , vector<int> (n, 0));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>M[i][j];
}
}
Solution ob;
cout<<ob.celebrity(M,n)<<endl;
}
}
/////////////////////////////////////////////////////////////////////////////////
/// Two Pointers Approach
// TC : O(N) SC: O(1)
class Solution
{
public:
//Function to find if there is a celebrity in the party or not.
int celebrity(vector<vector<int> >& M, int n)
{
int i = 0;
int j = n-1;
while(i < j){
if(M[i][j] == 1)
i++;
else
j--;
}
int candidate = i;
for(i = 0; i< n; i++){
if(i != candidate){
if(M[i][candidate] == 0|| M[candidate][i])
return -1;
}
}
return candidate;
}
};
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
#define printf OutputDebugStringF
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
static std::string strRPCUserColonPass;
const Object emptyobj;
void ThreadRPCServer3(void* parg);
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 20268 : 10268;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64_t AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64_t nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64_t amount)
{
return (double)amount / (double)COIN;
}
//
// Utilities: convert hex-encoded Values
// (throws error if not hex).
//
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach´ boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop Abncoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Abncoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name function safemd unlocked
// ------------------------ ----------------------- ------ --------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getbestblockhash", &getbestblockhash, true, false },
{ "getblockcount", &getblockcount, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "getdifficulty", &getdifficulty, true, false },
{ "getinfo", &getinfo, true, false },
{ "getsubsidy", &getsubsidy, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getstakinginfo", &getstakinginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getnewpubkey", &getnewpubkey, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "validatepubkey", &validatepubkey, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "addredeemscript", &addredeemscript, false, false },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockbynumber", &getblockbynumber, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "getworkex", &getworkex, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, false, false },
{ "dumpwallet", &dumpwallet, true, false },
{ "importwallet", &importwallet, false, false },
{ "importprivkey", &importprivkey, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "decodescript", &decodescript, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "getcheckpoint", &getcheckpoint, true, false },
{ "reservebalance", &reservebalance, false, true},
{ "checkwallet", &checkwallet, false, true},
{ "repairwallet", &repairwallet, false, true},
{ "resendtx", &resendtx, false, true},
{ "makekeypair", &makekeypair, false, true},
{ "sendalert", &sendalert, false, false},
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: abncoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: abncoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: abncoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ThreadRPCServer(void* parg)
{
// Make this thread recognisable as the RPC listener
RenameThread("abncoin-rpclist");
try
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
ThreadRPCServer2(parg);
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(NULL, "ThreadRPCServer()");
}
printf("ThreadRPCServer exited\n");
}
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted
&& acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn
&& !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
// start HTTP client thread
else if (!NewThread(ThreadRPCServer3, conn)) {
printf("Failed to create RPC server client thread\n");
delete conn;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use abncoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=abncoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Abncoin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
const bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
boost::signals2::signal<void ()> StopRequests;
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, _("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
while (!fShutdown)
io_service.run_one();
vnThreadsRunning[THREAD_RPCLISTENER]++;
StopRequests();
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
static CCriticalSection cs_THREAD_RPCHANDLER;
void ThreadRPCServer3(void* parg)
{
// Make this thread recognisable as the RPC handler
RenameThread("abncoin-rpchand");
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]++;
}
AcceptedConnection *conn = (AcceptedConnection *) parg;
bool fRun = true;
while (true)
{
if (fShutdown || !fRun)
{
conn->close();
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
--vnThreadsRunning[THREAD_RPCHANDLER];
}
return;
}
map<string, string> mapHeaders;
string strRequest;
ReadHTTP(conn->stream(), mapHeaders, strRequest);
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]--;
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->unlocked)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockbynumber" && n > 0) ConvertTo<int64_t>(params[0]);
if (strMethod == "getblockbynumber" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "sendalert" && n > 2) ConvertTo<int64_t>(params[2]);
if (strMethod == "sendalert" && n > 3) ConvertTo<int64_t>(params[3]);
if (strMethod == "sendalert" && n > 4) ConvertTo<int64_t>(params[4]);
if (strMethod == "sendalert" && n > 5) ConvertTo<int64_t>(params[5]);
if (strMethod == "sendalert" && n > 6) ConvertTo<int64_t>(params[6]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<int64_t>(params[2]);
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "keypoolrefill" && n > 0) ConvertTo<int64_t>(params[0]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
|
/*!
This program is an example of steps to allow embedded database connectivity to a C++ program.
A database containing simple notes with logging function was implemented.
*/
#include <iostream>
#include <map>
#include "Poco/Data/Session.h"
#include "Poco/Data/SQLite/Connector.h"
#include "note.h"
using namespace Poco::Data::Keywords;
using namespace Poco::Data;
using Poco::Data::Session;
using Poco::Data::Statement;
int main(int argc, char* argv[]) {
/// register connector and create a session
/// sqlite3.db is a default database file
Poco::Data::SQLite::Connector::registerConnector();
Session session("SQLite", "assets/sqlite3.db");
/// turn on FOREIGN KEYS support
session << "PRAGMA foreign_keys = ON", now;
/// create tables (Notes and Logs)
session << "DROP TABLE IF EXISTS notes", now;
session << "CREATE TABLE notes("
"uid INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT)",
now;
session << "DROP TABLE IF EXISTS logs", now;
session << "CREATE TABLE logs("
"note_uid INTEGER,"
"timestamp INTEGER,"
"action INTEGER,"
"CONSTRAINT note_action UNIQUE (note_uid,timestamp,action),"
"FOREIGN KEY (note_uid) REFERENCES notes(uid) ON DELETE CASCADE)",
now;
/// insert a note
std::string title = "This is the first note in the database";
session << "INSERT INTO notes(title) VALUES (?)", use(title), now;
/// insert corresponding log record
Poco::UInt64 note_uid;
Poco::UInt8 action = 0; /// i.e. note creation
session << "SELECT last_insert_rowid()", into(note_uid), now;
Poco::Timestamp timestamp;
timestamp.update();
Poco::UInt64 timestamp_value = timestamp.epochMicroseconds();
session << "INSERT INTO logs VALUES(?,?,?)",
use(note_uid),
use(timestamp_value),
use(action),
now;
/// update the note
title = "This is the first note UPDATED";
session << "UPDATE notes SET title = (?) WHERE uid = (?)",
use(title),
use(note_uid),
now;
/// log this update
action = 1; /// i.e. update
timestamp.update();
timestamp_value = timestamp.epochMicroseconds();
session << "INSERT INTO logs VALUES(?,?,?)",
use(note_uid),
use(timestamp_value),
use(action),
now;
/// get notes from the database to Note objects with STL
std::vector<Note> notes;
session << "SELECT uid, title FROM notes", into(notes), now;
/// let's work with the first row
Note note = notes.at(0);
Log logs;
note.setlog_ptr(logs);
note_uid = note.getuid();
/// get all logs for note with uid = 1
session << "SELECT * FROM logs WHERE note_uid = (?)", into(logs), use(note_uid), now;
note.print_log();
system("pause");
}
|
#ifndef ODEPLUS_INCLUDE_ODEPLUS_VIZ_VIEW_HPP_
#define ODEPLUS_INCLUDE_ODEPLUS_VIZ_VIEW_HPP_
#include <memory>
namespace odeplus
{
namespace viz
{
class View
{
public:
explicit View(float x, float y, float z, float roll, float pitch, float yaw);
private:
float xyz_[3];
float rpy_[3];
};
using ViewPtr = std::shared_ptr<View>;
}
}
#endif // ODEPLUS_INCLUDE_ODEPLUS_VIZ_VIEW_HPP_
|
// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <qt/utilitydialog.h>
#include <qt/forms/ui_helpmessagedialog.h>
#include <qt/bitcoingui.h>
#include <qt/clientmodel.h>
#include <qt/guiconstants.h>
#include <qt/intro.h>
#ifdef ENABLE_BIP70
#include <qt/paymentrequestplus.h>
#endif
#include <qt/guiutil.h>
#include <clientversion.h>
#include <init.h>
#include <interfaces/node.h>
#include <util/system.h>
#include <util/strencodings.h>
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QTextTable>
#include <QTextCursor>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(interfaces::Node& node, QWidget *parent, bool about) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
QString version = QString{PACKAGE_NAME} + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambiguous.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
if (about)
{
setWindowTitle(tr("About %1").arg(PACKAGE_NAME));
std::string licenseInfo = LicenseInfo();
/// HTML-format the license message from the core
QString licenseInfoHTML = QString::fromStdString(LicenseInfo());
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n", "<br>");
ui->aboutMessage->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + QString::fromStdString(FormatParagraph(licenseInfo));
ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
ui->aboutMessage->setWordWrap(true);
ui->helpMessage->setVisible(false);
} else {
setWindowTitle(tr("Command-line options"));
QString header = "Usage: ruicoin-qt [command-line options] \n";
QTextCursor cursor(ui->helpMessage->document());
cursor.insertText(version);
cursor.insertBlock();
cursor.insertText(header);
cursor.insertBlock();
std::string strUsage = gArgs.GetHelpMessage();
QString coreOptions = QString::fromStdString(strUsage);
text = version + "\n\n" + header + "\n" + coreOptions;
QTextTableFormat tf;
tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
tf.setCellPadding(2);
QVector<QTextLength> widths;
widths << QTextLength(QTextLength::PercentageLength, 35);
widths << QTextLength(QTextLength::PercentageLength, 65);
tf.setColumnWidthConstraints(widths);
QTextCharFormat bold;
bold.setFontWeight(QFont::Bold);
for (const QString &line : coreOptions.split("\n")) {
if (line.startsWith(" -"))
{
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::PreviousCell);
cursor.movePosition(QTextCursor::NextRow);
cursor.insertText(line.trimmed());
cursor.movePosition(QTextCursor::NextCell);
} else if (line.startsWith(" ")) {
cursor.insertText(line.trimmed()+' ');
} else if (line.size() > 0) {
//Title of a group
if (cursor.currentTable())
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::Down);
cursor.insertText(line.trimmed(), bold);
cursor.insertTable(1, 2, tf);
}
}
ui->helpMessage->moveCursor(QTextCursor::Start);
ui->scrollArea->setVisible(false);
ui->aboutLogo->setVisible(false);
}
}
HelpMessageDialog::~HelpMessageDialog()
{
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
tfm::format(std::cout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f):
QWidget(parent, f)
{
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("%1 is shutting down...").arg(PACKAGE_NAME) + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
QWidget *ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return nullptr;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new ShutdownWindow();
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
return shutdownWindow;
}
void ShutdownWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
}
|
/*
* Copyright 2014-2015 Matus Chochlik. 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)
*/
//[oglplus_dsa_vertex_array_1
template <>
class __ObjectOps<__tag_DirectState, __tag_VertexArray>
: public __ObjZeroOps<__tag_DirectState, __tag_VertexArray> /*<
Indirectly inherits from __ObjCommonOps_VertexArray<__tag_VertexArray>.
>*/
{
public:
ObjectOps& ElementBuffer(__BufferName buffer); /*<
Bind buffer to [^this] VAO's element buffer binding point.
See [glfunc VertexArrayElementBuffer].
>*/
ObjectOps& EnableVertexAttrib(__VertexAttribSlot location); /*<
Disable the specified vertex attribute array.
See [glfunc EnableVertexArrayAttrib].
>*/
ObjectOps& DisableVertexAttrib(__VertexAttribSlot location); /*<
Enable the specified vertex attribute array.
See [glfunc DisableVertexArrayAttrib].
>*/
};
//]
//[oglplus_dsa_vertex_array_def
typedef __ObjectOps<__tag_DirectState, __tag_VertexArray>
DSAVertexArrayOps;
typedef __Object<DSAVertexArrayOps> DSAVertexArray;
//]
|
// Copyright (c) 2014 Thomas Heller
//
// SPDX-License-Identifier: BSL-1.0
// 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 <hpx/memory/serialization/intrusive_ptr.hpp>
#include <hpx/modules/memory.hpp>
#include <hpx/modules/serialization.hpp>
#include <hpx/modules/testing.hpp>
#include <memory>
#include <vector>
struct A
{
A()
: i(7)
, count(0)
{
}
int i;
int count;
template <typename Archive>
void serialize(Archive& ar, unsigned)
{
ar& i;
}
};
void intrusive_ptr_add_ref(A* a)
{
++a->count;
}
void intrusive_ptr_release(A* a)
{
if (--a->count == 0)
{
delete a;
}
}
void test_intrusive()
{
hpx::intrusive_ptr<A> ip(new A());
hpx::intrusive_ptr<A> op1;
hpx::intrusive_ptr<A> op2;
{
std::vector<char> buffer;
hpx::serialization::output_archive oarchive(buffer);
oarchive << ip << ip;
hpx::serialization::input_archive iarchive(buffer);
iarchive >> op1;
iarchive >> op2;
}
HPX_TEST_EQ(ip->count, 1);
HPX_TEST_NEQ(op1.get(), ip.get());
HPX_TEST_NEQ(op2.get(), ip.get());
HPX_TEST_EQ(op1.get(), op2.get());
HPX_TEST_EQ(op1->i, ip->i);
HPX_TEST_EQ(op1->count, 2);
HPX_TEST_EQ(op2->count, 2);
op1.reset();
HPX_TEST_EQ(op2->count, 1);
HPX_TEST_EQ(op2->i, ip->i);
}
int main()
{
test_intrusive();
return hpx::util::report_errors();
}
|
#include "hilite/hilite.hh"
#include "hilite/hilite_impl.hh"
#include <algorithm>
namespace hl {
namespace {
template <typename Vector>
void sort_uniq(Vector& v) {
std::sort(std::begin(v), std::end(v));
auto last = std::unique(std::begin(v), std::end(v));
v.erase(last, std::end(v));
}
void break_token(tokens& out,
token_t tok,
endlines::const_iterator eol,
endlines::const_iterator const& eol_to)
{
while (eol != eol_to) {
auto const end = eol->offset - eol->size;
if (tok.end <= end) {
out.push_back({ tok.start, tok.end, tok.kind });
return;
}
out.push_back({ tok.start, end, tok.kind });
tok.start = eol->offset;
++eol;
}
out.push_back({ tok.start, tok.end, tok.kind });
}
tokens break_lines(
endlines::const_iterator const& eol_from,
endlines::const_iterator const& eol_to,
tokens::const_iterator from,
tokens::const_iterator const& to)
{
tokens out;
out.reserve(static_cast<size_t>(std::distance(from, to)));
for (auto eol = eol_from; eol != eol_to; ++eol) {
while (from != to && from->start < eol->offset) {
break_token(out, *from, eol, eol_to);
++from;
}
}
out.insert(out.end(), from, to);
return out;
}
}
callback::~callback() = default;
callback::callback() = default;
callback::callback(callback&&) = default;
callback& callback::operator=(callback&&) = default;
void grammar_result::produce_lines(callback& cb, size_t contents_length) {
sort_uniq(endlines_);
sort_uniq(tokens_);
auto broken = break_lines(
std::begin(endlines_), std::end(endlines_),
std::begin(tokens_), std::end(tokens_));
std::sort(std::begin(broken), std::end(broken));
tokens_.clear();
for (size_t i = 1; i < endlines_.size(); ++i) {
auto& prev = endlines_[i - 1];
auto const& curr = endlines_[i];
prev.size = curr.offset - prev.offset - curr.size;
}
{
auto & back = endlines_.back();
back.size = contents_length < back.offset ? 0 : contents_length - back.offset;
}
auto it = std::begin(broken);
auto const end = std::end(broken);
for (auto const& endline : endlines_) {
auto const eol = endline.offset + endline.size;
auto saved_pos = it;
size_t token_count = 0;
size_t prev_end = 0;
bool prev_ws = false;
while (it != end && it->end <= eol) {
++token_count;
const bool is_ws = it->kind == hl::token::whitespace;
if (prev_ws && is_ws && it->start == prev_end)
--token_count;
prev_ws = is_ws;
prev_end = it->end;
++it;
}
tokens line_tokens;
line_tokens.reserve(token_count);
prev_end = 0;
prev_ws = false;
it = saved_pos;
while (it != end && it->end <= eol) {
const bool is_ws = it->kind == hl::token::whitespace;
if (prev_ws && is_ws && it->start == prev_end) {
line_tokens.back().end = it->end;
}
else {
line_tokens.push_back({ it->start, it->end, it->kind });
}
prev_ws = is_ws;
prev_end = it->end;
++it;
}
for (auto& tok : line_tokens) {
tok.start -= endline.offset;
tok.end -= endline.offset;
}
cb.on_line(endline.offset, endline.size, line_tokens);
}
}
}
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_BENCH_MODULE "nt2 boost.simd.operator toolbox - is_equal/simd Mode"
//////////////////////////////////////////////////////////////////////////////
// timing Test behavior of boost.simd.operator components in simd mode
//////////////////////////////////////////////////////////////////////////////
#include <boost/simd/toolbox/operator/include/functions/is_equal.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <nt2/sdk/bench/benchmark.hpp>
#include <nt2/sdk/bench/timing.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <cmath>
typedef NT2_SIMD_DEFAULT_EXTENSION ext_t;
//////////////////////////////////////////////////////////////////////////////
// simd runtime benchmark for functor<is_equal_> from boost.simd.operator
//////////////////////////////////////////////////////////////////////////////
using boost::simd::tag::is_equal_;
//////////////////////////////////////////////////////////////////////////////
// range macro
//////////////////////////////////////////////////////////////////////////////
#define RS(T,V1,V2) (T, (V1) ,(V2))
namespace n1 {
typedef boost::simd::int8_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n2 {
typedef boost::simd::int16_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n3 {
typedef boost::simd::int32_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n4 {
typedef boost::simd::int64_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n5 {
typedef boost::simd::uint8_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n6 {
typedef boost::simd::uint16_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n7 {
typedef boost::simd::uint32_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n8 {
typedef boost::simd::uint64_t T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n9 {
typedef float T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
namespace n10 {
typedef double T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(is_equal_,(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2))(RS(vT,boost::simd::Valmin<T>()/2,boost::simd::Valmax<T>()/2)))
}
#undef RS
|
#include <realm/list.hpp>
#include <realm/table.hpp>
#include <realm/group.hpp>
#include <realm/sync/noinst/server/server_legacy_migration.hpp>
#include <realm/sync/noinst/server/server_history.hpp>
#include <realm/sync/noinst/client_history_impl.hpp>
#include <realm/sync/history.hpp>
#include "test.hpp"
using namespace realm;
using namespace realm::sync;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment variable `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
namespace {
class MyContext : public _impl::ServerHistory::Context {
public:
std::mt19937_64& server_history_get_random() noexcept override final
{
return m_random;
}
private:
std::mt19937_64 m_random;
};
TEST(ServerLegacyMigration_ClientFileToCore6)
{
std::string path = util::File::resolve("client_file_migration_core6.realm", "resources"); // Throws
SHARED_GROUP_TEST_PATH(copy_path);
util::File::copy(path, copy_path);
std::unique_ptr<Replication> history = make_client_replication();
// Upgrade not possible
CHECK_THROW_ANY(DB::create(*history, copy_path));
}
} // unnamed namespace
|
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "shared_test_classes/single_layer/rnn_sequence.hpp"
#include "ngraph/pass/visualize_tree.hpp"
#include "test_utils/cpu_test_utils.hpp"
#include "transformations/op_conversions/bidirectional_sequences_decomposition.hpp"
#include "transformations/op_conversions/convert_sequences_to_tensor_iterator.hpp"
using namespace InferenceEngine;
using namespace CPUTestUtils;
namespace CPULayerTestsDefinitions {
using RNNSequenceCpuSpecificParams = typename std::tuple<LayerTestsDefinitions::RNNSequenceParams, CPUSpecificParams, std::map<std::string, std::string>>;
class RNNSequenceCPUTest : public testing::WithParamInterface<RNNSequenceCpuSpecificParams>,
virtual public LayerTestsUtils::LayerTestsCommon,
public CPUTestsBase {
public:
static std::string getTestCaseName(const testing::TestParamInfo<RNNSequenceCpuSpecificParams> &obj) {
CPUSpecificParams cpuParams;
LayerTestsDefinitions::RNNSequenceParams basicParamsSet;
std::map<std::string, std::string> additionalConfig;
std::tie(basicParamsSet, cpuParams, additionalConfig) = obj.param;
std::ostringstream result;
result << LayerTestsDefinitions::RNNSequenceTest::getTestCaseName(testing::TestParamInfo<LayerTestsDefinitions::RNNSequenceParams>(basicParamsSet, 0));
result << CPUTestsBase::getTestCaseName(cpuParams);
if (!additionalConfig.empty()) {
result << "_PluginConf";
for (auto &item : additionalConfig) {
if (item.second == PluginConfigParams::YES)
result << "_" << item.first << "=" << item.second;
}
}
return result.str();
}
protected:
void SetUp() override {
LayerTestsDefinitions::RNNSequenceParams basicParamsSet;
CPUSpecificParams cpuParams;
std::map<std::string, std::string> additionalConfig;
size_t seq_lengths;
size_t batch;
size_t hidden_size;
size_t input_size;
std::vector<std::string> activations;
std::vector<float> activations_alpha;
std::vector<float> activations_beta;
float clip;
ngraph::op::RecurrentSequenceDirection direction;
InferenceEngine::Precision netPrecision;
std::tie(basicParamsSet, cpuParams, additionalConfig) = this->GetParam();
std::tie(inFmts, outFmts, priority, selectedType) = cpuParams;
std::tie(m_mode, seq_lengths, batch, hidden_size, input_size, activations, clip, direction, netPrecision, targetDevice) = basicParamsSet;
size_t num_directions = direction == ngraph::op::RecurrentSequenceDirection::BIDIRECTIONAL ? 2 : 1;
std::vector<std::vector<size_t>> inputShapes = {
{{batch, seq_lengths, input_size},
{batch, num_directions, hidden_size},
{batch},
{num_directions, hidden_size, input_size},
{num_directions, hidden_size, hidden_size},
{num_directions, hidden_size}},
};
configuration.insert(additionalConfig.begin(), additionalConfig.end());
if (additionalConfig[PluginConfigParams::KEY_ENFORCE_BF16] == PluginConfigParams::YES) {
inPrc = outPrc = Precision::BF16;
} else {
inPrc = outPrc = netPrecision;
}
selectedType += "_";
selectedType += outPrc.name();
m_max_seq_len = seq_lengths;
auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(Precision::FP32);
auto params = ngraph::builder::makeParams(ngPrc, {inputShapes[0], inputShapes[1]});
if (m_mode == ngraph::helpers::SequenceTestsMode::CONVERT_TO_TI_MAX_SEQ_LEN_PARAM
|| m_mode == ngraph::helpers::SequenceTestsMode::CONVERT_TO_TI_RAND_SEQ_LEN_PARAM) {
auto seq_lengths = ngraph::builder::makeParams(ngraph::element::i64, {inputShapes[2]}).at(0);
seq_lengths->set_friendly_name("seq_lengths");
params.push_back(seq_lengths);
}
std::vector<ngraph::Shape> WRB = {inputShapes[3], inputShapes[4], inputShapes[5], inputShapes[2]};
auto rnn_sequence = ngraph::builder::makeRNN(ngraph::helpers::convert2OutputVector(ngraph::helpers::castOps2Nodes(params)),
WRB,
hidden_size,
activations,
{},
{},
clip,
true,
direction,
m_mode);
ngraph::ResultVector results{std::make_shared<ngraph::opset1::Result>(rnn_sequence->output(0)),
std::make_shared<ngraph::opset1::Result>(rnn_sequence->output(1))};
function = makeNgraphFunction(ngPrc, params, rnn_sequence, "rnn_sequence");
if (m_mode != ngraph::helpers::SequenceTestsMode::PURE_SEQ) {
ngraph::pass::Manager manager;
if (direction == ngraph::op::RecurrentSequenceDirection::BIDIRECTIONAL)
manager.register_pass<ngraph::pass::BidirectionalRNNSequenceDecomposition>();
manager.register_pass<ngraph::pass::ConvertRNNSequenceToTensorIterator>();
manager.run_passes(function);
bool ti_found = ngraph::helpers::is_tensor_iterator_exist(function);
EXPECT_EQ(ti_found, true);
} else {
bool ti_found = ngraph::helpers::is_tensor_iterator_exist(function);
EXPECT_EQ(ti_found, false);
}
}
void GenerateInputs() override {
for (const auto &input : executableNetwork.GetInputsInfo()) {
const auto &info = input.second;
auto blob = GenerateInput(*info);
if (input.first == "seq_lengths") {
blob = FuncTestUtils::createAndFillBlob(info->getTensorDesc(), m_max_seq_len, 0);
}
inputs.push_back(blob);
}
}
private:
ngraph::helpers::SequenceTestsMode m_mode;
int64_t m_max_seq_len = 0;
};
TEST_P(RNNSequenceCPUTest, CompareWithRefs) {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
Run();
CheckPluginRelatedResults(executableNetwork, "RNNSeq");
}
namespace {
/* CPU PARAMS */
std::vector<std::map<std::string, std::string>> additionalConfig
= {{{PluginConfigParams::KEY_ENFORCE_BF16, PluginConfigParams::NO}}, {{PluginConfigParams::KEY_ENFORCE_BF16, PluginConfigParams::YES}}};
CPUSpecificParams cpuParams{{ntc, ntc}, {ntc, ntc}, {"ref_any"}, "ref_any"};
CPUSpecificParams cpuParamsBatchSizeOne{{tnc, ntc}, {tnc, tnc}, {"ref_any"}, "ref_any"};
std::vector<ngraph::helpers::SequenceTestsMode> mode{ngraph::helpers::SequenceTestsMode::PURE_SEQ};
// output values increase rapidly without clip, so use only seq_lengths = 2
std::vector<size_t> seq_lengths_zero_clip{2};
std::vector<size_t> batch{10};
std::vector<size_t> batch_size_one{1};
std::vector<size_t> hidden_size{10};
// std::vector<size_t> hidden_size{1, 10};
std::vector<size_t> input_size{10};
std::vector<std::vector<std::string>> activations = {{"relu"}, {"sigmoid"}, {"tanh"}};
// oneDNN supports only zero clip
std::vector<float> clip{0.f};
std::vector<ngraph::op::RecurrentSequenceDirection> direction{ngraph::op::RecurrentSequenceDirection::FORWARD};
std::vector<InferenceEngine::Precision> netPrecisions = {InferenceEngine::Precision::FP32};
INSTANTIATE_TEST_SUITE_P(smoke_RNNSequenceCPU,
RNNSequenceCPUTest,
::testing::Combine(::testing::Combine(::testing::ValuesIn(mode),
::testing::ValuesIn(seq_lengths_zero_clip),
::testing::ValuesIn(batch),
::testing::ValuesIn(hidden_size),
::testing::ValuesIn(input_size),
::testing::ValuesIn(activations),
::testing::ValuesIn(clip),
::testing::ValuesIn(direction),
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_CPU)),
::testing::Values(cpuParams),
::testing::ValuesIn(additionalConfig)),
RNNSequenceCPUTest::getTestCaseName);
INSTANTIATE_TEST_SUITE_P(smoke_RNNSequenceCPUBatchSizeOne,
RNNSequenceCPUTest,
::testing::Combine(::testing::Combine(::testing::ValuesIn(mode),
::testing::ValuesIn(seq_lengths_zero_clip),
::testing::ValuesIn(batch_size_one),
::testing::ValuesIn(hidden_size),
::testing::ValuesIn(input_size),
::testing::ValuesIn(activations),
::testing::ValuesIn(clip),
::testing::ValuesIn(direction),
::testing::ValuesIn(netPrecisions),
::testing::Values(CommonTestUtils::DEVICE_CPU)),
::testing::Values(cpuParamsBatchSizeOne),
::testing::ValuesIn(additionalConfig)),
RNNSequenceCPUTest::getTestCaseName);
} // namespace
} // namespace CPULayerTestsDefinitions
|
#include "ItemShells.h"
ItemShells::ItemShells(int _x, int _y):
x(_x),
y(_y)
{
sprite = new cgf::Sprite();
sprite->load("data/img/buckshot.png");
sprite->scale(1.2, 1.2);
sf::Vector2f vpos = sf::Vector2f();
vpos.x = x;
vpos.y = y;
sprite->setPosition(vpos);
}
ItemShells::~ItemShells(){
if (sprite){
delete sprite;
}
}
void ItemShells::visit(Inventory *iv) {
iv->refillShotgun(8);
}
void ItemShells::draw(cgf::Game* game){
game->getScreen()->draw(*sprite);
}
|
#ifdef PEGASUS_OS_LINUX
#ifndef __UNIX_AUTHENTICATEFORUSE_PRIVATE_H
#define __UNIX_AUTHENTICATEFORUSE_PRIVATE_H
#endif
#endif
|
// Copyright (c) 2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <script/descriptor.h>
#include <chainparams.h> // For Params()
#include <config.h>
#include <key_io.h>
#include <pubkey.h>
#include <script/script.h>
#include <script/standard.h>
#include <span.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <memory>
#include <string>
#include <vector>
namespace {
////////////////////////////////////////////////////////////////////////////
// Internal representation //
////////////////////////////////////////////////////////////////////////////
typedef std::vector<uint32_t> KeyPath;
std::string FormatKeyPath(const KeyPath &path) {
std::string ret;
for (auto i : path) {
ret += strprintf("/%i", (i << 1) >> 1);
if (i >> 31) {
ret += '\'';
}
}
return ret;
}
/** Interface for public key objects in descriptors. */
struct PubkeyProvider {
virtual ~PubkeyProvider() = default;
/** Derive a public key. */
virtual bool GetPubKey(int pos, const SigningProvider &arg, CPubKey &key,
KeyOriginInfo &info) const = 0;
/** Whether this represent multiple public keys at different positions. */
virtual bool IsRange() const = 0;
/** Get the size of the generated public key(s) in bytes (33 or 65). */
virtual size_t GetSize() const = 0;
/** Get the descriptor string form. */
virtual std::string ToString() const = 0;
/**
* Get the descriptor string form including private data (if available in
* arg).
*/
virtual bool ToPrivateString(const SigningProvider &arg,
std::string &out) const = 0;
};
class OriginPubkeyProvider final : public PubkeyProvider {
KeyOriginInfo m_origin;
std::unique_ptr<PubkeyProvider> m_provider;
std::string OriginString() const {
return HexStr(std::begin(m_origin.fingerprint),
std::end(m_origin.fingerprint)) +
FormatKeyPath(m_origin.path);
}
public:
OriginPubkeyProvider(KeyOriginInfo info,
std::unique_ptr<PubkeyProvider> provider)
: m_origin(std::move(info)), m_provider(std::move(provider)) {}
bool GetPubKey(int pos, const SigningProvider &arg, CPubKey &key,
KeyOriginInfo &info) const override {
if (!m_provider->GetPubKey(pos, arg, key, info)) {
return false;
}
std::copy(std::begin(m_origin.fingerprint),
std::end(m_origin.fingerprint), info.fingerprint);
info.path.insert(info.path.begin(), m_origin.path.begin(),
m_origin.path.end());
return true;
}
bool IsRange() const override { return m_provider->IsRange(); }
size_t GetSize() const override { return m_provider->GetSize(); }
std::string ToString() const override {
return "[" + OriginString() + "]" + m_provider->ToString();
}
bool ToPrivateString(const SigningProvider &arg,
std::string &ret) const override {
std::string sub;
if (!m_provider->ToPrivateString(arg, sub)) {
return false;
}
ret = "[" + OriginString() + "]" + std::move(sub);
return true;
}
};
/** An object representing a parsed constant public key in a descriptor. */
class ConstPubkeyProvider final : public PubkeyProvider {
CPubKey m_pubkey;
public:
ConstPubkeyProvider(const CPubKey &pubkey) : m_pubkey(pubkey) {}
bool GetPubKey(int pos, const SigningProvider &arg, CPubKey &key,
KeyOriginInfo &info) const override {
key = m_pubkey;
info.path.clear();
CKeyID keyid = m_pubkey.GetID();
std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint),
info.fingerprint);
return true;
}
bool IsRange() const override { return false; }
size_t GetSize() const override { return m_pubkey.size(); }
std::string ToString() const override {
return HexStr(m_pubkey.begin(), m_pubkey.end());
}
bool ToPrivateString(const SigningProvider &arg,
std::string &ret) const override {
CKey key;
if (!arg.GetKey(m_pubkey.GetID(), key)) {
return false;
}
ret = EncodeSecret(key);
return true;
}
};
enum class DeriveType {
NO,
UNHARDENED,
HARDENED,
};
/** An object representing a parsed extended public key in a descriptor. */
class BIP32PubkeyProvider final : public PubkeyProvider {
CExtPubKey m_extkey;
KeyPath m_path;
DeriveType m_derive;
bool GetExtKey(const SigningProvider &arg, CExtKey &ret) const {
CKey key;
if (!arg.GetKey(m_extkey.pubkey.GetID(), key)) {
return false;
}
ret.nDepth = m_extkey.nDepth;
std::copy(m_extkey.vchFingerprint,
m_extkey.vchFingerprint + sizeof(ret.vchFingerprint),
ret.vchFingerprint);
ret.nChild = m_extkey.nChild;
ret.chaincode = m_extkey.chaincode;
ret.key = key;
return true;
}
bool IsHardened() const {
if (m_derive == DeriveType::HARDENED) {
return true;
}
for (auto entry : m_path) {
if (entry >> 31) {
return true;
}
}
return false;
}
public:
BIP32PubkeyProvider(const CExtPubKey &extkey, KeyPath path,
DeriveType derive)
: m_extkey(extkey), m_path(std::move(path)), m_derive(derive) {}
bool IsRange() const override { return m_derive != DeriveType::NO; }
size_t GetSize() const override { return 33; }
bool GetPubKey(int pos, const SigningProvider &arg, CPubKey &key,
KeyOriginInfo &info) const override {
if (IsHardened()) {
CExtKey extkey;
if (!GetExtKey(arg, extkey)) {
return false;
}
for (auto entry : m_path) {
extkey.Derive(extkey, entry);
}
if (m_derive == DeriveType::UNHARDENED) {
extkey.Derive(extkey, pos);
}
if (m_derive == DeriveType::HARDENED) {
extkey.Derive(extkey, pos | 0x80000000UL);
}
key = extkey.Neuter().pubkey;
} else {
// TODO: optimize by caching
CExtPubKey extkey = m_extkey;
for (auto entry : m_path) {
extkey.Derive(extkey, entry);
}
if (m_derive == DeriveType::UNHARDENED) {
extkey.Derive(extkey, pos);
}
assert(m_derive != DeriveType::HARDENED);
key = extkey.pubkey;
}
CKeyID keyid = m_extkey.pubkey.GetID();
std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint),
info.fingerprint);
info.path = m_path;
if (m_derive == DeriveType::UNHARDENED) {
info.path.push_back(uint32_t(pos));
}
if (m_derive == DeriveType::HARDENED) {
info.path.push_back(uint32_t(pos) | 0x80000000L);
}
return true;
}
std::string ToString() const override {
std::string ret = EncodeExtPubKey(m_extkey) + FormatKeyPath(m_path);
if (IsRange()) {
ret += "/*";
if (m_derive == DeriveType::HARDENED) {
ret += '\'';
}
}
return ret;
}
bool ToPrivateString(const SigningProvider &arg,
std::string &out) const override {
CExtKey key;
if (!GetExtKey(arg, key)) {
return false;
}
out = EncodeExtKey(key) + FormatKeyPath(m_path);
if (IsRange()) {
out += "/*";
if (m_derive == DeriveType::HARDENED) {
out += '\'';
}
}
return true;
}
};
/** A parsed addr(A) descriptor. */
class AddressDescriptor final : public Descriptor {
CTxDestination m_destination;
public:
AddressDescriptor(CTxDestination destination)
: m_destination(std::move(destination)) {}
bool IsRange() const override { return false; }
bool IsSolvable() const override { return false; }
std::string ToString() const override {
return "addr(" + EncodeDestination(m_destination, GetConfig()) + ")";
}
bool ToPrivateString(const SigningProvider &arg,
std::string &out) const override {
out = ToString();
return true;
}
bool Expand(int pos, const SigningProvider &arg,
std::vector<CScript> &output_scripts,
FlatSigningProvider &out) const override {
output_scripts =
std::vector<CScript>{GetScriptForDestination(m_destination)};
return true;
}
};
/** A parsed raw(H) descriptor. */
class RawDescriptor final : public Descriptor {
CScript m_script;
public:
RawDescriptor(CScript script) : m_script(std::move(script)) {}
bool IsRange() const override { return false; }
bool IsSolvable() const override { return false; }
std::string ToString() const override {
return "raw(" + HexStr(m_script.begin(), m_script.end()) + ")";
}
bool ToPrivateString(const SigningProvider &arg,
std::string &out) const override {
out = ToString();
return true;
}
bool Expand(int pos, const SigningProvider &arg,
std::vector<CScript> &output_scripts,
FlatSigningProvider &out) const override {
output_scripts = std::vector<CScript>{m_script};
return true;
}
};
/** A parsed pk(P), pkh(P) descriptor. */
class SingleKeyDescriptor final : public Descriptor {
const std::function<CScript(const CPubKey &)> m_script_fn;
const std::string m_fn_name;
std::unique_ptr<PubkeyProvider> m_provider;
public:
SingleKeyDescriptor(std::unique_ptr<PubkeyProvider> prov,
const std::function<CScript(const CPubKey &)> &fn,
const std::string &name)
: m_script_fn(fn), m_fn_name(name), m_provider(std::move(prov)) {}
bool IsRange() const override { return m_provider->IsRange(); }
bool IsSolvable() const override { return true; }
std::string ToString() const override {
return m_fn_name + "(" + m_provider->ToString() + ")";
}
bool ToPrivateString(const SigningProvider &arg,
std::string &out) const override {
std::string ret;
if (!m_provider->ToPrivateString(arg, ret)) {
return false;
}
out = m_fn_name + "(" + std::move(ret) + ")";
return true;
}
bool Expand(int pos, const SigningProvider &arg,
std::vector<CScript> &output_scripts,
FlatSigningProvider &out) const override {
CPubKey key;
KeyOriginInfo info;
if (!m_provider->GetPubKey(pos, arg, key, info)) {
return false;
}
output_scripts = std::vector<CScript>{m_script_fn(key)};
out.origins.emplace(key.GetID(), std::move(info));
out.pubkeys.emplace(key.GetID(), key);
return true;
}
};
CScript P2PKHGetScript(const CPubKey &pubkey) {
return GetScriptForDestination(pubkey.GetID());
}
CScript P2PKGetScript(const CPubKey &pubkey) {
return GetScriptForRawPubKey(pubkey);
}
/** A parsed multi(...) descriptor. */
class MultisigDescriptor : public Descriptor {
int m_threshold;
std::vector<std::unique_ptr<PubkeyProvider>> m_providers;
public:
MultisigDescriptor(int threshold,
std::vector<std::unique_ptr<PubkeyProvider>> providers)
: m_threshold(threshold), m_providers(std::move(providers)) {}
bool IsRange() const override {
for (const auto &p : m_providers) {
if (p->IsRange()) {
return true;
}
}
return false;
}
bool IsSolvable() const override { return true; }
std::string ToString() const override {
std::string ret = strprintf("multi(%i", m_threshold);
for (const auto &p : m_providers) {
ret += "," + p->ToString();
}
return std::move(ret) + ")";
}
bool ToPrivateString(const SigningProvider &arg,
std::string &out) const override {
std::string ret = strprintf("multi(%i", m_threshold);
for (const auto &p : m_providers) {
std::string sub;
if (!p->ToPrivateString(arg, sub)) {
return false;
}
ret += "," + std::move(sub);
}
out = std::move(ret) + ")";
return true;
}
bool Expand(int pos, const SigningProvider &arg,
std::vector<CScript> &output_scripts,
FlatSigningProvider &out) const override {
std::vector<std::pair<CPubKey, KeyOriginInfo>> entries;
entries.reserve(m_providers.size());
// Construct temporary data in `entries`, to avoid producing output in
// case of failure.
for (const auto &p : m_providers) {
entries.emplace_back();
if (!p->GetPubKey(pos, arg, entries.back().first,
entries.back().second)) {
return false;
}
}
std::vector<CPubKey> pubkeys;
pubkeys.reserve(entries.size());
for (auto &entry : entries) {
pubkeys.push_back(entry.first);
out.origins.emplace(entry.first.GetID(), std::move(entry.second));
out.pubkeys.emplace(entry.first.GetID(), entry.first);
}
output_scripts =
std::vector<CScript>{GetScriptForMultisig(m_threshold, pubkeys)};
return true;
}
};
/** A parsed sh(S) descriptor. */
class ConvertorDescriptor : public Descriptor {
const std::function<CScript(const CScript &)> m_convert_fn;
const std::string m_fn_name;
std::unique_ptr<Descriptor> m_descriptor;
public:
ConvertorDescriptor(std::unique_ptr<Descriptor> descriptor,
const std::function<CScript(const CScript &)> &fn,
const std::string &name)
: m_convert_fn(fn), m_fn_name(name),
m_descriptor(std::move(descriptor)) {}
bool IsRange() const override { return m_descriptor->IsRange(); }
bool IsSolvable() const override { return m_descriptor->IsSolvable(); }
std::string ToString() const override {
return m_fn_name + "(" + m_descriptor->ToString() + ")";
}
bool ToPrivateString(const SigningProvider &arg,
std::string &out) const override {
std::string ret;
if (!m_descriptor->ToPrivateString(arg, ret)) {
return false;
}
out = m_fn_name + "(" + std::move(ret) + ")";
return true;
}
bool Expand(int pos, const SigningProvider &arg,
std::vector<CScript> &output_scripts,
FlatSigningProvider &out) const override {
std::vector<CScript> sub;
if (!m_descriptor->Expand(pos, arg, sub, out)) {
return false;
}
output_scripts.clear();
for (const auto &script : sub) {
CScriptID id(script);
out.scripts.emplace(CScriptID(script), script);
output_scripts.push_back(m_convert_fn(script));
}
return true;
}
};
CScript ConvertP2SH(const CScript &script) {
return GetScriptForDestination(CScriptID(script));
}
/** A parsed combo(P) descriptor. */
class ComboDescriptor final : public Descriptor {
std::unique_ptr<PubkeyProvider> m_provider;
public:
ComboDescriptor(std::unique_ptr<PubkeyProvider> provider)
: m_provider(std::move(provider)) {}
bool IsRange() const override { return m_provider->IsRange(); }
bool IsSolvable() const override { return true; }
std::string ToString() const override {
return "combo(" + m_provider->ToString() + ")";
}
bool ToPrivateString(const SigningProvider &arg,
std::string &out) const override {
std::string ret;
if (!m_provider->ToPrivateString(arg, ret)) {
return false;
}
out = "combo(" + std::move(ret) + ")";
return true;
}
bool Expand(int pos, const SigningProvider &arg,
std::vector<CScript> &output_scripts,
FlatSigningProvider &out) const override {
CPubKey key;
KeyOriginInfo info;
if (!m_provider->GetPubKey(pos, arg, key, info)) {
return false;
}
CKeyID keyid = key.GetID();
{
CScript p2pk = GetScriptForRawPubKey(key);
CScript p2pkh = GetScriptForDestination(keyid);
output_scripts =
std::vector<CScript>{std::move(p2pk), std::move(p2pkh)};
out.pubkeys.emplace(keyid, key);
out.origins.emplace(keyid, std::move(info));
}
return true;
}
};
////////////////////////////////////////////////////////////////////////////
// Parser //
////////////////////////////////////////////////////////////////////////////
enum class ParseScriptContext {
TOP,
P2SH,
};
/**
* Parse a constant. If successful, sp is updated to skip the constant and
* return true.
*/
bool Const(const std::string &str, Span<const char> &sp) {
if ((size_t)sp.size() >= str.size() &&
std::equal(str.begin(), str.end(), sp.begin())) {
sp = sp.subspan(str.size());
return true;
}
return false;
}
/**
* Parse a function call. If successful, sp is updated to be the function's
* argument(s).
*/
bool Func(const std::string &str, Span<const char> &sp) {
if ((size_t)sp.size() >= str.size() + 2 && sp[str.size()] == '(' &&
sp[sp.size() - 1] == ')' &&
std::equal(str.begin(), str.end(), sp.begin())) {
sp = sp.subspan(str.size() + 1, sp.size() - str.size() - 2);
return true;
}
return false;
}
/** Return the expression that sp begins with, and update sp to skip it. */
Span<const char> Expr(Span<const char> &sp) {
int level = 0;
auto it = sp.begin();
while (it != sp.end()) {
if (*it == '(') {
++level;
} else if (level && *it == ')') {
--level;
} else if (level == 0 && (*it == ')' || *it == ',')) {
break;
}
++it;
}
Span<const char> ret = sp.first(it - sp.begin());
sp = sp.subspan(it - sp.begin());
return ret;
}
/** Split a string on every instance of sep, returning a vector. */
std::vector<Span<const char>> Split(const Span<const char> &sp, char sep) {
std::vector<Span<const char>> ret;
auto it = sp.begin();
auto start = it;
while (it != sp.end()) {
if (*it == sep) {
ret.emplace_back(start, it);
start = it + 1;
}
++it;
}
ret.emplace_back(start, it);
return ret;
}
/**
* Parse a key path, being passed a split list of elements (the first element is
* ignored).
*/
NODISCARD bool ParseKeyPath(const std::vector<Span<const char>> &split,
KeyPath &out) {
for (size_t i = 1; i < split.size(); ++i) {
Span<const char> elem = split[i];
bool hardened = false;
if (elem.size() > 0 &&
(elem[elem.size() - 1] == '\'' || elem[elem.size() - 1] == 'h')) {
elem = elem.first(elem.size() - 1);
hardened = true;
}
uint32_t p;
if (!ParseUInt32(std::string(elem.begin(), elem.end()), &p) ||
p > 0x7FFFFFFFUL) {
return false;
}
out.push_back(p | (uint32_t(hardened) << 31));
}
return true;
}
/**
* Parse a public key that excludes origin information.
*/
std::unique_ptr<PubkeyProvider> ParsePubkeyInner(const Span<const char> &sp,
FlatSigningProvider &out) {
auto split = Split(sp, '/');
std::string str(split[0].begin(), split[0].end());
if (split.size() == 1) {
if (IsHex(str)) {
std::vector<uint8_t> data = ParseHex(str);
CPubKey pubkey(data);
if (pubkey.IsFullyValid()) {
return std::make_unique<ConstPubkeyProvider>(pubkey);
}
}
CKey key = DecodeSecret(str);
if (key.IsValid()) {
CPubKey pubkey = key.GetPubKey();
out.keys.emplace(pubkey.GetID(), key);
return std::make_unique<ConstPubkeyProvider>(pubkey);
}
}
CExtKey extkey = DecodeExtKey(str);
CExtPubKey extpubkey = DecodeExtPubKey(str);
if (!extkey.key.IsValid() && !extpubkey.pubkey.IsValid()) {
return nullptr;
}
KeyPath path;
DeriveType type = DeriveType::NO;
if (split.back() == MakeSpan("*").first(1)) {
split.pop_back();
type = DeriveType::UNHARDENED;
} else if (split.back() == MakeSpan("*'").first(2) ||
split.back() == MakeSpan("*h").first(2)) {
split.pop_back();
type = DeriveType::HARDENED;
}
if (!ParseKeyPath(split, path)) {
return nullptr;
}
if (extkey.key.IsValid()) {
extpubkey = extkey.Neuter();
out.keys.emplace(extpubkey.pubkey.GetID(), extkey.key);
}
return std::make_unique<BIP32PubkeyProvider>(extpubkey, std::move(path),
type);
}
/**
* Parse a public key including origin information (if enabled).
*/
std::unique_ptr<PubkeyProvider> ParsePubkey(const Span<const char> &sp,
FlatSigningProvider &out) {
auto origin_split = Split(sp, ']');
if (origin_split.size() > 2) {
return nullptr;
}
if (origin_split.size() == 1) {
return ParsePubkeyInner(origin_split[0], out);
}
if (origin_split[0].size() < 1 || origin_split[0][0] != '[') {
return nullptr;
}
auto slash_split = Split(origin_split[0].subspan(1), '/');
if (slash_split[0].size() != 8) {
return nullptr;
}
std::string fpr_hex =
std::string(slash_split[0].begin(), slash_split[0].end());
if (!IsHex(fpr_hex)) {
return nullptr;
}
auto fpr_bytes = ParseHex(fpr_hex);
KeyOriginInfo info;
static_assert(sizeof(info.fingerprint) == 4, "Fingerprint must be 4 bytes");
assert(fpr_bytes.size() == 4);
std::copy(fpr_bytes.begin(), fpr_bytes.end(), info.fingerprint);
if (!ParseKeyPath(slash_split, info.path)) {
return nullptr;
}
auto provider = ParsePubkeyInner(origin_split[1], out);
if (!provider) {
return nullptr;
}
return std::make_unique<OriginPubkeyProvider>(std::move(info),
std::move(provider));
}
/** Parse a script in a particular context. */
std::unique_ptr<Descriptor> ParseScript(Span<const char> &sp,
ParseScriptContext ctx,
FlatSigningProvider &out) {
auto expr = Expr(sp);
if (Func("pk", expr)) {
auto pubkey = ParsePubkey(expr, out);
if (!pubkey) {
return nullptr;
}
return std::make_unique<SingleKeyDescriptor>(std::move(pubkey),
P2PKGetScript, "pk");
}
if (Func("pkh", expr)) {
auto pubkey = ParsePubkey(expr, out);
if (!pubkey) {
return nullptr;
}
return std::make_unique<SingleKeyDescriptor>(std::move(pubkey),
P2PKHGetScript, "pkh");
}
if (ctx == ParseScriptContext::TOP && Func("combo", expr)) {
auto pubkey = ParsePubkey(expr, out);
if (!pubkey) {
return nullptr;
}
return std::make_unique<ComboDescriptor>(std::move(pubkey));
}
if (Func("multi", expr)) {
auto threshold = Expr(expr);
uint32_t thres;
std::vector<std::unique_ptr<PubkeyProvider>> providers;
if (!ParseUInt32(std::string(threshold.begin(), threshold.end()),
&thres)) {
return nullptr;
}
size_t script_size = 0;
while (expr.size()) {
if (!Const(",", expr)) {
return nullptr;
}
auto arg = Expr(expr);
auto pk = ParsePubkey(arg, out);
if (!pk) {
return nullptr;
}
script_size += pk->GetSize() + 1;
providers.emplace_back(std::move(pk));
}
if (providers.size() < 1 || providers.size() > 16 || thres < 1 ||
thres > providers.size()) {
return nullptr;
}
if (ctx == ParseScriptContext::TOP) {
if (providers.size() > 3) {
// Not more than 3 pubkeys for raw multisig
return nullptr;
}
}
if (ctx == ParseScriptContext::P2SH) {
if (script_size + 3 > 520) {
// Enforce P2SH script size limit
return nullptr;
}
}
return std::make_unique<MultisigDescriptor>(thres,
std::move(providers));
}
if (ctx == ParseScriptContext::TOP && Func("sh", expr)) {
auto desc = ParseScript(expr, ParseScriptContext::P2SH, out);
if (!desc || expr.size()) {
return nullptr;
}
return std::make_unique<ConvertorDescriptor>(std::move(desc),
ConvertP2SH, "sh");
}
if (ctx == ParseScriptContext::TOP && Func("addr", expr)) {
CTxDestination dest =
DecodeDestination(std::string(expr.begin(), expr.end()), Params());
if (!IsValidDestination(dest)) {
return nullptr;
}
return std::make_unique<AddressDescriptor>(std::move(dest));
}
if (ctx == ParseScriptContext::TOP && Func("raw", expr)) {
std::string str(expr.begin(), expr.end());
if (!IsHex(str)) {
return nullptr;
}
auto bytes = ParseHex(str);
return std::make_unique<RawDescriptor>(
CScript(bytes.begin(), bytes.end()));
}
return nullptr;
}
static std::unique_ptr<PubkeyProvider>
InferPubkey(const CPubKey &pubkey, ParseScriptContext,
const SigningProvider &provider) {
auto key_provider = std::make_unique<ConstPubkeyProvider>(pubkey);
KeyOriginInfo info;
if (provider.GetKeyOrigin(pubkey.GetID(), info)) {
return std::make_unique<OriginPubkeyProvider>(std::move(info),
std::move(key_provider));
}
return key_provider;
}
std::unique_ptr<Descriptor> InferScript(const CScript &script,
ParseScriptContext ctx,
const SigningProvider &provider) {
std::vector<std::vector<uint8_t>> data;
txnouttype txntype = Solver(script, data);
if (txntype == TX_PUBKEY) {
CPubKey pubkey(data[0].begin(), data[0].end());
if (pubkey.IsValid()) {
return std::make_unique<SingleKeyDescriptor>(
InferPubkey(pubkey, ctx, provider), P2PKGetScript, "pk");
}
}
if (txntype == TX_PUBKEYHASH) {
uint160 hash(data[0]);
CKeyID keyid(hash);
CPubKey pubkey;
if (provider.GetPubKey(keyid, pubkey)) {
return std::make_unique<SingleKeyDescriptor>(
InferPubkey(pubkey, ctx, provider), P2PKHGetScript, "pkh");
}
}
if (txntype == TX_MULTISIG) {
std::vector<std::unique_ptr<PubkeyProvider>> providers;
for (size_t i = 1; i + 1 < data.size(); ++i) {
CPubKey pubkey(data[i].begin(), data[i].end());
providers.push_back(InferPubkey(pubkey, ctx, provider));
}
return std::make_unique<MultisigDescriptor>((int)data[0][0],
std::move(providers));
}
if (txntype == TX_SCRIPTHASH && ctx == ParseScriptContext::TOP) {
uint160 hash(data[0]);
CScriptID scriptid(hash);
CScript subscript;
if (provider.GetCScript(scriptid, subscript)) {
auto sub =
InferScript(subscript, ParseScriptContext::P2SH, provider);
if (sub) {
return std::make_unique<ConvertorDescriptor>(std::move(sub),
ConvertP2SH, "sh");
}
}
}
CTxDestination dest;
if (ExtractDestination(script, dest)) {
if (GetScriptForDestination(dest) == script) {
return std::make_unique<AddressDescriptor>(std::move(dest));
}
}
return std::make_unique<RawDescriptor>(script);
}
} // namespace
std::unique_ptr<Descriptor> Parse(const std::string &descriptor,
FlatSigningProvider &out) {
Span<const char> sp(descriptor.data(), descriptor.size());
auto ret = ParseScript(sp, ParseScriptContext::TOP, out);
if (sp.size() == 0 && ret) {
return ret;
}
return nullptr;
}
std::unique_ptr<Descriptor> InferDescriptor(const CScript &script,
const SigningProvider &provider) {
return InferScript(script, ParseScriptContext::TOP, provider);
}
|
#include "AknOt_Tests.h"
#include <cryptoTools/Common/Defines.h>
#include <cryptoTools/Network/IOService.h>
#include <cryptoTools/Network/Session.h>
#include <cryptoTools/Common/Log.h>
#include "libOTe/NChooseK/AknOtReceiver.h"
#include "libOTe/NChooseK/AknOtSender.h"
#include "libOTe/TwoChooseOne/KosOtExtReceiver.h"
#include "libOTe/TwoChooseOne/KosOtExtSender.h"
#include "Common.h"
#include <cryptoTools/Common/TestCollection.h>
using namespace osuCrypto;
#include "libOTe/Base/BaseOT.h"
namespace tests_libOTe
{
void AknOt_sendRecv1000_Test()
{
#if defined(ENABLE_AKN)
#ifndef LIBOTE_HAS_BASE_OT
#pragma error("ENABLE_AKN requires libOTe to have base OTs");
#endif
u64 totalOts(149501);
u64 minOnes(4028);
u64 avgOnes(5028);
u64 maxOnes(9363);
u64 cncThreshold(724);
double cncProb(0.0999);
//u64 totalOts (10);
//u64 minOnes (0);
//u64 avgOnes (5);
//u64 maxOnes (999999999);
//u64 cncThreshold(9999999);
//double cncProb (0.1);
setThreadName("Recvr");
IOService ios(0);
Session ep0(ios, "127.0.0.1", 1212, SessionMode::Server, "ep");
Session ep1(ios, "127.0.0.1", 1212, SessionMode::Client, "ep");
u64 numTHreads(4);
std::vector<Channel> sendChls(numTHreads), recvChls(numTHreads);
for (u64 i = 0; i < numTHreads; ++i)
{
sendChls[i] = std::move(ep1.addChannel("chl" + std::to_string(i), "chl" + std::to_string(i)));
recvChls[i] = std::move(ep0.addChannel("chl" + std::to_string(i), "chl" + std::to_string(i)));
}
AknOtReceiver recv;
AknOtSender send;
KosOtExtReceiver otExtRecv;
KosOtExtSender otExtSend;
PRNG
sPrng(ZeroBlock),
rPrng(OneBlock);
bool failed = false;
std::thread thrd([&]() {
setThreadName("Sender");
try {
send.init(totalOts, cncThreshold, cncProb, otExtSend, sendChls, sPrng);
}
catch (...)
{
failed = true;
}
});
try {
recv.init(totalOts, avgOnes, cncProb, otExtRecv, recvChls, rPrng);
}
catch (...)
{
failed = true;
}
thrd.join();
if (failed)
throw RTE_LOC;
for (u64 i = 0; i < recv.mMessages.size(); ++i)
{
if (neq(send.mMessages[i][recv.mChoices[i]], recv.mMessages[i]))
throw UnitTestFail();
}
if (recv.mOnes.size() < minOnes)
throw UnitTestFail();
if (recv.mOnes.size() > maxOnes)
throw UnitTestFail();
#else
throw UnitTestSkipped("no base OTs are enabled or ENABLE_AKN not defined.");
#endif
}
}
|
// (C) Copyright R.W. Grosse-Kunstleve 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)
#include <boost/python/make_function.hpp>
#include <boost/python/object/class.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/list.hpp>
#include <boost/python/dict.hpp>
#include <boost/python/str.hpp>
namespace boost { namespace python {
namespace {
tuple instance_reduce(object instance_obj)
{
list result;
object instance_class(instance_obj.attr("__class__"));
result.append(instance_class);
object none;
if (!getattr(instance_obj, "__safe_for_unpickling__", none))
{
str type_name(getattr(instance_class, "__name__"));
str module_name(getattr(instance_class, "__module__", object("")));
if (module_name)
module_name += ".";
PyErr_SetObject(
PyExc_RuntimeError,
( "Pickling of \"%s\" instances is not enabled"
" (http://www.boost.org/libs/python/doc/v2/pickle.html)"
% (module_name+type_name)).ptr()
);
throw_error_already_set();
}
object getinitargs = getattr(instance_obj, "__getinitargs__", none);
tuple initargs;
if (getinitargs.ptr() != none.ptr()) {
initargs = tuple(getinitargs());
}
result.append(initargs);
object getstate = getattr(instance_obj, "__getstate__", none);
object instance_dict = getattr(instance_obj, "__dict__", none);
long len_instance_dict = 0;
if (instance_dict.ptr() != none.ptr()) {
len_instance_dict = len(instance_dict);
}
if (getstate.ptr() != none.ptr()) {
if (len_instance_dict > 0) {
object getstate_manages_dict = getattr(
instance_obj, "__getstate_manages_dict__", none);
if (getstate_manages_dict.ptr() == none.ptr()) {
PyErr_SetString(PyExc_RuntimeError,
"Incomplete pickle support"
" (__getstate_manages_dict__ not set)");
throw_error_already_set();
}
}
result.append(getstate());
}
else if (len_instance_dict > 0) {
result.append(instance_dict);
}
return tuple(result);
}
} // namespace
object const& make_instance_reduce_function()
{
static object result(&instance_reduce);
return result;
}
}} // namespace boost::python
|
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of // TODO: needs to adjusted for checkpoint checks, also see main.cpp
( 0, uint256("0x14dc23f54de47df797172d66531e7a115b782e65f69dda7bf5a4e98fac0ae086"))
// ( 15, uint256("0xc42590789c2ff5ed878fd3cb5ffeab52679cfb45862e8ec328a795b8f86be759"))
/* ( 2, uint256("0x43682e5929c9234209db6592953347aa8b4c8e233692369a61b4780b80835c42"))
( 34336, uint256("0xfc6a3ee59b9f2429114178ff7a4792a7af102688156d26a3edbb90c243850dcd"))
( 50000, uint256("0x5fa3d8bb008a55a1b6e301b435be3a68985083435748b913ef8572bf1282303c"))
( 70000, uint256("0x7ee7864ffec5a23f526e01a1388a6e988d2773365522e04dd51d3c71c19b459f"))
*/
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
|
//
// Created by Jakub Gert on 20/06/2020.
//
#include <QtTest/QtTest>
#include <QtTest/QSignalSpy>
#include "tests/TestSuite.h"
#include "src/grbl/Message.h"
class MessageTests : public TestSuite {
Q_OBJECT
private slots:
void testCustom() {
auto message = Message::custom("ABC");
QCOMPARE(message.data, "ABC");
}
void testMessageInfo() {
auto message = Message::messageInfo();
QCOMPARE(message.data, "$I\n");
}
void testMessageKillAlarm() {
auto message = Message::messageKillAlarm();
QCOMPARE(message.data, "$X\n");
}
void testMessageSetSetting() {
auto settingItem = SettingItem();
settingItem.code = 20;
settingItem.value = "abc";
auto message = Message::messageSetSetting(settingItem);
QCOMPARE(message.data, "$20=abc\n");
}
void testMessageSettings() {
auto message = Message::messageSettings();
QCOMPARE(message.data, "$$\n");
}
};
static MessageTests T_Message;
#include "Message.test.moc"
|
#include "source/extensions/matching/input_matchers/consistent_hashing/config.h"
#include "test/mocks/server/factory_context.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Extensions {
namespace Matching {
namespace InputMatchers {
namespace ConsistentHashing {
TEST(ConfigTest, TestConfig) {
NiceMock<Server::Configuration::MockFactoryContext> context;
const std::string yaml_string = R"EOF(
name: hashing
typed_config:
"@type": type.googleapis.com/envoy.extensions.matching.input_matchers.consistent_hashing.v3.ConsistentHashing
modulo: 100
threshold: 10
)EOF";
envoy::config::core::v3::TypedExtensionConfig config;
TestUtility::loadFromYaml(yaml_string, config);
ConsistentHashingConfig factory;
auto message = Config::Utility::translateAnyToFactoryConfig(
config.typed_config(), ProtobufMessage::getStrictValidationVisitor(), factory);
auto matcher = factory.createInputMatcherFactoryCb(*message, context);
ASSERT_NE(nullptr, matcher);
matcher();
}
TEST(ConfigTest, InvalidConfig) {
NiceMock<Server::Configuration::MockFactoryContext> context;
const std::string yaml_string = R"EOF(
name: hashing
typed_config:
"@type": type.googleapis.com/envoy.extensions.matching.input_matchers.consistent_hashing.v3.ConsistentHashing
modulo: 100
threshold: 200
)EOF";
envoy::config::core::v3::TypedExtensionConfig config;
TestUtility::loadFromYaml(yaml_string, config);
ConsistentHashingConfig factory;
auto message = Config::Utility::translateAnyToFactoryConfig(
config.typed_config(), ProtobufMessage::getStrictValidationVisitor(), factory);
EXPECT_THROW_WITH_MESSAGE(factory.createInputMatcherFactoryCb(*message, context), EnvoyException,
"threshold cannot be greater than modulo: 200 > 100");
}
} // namespace ConsistentHashing
} // namespace InputMatchers
} // namespace Matching
} // namespace Extensions
} // namespace Envoy
|
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/HLTReco/interface/TriggerFilterObjectWithRefs.h"
#include "DataFormats/HLTReco/interface/TriggerRefsCollections.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/RecoCandidate/interface/RecoChargedCandidate.h"
#include "DataFormats/RecoCandidate/interface/RecoChargedCandidateFwd.h"
#include "DataFormats/MuonReco/interface/MuonFwd.h"
#include "HLTDiMuonGlbTrkFilter.h"
#include "DataFormats/BeamSpot/interface/BeamSpot.h"
#include "DataFormats/MuonSeed/interface/L3MuonTrajectorySeed.h"
#include "DataFormats/MuonSeed/interface/L3MuonTrajectorySeedCollection.h"
#include "TrackingTools/PatternTools/interface/ClosestApproachInRPhi.h"
#include "TrackingTools/TransientTrack/interface/TransientTrack.h"
#include "MagneticField/Engine/interface/MagneticField.h"
#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "FWCore/Utilities/interface/EDMException.h"
#include "DataFormats/Math/interface/deltaR.h"
HLTDiMuonGlbTrkFilter::HLTDiMuonGlbTrkFilter(const edm::ParameterSet& iConfig) : HLTFilter(iConfig) {
m_muonsTag = iConfig.getParameter<edm::InputTag>("inputMuonCollection");
m_muonsToken = consumes<reco::MuonCollection>(m_muonsTag);
m_candsTag = iConfig.getParameter<edm::InputTag>("inputCandCollection");
m_candsToken = consumes<reco::RecoChargedCandidateCollection>(m_candsTag);
m_minTrkHits = iConfig.getParameter<int>("minTrkHits");
m_minMuonHits = iConfig.getParameter<int>("minMuonHits");
m_maxNormalizedChi2 = iConfig.getParameter<double>("maxNormalizedChi2");
m_minDR = iConfig.getParameter<double>("minDR");
m_allowedTypeMask = iConfig.getParameter<unsigned int>("allowedTypeMask");
m_requiredTypeMask = iConfig.getParameter<unsigned int>("requiredTypeMask");
m_trkMuonId = muon::SelectionType(iConfig.getParameter<unsigned int>("trkMuonId"));
m_minPtMuon1 = iConfig.getParameter<double>("minPtMuon1");
m_minPtMuon2 = iConfig.getParameter<double>("minPtMuon2");
m_maxEtaMuon = iConfig.getParameter<double>("maxEtaMuon");
m_maxYDimuon = iConfig.getParameter<double>("maxYDimuon");
m_minMass = iConfig.getParameter<double>("minMass");
m_maxMass = iConfig.getParameter<double>("maxMass");
m_chargeOpt = iConfig.getParameter<int>("ChargeOpt");
m_maxDCAMuMu = iConfig.getParameter<double>("maxDCAMuMu");
m_maxdEtaMuMu = iConfig.getParameter<double>("maxdEtaMuMu");
}
void HLTDiMuonGlbTrkFilter::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
makeHLTFilterDescription(desc);
desc.add<edm::InputTag>("inputMuonCollection", edm::InputTag(""));
desc.add<edm::InputTag>("inputCandCollection", edm::InputTag(""));
desc.add<int>("minTrkHits", -1);
desc.add<int>("minMuonHits", -1);
desc.add<double>("maxNormalizedChi2", 1e99);
desc.add<double>("minDR", 0.1);
desc.add<unsigned int>("allowedTypeMask", 255);
desc.add<unsigned int>("requiredTypeMask", 0);
desc.add<unsigned int>("trkMuonId", 0);
desc.add<double>("minPtMuon1", 17);
desc.add<double>("minPtMuon2", 8);
desc.add<double>("maxEtaMuon", 1e99);
desc.add<double>("maxYDimuon", 1e99);
desc.add<double>("minMass", 1);
desc.add<double>("maxMass", 1e99);
desc.add<int>("ChargeOpt", 0);
desc.add<double>("maxDCAMuMu", 1e99);
desc.add<double>("maxdEtaMuMu", 1e99);
descriptions.add("hltDiMuonGlbTrkFilter", desc);
}
bool HLTDiMuonGlbTrkFilter::hltFilter(edm::Event& iEvent,
const edm::EventSetup& iSetup,
trigger::TriggerFilterObjectWithRefs& filterproduct) const {
edm::Handle<reco::MuonCollection> muons;
iEvent.getByToken(m_muonsToken, muons);
edm::Handle<reco::RecoChargedCandidateCollection> cands;
iEvent.getByToken(m_candsToken, cands);
if (saveTags())
filterproduct.addCollectionTag(m_candsTag);
if (cands->size() != muons->size())
throw edm::Exception(edm::errors::Configuration)
<< "Both input collection must be aligned and represent same physical muon objects";
std::vector<unsigned int> filteredMuons;
for (unsigned int i = 0; i < muons->size(); ++i) {
const reco::Muon& muon(muons->at(i));
if ((muon.type() & m_allowedTypeMask) == 0)
continue;
if ((muon.type() & m_requiredTypeMask) != m_requiredTypeMask)
continue;
if (!muon.innerTrack().isNull()) {
if (muon.innerTrack()->numberOfValidHits() < m_minTrkHits)
continue;
}
if (!muon.globalTrack().isNull()) {
if (muon.globalTrack()->normalizedChi2() > m_maxNormalizedChi2)
continue;
if (muon.globalTrack()->hitPattern().numberOfValidMuonHits() < m_minMuonHits)
continue;
}
if (muon.isTrackerMuon() && !muon::isGoodMuon(muon, m_trkMuonId))
continue;
if (muon.pt() < std::min(m_minPtMuon1, m_minPtMuon2))
continue;
if (std::abs(muon.eta()) > m_maxEtaMuon)
continue;
filteredMuons.push_back(i);
}
unsigned int npassed(0);
std::set<unsigned int> mus;
if (filteredMuons.size() > 1) {
// Needed for DCA calculation
edm::ESHandle<MagneticField> bFieldHandle;
if (m_maxDCAMuMu < 100.)
iSetup.get<IdealMagneticFieldRecord>().get(bFieldHandle);
for (unsigned int i = 0; i < filteredMuons.size() - 1; ++i)
for (unsigned int j = i + 1; j < filteredMuons.size(); ++j) {
const reco::Muon& mu1(muons->at(filteredMuons.at(i)));
const reco::Muon& mu2(muons->at(filteredMuons.at(j)));
if (std::max(mu1.pt(), mu2.pt()) > std::max(m_minPtMuon1, m_minPtMuon2) &&
std::abs(mu2.eta() - mu1.eta()) < m_maxdEtaMuMu && deltaR(mu1, mu2) > m_minDR &&
(mu1.p4() + mu2.p4()).mass() > m_minMass && (mu1.p4() + mu2.p4()).mass() < m_maxMass &&
std::abs((mu1.p4() + mu2.p4()).Rapidity()) < m_maxYDimuon) {
if (m_chargeOpt < 0) {
if (mu1.charge() * mu2.charge() > 0)
continue;
} else if (m_chargeOpt > 0) {
if (mu1.charge() * mu2.charge() < 0)
continue;
}
if (m_maxDCAMuMu < 100.) {
reco::TrackRef tk1 = mu1.get<reco::TrackRef>();
reco::TrackRef tk2 = mu2.get<reco::TrackRef>();
reco::TransientTrack mu1TT(*tk1, &(*bFieldHandle));
reco::TransientTrack mu2TT(*tk2, &(*bFieldHandle));
TrajectoryStateClosestToPoint mu1TS = mu1TT.impactPointTSCP();
TrajectoryStateClosestToPoint mu2TS = mu2TT.impactPointTSCP();
if (mu1TS.isValid() && mu2TS.isValid()) {
ClosestApproachInRPhi cApp;
cApp.calculate(mu1TS.theState(), mu2TS.theState());
if (!cApp.status() || cApp.distance() > m_maxDCAMuMu)
continue;
}
}
mus.insert(filteredMuons.at(i));
mus.insert(filteredMuons.at(j));
npassed++;
}
}
}
for (unsigned int mu : mus)
filterproduct.addObject(trigger::TriggerMuon, reco::RecoChargedCandidateRef(cands, mu));
return npassed > 0;
}
// declare this class as a framework plugin
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(HLTDiMuonGlbTrkFilter);
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentserver.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "base58.h"
#include "chainparams.h"
#include "ui_interface.h"
#include "util.h"
#include "wallet.h"
#include <cstdlib>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QApplication>
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileOpenEvent>
#include <QHash>
#include <QList>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslCertificate>
#include <QSslError>
#include <QSslSocket>
#include <QStringList>
#include <QTextDocument>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
using namespace boost;
using namespace std;
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("kingscoin:");
// BIP70 payment protocol messages
const char* BIP70_MESSAGE_PAYMENTACK = "PaymentACK";
const char* BIP70_MESSAGE_PAYMENTREQUEST = "PaymentRequest";
// BIP71 payment protocol media types
const char* BIP71_MIMETYPE_PAYMENT = "application/kingscoin-payment";
const char* BIP71_MIMETYPE_PAYMENTACK = "application/kingscoin-paymentack";
const char* BIP71_MIMETYPE_PAYMENTREQUEST = "application/kingscoin-paymentrequest";
// BIP70 max payment request size in bytes (DoS protection)
const qint64 BIP70_MAX_PAYMENTREQUEST_SIZE = 50000;
struct X509StoreDeleter {
void operator()(X509_STORE* b) {
X509_STORE_free(b);
}
};
struct X509Deleter {
void operator()(X509* b) { X509_free(b); }
};
namespace // Anon namespace
{
std::unique_ptr<X509_STORE, X509StoreDeleter> certStore;
}
//
// Create a name that is unique for:
// testnet / non-testnet
// data directory
//
static QString ipcServerName()
{
QString name("KingscoinQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(QString::fromStdString(GetDataDir(true).string()));
name.append(QString::number(qHash(ddir)));
return name;
}
//
// We store payment URIs and requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QList<QString> savedPaymentRequests;
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
qDebug() << "ReportInvalidCertificate : Payment server found an invalid certificate: " << cert.subjectInfo(QSslCertificate::CommonName);
}
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
// Unit tests mostly use this, to pass in fake root CAs:
if (_store) {
certStore.reset(_store);
return;
}
// Normal execution, use either -rootcertificates or system certs:
certStore.reset(X509_STORE_new());
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));
if (certFile.isEmpty())
return; // Empty store
QList<QSslCertificate> certList;
if (certFile != "-system-") {
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslSocket::setDefaultCaCertificates(certList);
} else
certList = QSslSocket::systemCaCertificates();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
foreach (const QSslCertificate& cert, certList) {
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
ReportInvalidCertificate(cert);
continue;
}
#if QT_VERSION >= 0x050000
if (cert.isBlacklisted()) {
ReportInvalidCertificate(cert);
continue;
}
#endif
QByteArray certData = cert.toDer();
const unsigned char* data = (const unsigned char*)certData.data();
std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size()));
if (x509 && X509_STORE_add_cert(certStore.get(), x509.get())) {
// Note: X509_STORE increases the reference count to the X509 object,
// we still have to release our reference to it.
++nRootCerts;
} else {
ReportInvalidCertificate(cert);
continue;
}
}
qWarning() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
// Warning: ipcSendCommandLine() is called early in init,
// so don't use "emit message()", but "QMessageBox::"!
//
void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
{
for (int i = 1; i < argc; i++) {
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
// If the kingscoin: URI contains a payment request, we are not able to detect the
// network as that would require fetching and parsing the payment request.
// That means clicking such an URI which contains a testnet payment request
// will start a mainnet instance and throw a "wrong network" error.
if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // kingscoin: URI
{
savedPaymentRequests.append(arg);
SendCoinsRecipient r;
if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty()) {
CBitcoinAddress address(r.address.toStdString());
if (address.IsValid(Params(CBaseChainParams::MAIN))) {
SelectParams(CBaseChainParams::MAIN);
} else if (address.IsValid(Params(CBaseChainParams::TESTNET))) {
SelectParams(CBaseChainParams::TESTNET);
}
}
} else if (QFile::exists(arg)) // Filename
{
savedPaymentRequests.append(arg);
PaymentRequestPlus request;
if (readPaymentRequestFromFile(arg, request)) {
if (request.getDetails().network() == "main") {
SelectParams(CBaseChainParams::MAIN);
} else if (request.getDetails().network() == "test") {
SelectParams(CBaseChainParams::TESTNET);
}
}
} else {
// Printing to debug.log is about the best we can do here, the
// GUI hasn't started yet so we can't pop up a message box.
qWarning() << "PaymentServer::ipcSendCommandLine : Payment request file does not exist: " << arg;
}
}
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
foreach (const QString& r, savedPaymentRequests) {
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) {
delete socket;
socket = NULL;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
socket = NULL;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) : QObject(parent),
saveURIs(true),
uriServer(0),
netManager(0),
optionsModel(0)
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Install global event filter to catch QFileOpenEvents
// on Mac: sent when you click kingscoin: links
// other OSes: helpful when dealing with payment request files (in the future)
if (parent)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
if (startLocalServer) {
uriServer = new QLocalServer(this);
if (!uriServer->listen(name)) {
// constructor is called early in init, so don't use "emit message()" here
QMessageBox::critical(0, tr("Payment request error"),
tr("Cannot start kingscoin: click-to-pay handler"));
} else {
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString)));
}
}
}
PaymentServer::~PaymentServer()
{
google::protobuf::ShutdownProtobufLibrary();
}
//
// OSX-specific way of handling kingscoin: URIs and
// PaymentRequest mime types
//
bool PaymentServer::eventFilter(QObject* object, QEvent* event)
{
// clicking on kingscoin: URIs creates FileOpen events on the Mac
if (event->type() == QEvent::FileOpen) {
QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->file().isEmpty())
handleURIOrFile(fileEvent->file());
else if (!fileEvent->url().isEmpty())
handleURIOrFile(fileEvent->url().toString());
return true;
}
return QObject::eventFilter(object, event);
}
void PaymentServer::initNetManager()
{
if (!optionsModel)
return;
if (netManager != NULL)
delete netManager;
// netManager is used to fetch paymentrequests given in kingscoin: URIs
netManager = new QNetworkAccessManager(this);
QNetworkProxy proxy;
// Query active SOCKS5 proxy
if (optionsModel->getProxySettings(proxy)) {
netManager->setProxy(proxy);
qDebug() << "PaymentServer::initNetManager : Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port();
} else
qDebug() << "PaymentServer::initNetManager : No active proxy server found.";
connect(netManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(netRequestFinished(QNetworkReply*)));
connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)),
this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError>&)));
}
void PaymentServer::uiReady()
{
initNetManager();
saveURIs = false;
foreach (const QString& s, savedPaymentRequests) {
handleURIOrFile(s);
}
savedPaymentRequests.clear();
}
void PaymentServer::handleURIOrFile(const QString& s)
{
if (saveURIs) {
savedPaymentRequests.append(s);
return;
}
if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // kingscoin: URI
{
#if QT_VERSION < 0x050000
QUrl uri(s);
#else
QUrlQuery uri((QUrl(s)));
#endif
if (uri.hasQueryItem("r")) // payment request URI
{
QByteArray temp;
temp.append(uri.queryItemValue("r"));
QString decoded = QUrl::fromPercentEncoding(temp);
QUrl fetchUrl(decoded, QUrl::StrictMode);
if (fetchUrl.isValid()) {
qDebug() << "PaymentServer::handleURIOrFile : fetchRequest(" << fetchUrl << ")";
fetchRequest(fetchUrl);
} else {
qWarning() << "PaymentServer::handleURIOrFile : Invalid URL: " << fetchUrl;
emit message(tr("URI handling"),
tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
CClientUIInterface::ICON_WARNING);
}
return;
} else // normal URI
{
SendCoinsRecipient recipient;
if (GUIUtil::parseBitcoinURI(s, &recipient)) {
CBitcoinAddress address(recipient.address.toStdString());
if (!address.IsValid()) {
emit message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address),
CClientUIInterface::MSG_ERROR);
} else
emit receivedPaymentRequest(recipient);
} else
emit message(tr("URI handling"),
tr("URI cannot be parsed! This can be caused by an invalid KGS address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
return;
}
}
if (QFile::exists(s)) // payment request file
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!readPaymentRequestFromFile(s, request)) {
emit message(tr("Payment request file handling"),
tr("Payment request file cannot be read! This can be caused by an invalid payment request file."),
CClientUIInterface::ICON_WARNING);
} else if (processPaymentRequest(request, recipient))
emit receivedPaymentRequest(recipient);
return;
}
}
void PaymentServer::handleURIConnection()
{
QLocalSocket* clientConnection = uriServer->nextPendingConnection();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString msg;
in >> msg;
handleURIOrFile(msg);
}
//
// Warning: readPaymentRequestFromFile() is used in ipcSendCommandLine()
// so don't use "emit message()", but "QMessageBox::"!
//
bool PaymentServer::readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
qWarning() << QString("PaymentServer::%1: Failed to open %2").arg(__func__).arg(filename);
return false;
}
// BIP70 DoS protection
if (f.size() > BIP70_MAX_PAYMENTREQUEST_SIZE) {
qWarning() << QString("PaymentServer::%1: Payment request %2 is too large (%3 bytes, allowed %4 bytes).")
.arg(__func__)
.arg(filename)
.arg(f.size())
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE);
return false;
}
QByteArray data = f.readAll();
return request.parse(data);
}
bool PaymentServer::processPaymentRequest(PaymentRequestPlus& request, SendCoinsRecipient& recipient)
{
if (!optionsModel)
return false;
if (request.IsInitialized()) {
const payments::PaymentDetails& details = request.getDetails();
// Payment request network matches client network?
if (details.network() != Params().NetworkIDString()) {
emit message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Expired payment request?
if (details.has_expires() && (int64_t)details.expires() < GetTime()) {
emit message(tr("Payment request rejected"), tr("Payment request has expired."),
CClientUIInterface::MSG_ERROR);
return false;
}
} else {
emit message(tr("Payment request error"), tr("Payment request is not initialized."),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.paymentRequest = request;
recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());
request.getMerchant(certStore.get(), recipient.authenticatedMerchant);
QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo();
QStringList addresses;
foreach (const PAIRTYPE(CScript, CAmount) & sendingTo, sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
// Append destination address
addresses.append(QString::fromStdString(CBitcoinAddress(dest).ToString()));
} else if (!recipient.authenticatedMerchant.isEmpty()) {
// Insecure payments to custom kgs addresses are not supported
// (there is no good way to tell the user where they are paying in a way
// they'd have a chance of understanding).
emit message(tr("Payment request rejected"),
tr("Unverified payment requests to custom payment scripts are unsupported."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
if (txOut.IsDust(::minRelayTxFee)) {
emit message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).").arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.amount += sendingTo.second;
}
// Store addresses and format them to fit nicely into the GUI
recipient.address = addresses.join("<br />");
if (!recipient.authenticatedMerchant.isEmpty()) {
qDebug() << "PaymentServer::processPaymentRequest : Secure payment request from " << recipient.authenticatedMerchant;
} else {
qDebug() << "PaymentServer::processPaymentRequest : Insecure payment request to " << addresses.join(", ");
}
return true;
}
void PaymentServer::fetchRequest(const QUrl& url)
{
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTREQUEST);
netRequest.setUrl(url);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTREQUEST);
netManager->get(netRequest);
}
void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
return;
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTACK);
netRequest.setUrl(QString::fromStdString(details.payment_url()));
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BIP71_MIMETYPE_PAYMENT);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTACK);
payments::Payment payment;
payment.set_merchant_data(details.merchant_data());
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant);
std::string strAccount = account.toStdString();
set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount);
if (!refundAddresses.empty()) {
CScript s = GetScriptForDestination(*refundAddresses.begin());
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
} else {
CPubKey newKey;
if (wallet->GetKeyFromPool(newKey)) {
CKeyID keyID = newKey.GetID();
wallet->SetAddressBook(keyID, strAccount, "refund");
CScript s = GetScriptForDestination(keyID);
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
} else {
// This should never happen, because sending coins should have
// just unlocked the wallet and refilled the keypool.
qWarning() << "PaymentServer::fetchPaymentACK : Error getting refund key, refund_to not set";
}
}
int length = payment.ByteSize();
netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);
QByteArray serData(length, '\0');
if (payment.SerializeToArray(serData.data(), length)) {
netManager->post(netRequest, serData);
} else {
// This should never happen, either.
qWarning() << "PaymentServer::fetchPaymentACK : Error serializing payment message";
}
}
void PaymentServer::netRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
// BIP70 DoS protection
if (reply->size() > BIP70_MAX_PAYMENTREQUEST_SIZE) {
QString msg = tr("Payment request %1 is too large (%2 bytes, allowed %3 bytes).")
.arg(reply->request().url().toString())
.arg(reply->size())
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE);
qWarning() << QString("PaymentServer::%1:").arg(__func__) << msg;
emit message(tr("Payment request DoS protection"), msg, CClientUIInterface::MSG_ERROR);
return;
}
if (reply->error() != QNetworkReply::NoError) {
QString msg = tr("Error communicating with %1: %2")
.arg(reply->request().url().toString())
.arg(reply->errorString());
qWarning() << "PaymentServer::netRequestFinished: " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return;
}
QByteArray data = reply->readAll();
QString requestType = reply->request().attribute(QNetworkRequest::User).toString();
if (requestType == BIP70_MESSAGE_PAYMENTREQUEST) {
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!request.parse(data)) {
qWarning() << "PaymentServer::netRequestFinished : Error parsing payment request";
emit message(tr("Payment request error"),
tr("Payment request cannot be parsed!"),
CClientUIInterface::MSG_ERROR);
} else if (processPaymentRequest(request, recipient))
emit receivedPaymentRequest(recipient);
return;
} else if (requestType == BIP70_MESSAGE_PAYMENTACK) {
payments::PaymentACK paymentACK;
if (!paymentACK.ParseFromArray(data.data(), data.size())) {
QString msg = tr("Bad response from server %1")
.arg(reply->request().url().toString());
qWarning() << "PaymentServer::netRequestFinished : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
} else {
emit receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));
}
}
}
void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError>& errs)
{
Q_UNUSED(reply);
QString errString;
foreach (const QSslError& err, errs) {
qWarning() << "PaymentServer::reportSslErrors : " << err;
errString += err.errorString() + "\n";
}
emit message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR);
}
void PaymentServer::setOptionsModel(OptionsModel* optionsModel)
{
this->optionsModel = optionsModel;
}
void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
{
// currently we don't futher process or store the paymentACK message
emit message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
X509_STORE* PaymentServer::getCertStore()
{
return certStore.get();
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include "yb/client/yb_op.h"
#include "yb/client/client.h"
#include "yb/client/meta_cache.h"
#include "yb/common/row.h"
#include "yb/common/wire_protocol.pb.h"
#include "yb/common/wire_protocol.h"
#include "yb/common/redis_protocol.pb.h"
#include "yb/common/ql_protocol.pb.h"
#include "yb/common/ql_rowblock.h"
#include "yb/yql/redis/redisserver/redis_constants.h"
namespace yb {
namespace client {
using std::shared_ptr;
using std::unique_ptr;
//--------------------------------------------------------------------------------------------------
// YBOperation
//--------------------------------------------------------------------------------------------------
YBOperation::YBOperation(const shared_ptr<YBTable>& table)
: table_(table) {
}
YBOperation::~YBOperation() {}
void YBOperation::SetTablet(const scoped_refptr<internal::RemoteTablet>& tablet) {
tablet_ = tablet;
}
//--------------------------------------------------------------------------------------------------
// YBRedisOp
//--------------------------------------------------------------------------------------------------
YBRedisOp::YBRedisOp(const shared_ptr<YBTable>& table)
: YBOperation(table) {
}
YBRedisOp::~YBRedisOp() {}
RedisResponsePB* YBRedisOp::mutable_response() {
if (!redis_response_) {
redis_response_.reset(new RedisResponsePB());
}
return redis_response_.get();
}
const RedisResponsePB& YBRedisOp::response() const {
return *DCHECK_NOTNULL(redis_response_.get());
}
// YBRedisWriteOp -----------------------------------------------------------------
YBRedisWriteOp::YBRedisWriteOp(const shared_ptr<YBTable>& table)
: YBRedisOp(table), redis_write_request_(new RedisWriteRequestPB()) {
}
YBRedisWriteOp::~YBRedisWriteOp() {}
size_t YBRedisWriteOp::space_used_by_request() const {
return redis_write_request_->ByteSizeLong();
}
std::string YBRedisWriteOp::ToString() const {
return "REDIS_WRITE " + redis_write_request_->key_value().key();
}
void YBRedisWriteOp::SetHashCode(uint16_t hash_code) {
hash_code_ = hash_code;
redis_write_request_->mutable_key_value()->set_hash_code(hash_code);
}
const std::string& YBRedisWriteOp::GetKey() const {
return redis_write_request_->key_value().key();
}
Status YBRedisWriteOp::GetPartitionKey(std::string *partition_key) const {
const Slice& slice(redis_write_request_->key_value().key());
return table_->partition_schema().EncodeRedisKey(slice, partition_key);
}
// YBRedisReadOp -----------------------------------------------------------------
YBRedisReadOp::YBRedisReadOp(const shared_ptr<YBTable>& table)
: YBRedisOp(table), redis_read_request_(new RedisReadRequestPB()) {
}
YBRedisReadOp::~YBRedisReadOp() {}
size_t YBRedisReadOp::space_used_by_request() const {
return redis_read_request_->SpaceUsedLong();
}
std::string YBRedisReadOp::ToString() const {
return "REDIS_READ " + redis_read_request_->key_value().key();
}
void YBRedisReadOp::SetHashCode(uint16_t hash_code) {
hash_code_ = hash_code;
redis_read_request_->mutable_key_value()->set_hash_code(hash_code);
}
const std::string& YBRedisReadOp::GetKey() const {
return redis_read_request_->key_value().key();
}
Status YBRedisReadOp::GetPartitionKey(std::string *partition_key) const {
const Slice& slice(redis_read_request_->key_value().key());
return table_->partition_schema().EncodeRedisKey(slice, partition_key);
}
//--------------------------------------------------------------------------------------------------
// YBCql Operators
// - These ops should be prefixed with YBCql instead of YBql.
// - The prefixes "ql" or "QL" are used for common entities of all languages and not just CQL.
// - The name will be clean up later.
//--------------------------------------------------------------------------------------------------
YBqlOp::YBqlOp(const shared_ptr<YBTable>& table)
: YBOperation(table) , ql_response_(new QLResponsePB()) {
}
YBqlOp::~YBqlOp() {
}
// YBqlWriteOp -----------------------------------------------------------------
YBqlWriteOp::YBqlWriteOp(const shared_ptr<YBTable>& table)
: YBqlOp(table), ql_write_request_(new QLWriteRequestPB()) {
}
YBqlWriteOp::~YBqlWriteOp() {}
static YBqlWriteOp *NewYBqlWriteOp(const shared_ptr<YBTable>& table,
QLWriteRequestPB::QLStmtType stmt_type) {
YBqlWriteOp *op = new YBqlWriteOp(table);
QLWriteRequestPB *req = op->mutable_request();
req->set_type(stmt_type);
req->set_client(YQL_CLIENT_CQL);
// TODO: Request ID should be filled with CQL stream ID. Query ID should be replaced too.
req->set_request_id(reinterpret_cast<uint64_t>(op));
req->set_query_id(reinterpret_cast<int64_t>(op));
req->set_schema_version(table->schema().version());
return op;
}
YBqlWriteOp *YBqlWriteOp::NewInsert(const std::shared_ptr<YBTable>& table) {
return NewYBqlWriteOp(table, QLWriteRequestPB::QL_STMT_INSERT);
}
YBqlWriteOp *YBqlWriteOp::NewUpdate(const std::shared_ptr<YBTable>& table) {
return NewYBqlWriteOp(table, QLWriteRequestPB::QL_STMT_UPDATE);
}
YBqlWriteOp *YBqlWriteOp::NewDelete(const std::shared_ptr<YBTable>& table) {
return NewYBqlWriteOp(table, QLWriteRequestPB::QL_STMT_DELETE);
}
std::string YBqlWriteOp::ToString() const {
return "QL_WRITE " + ql_write_request_->ShortDebugString();
}
Status YBqlWriteOp::GetPartitionKey(string* partition_key) const {
return table_->partition_schema().EncodeKey(ql_write_request_->hashed_column_values(),
partition_key);
}
void YBqlWriteOp::SetHashCode(const uint16_t hash_code) {
ql_write_request_->set_hash_code(hash_code);
}
uint16_t YBqlWriteOp::GetHashCode() const {
return ql_write_request_->hash_code();
}
bool YBqlWriteOp::ReadsStaticRow() const {
// A QL write op reads the static row if it reads a static column, or it writes to the static row
// and has a user-defined timestamp (which DocDB requires a read-modify-write by the timestamp).
return !ql_write_request_->column_refs().static_ids().empty() ||
(writes_static_row_ && ql_write_request_->has_user_timestamp_usec());
}
bool YBqlWriteOp::ReadsPrimaryRow() const {
// A QL write op reads the primary row reads a non-static column, it writes to the primary row
// and has a user-defined timestamp (which DocDB requires a read-modify-write by the timestamp),
// or if there is an IF clause.
return !ql_write_request_->column_refs().ids().empty() ||
(writes_primary_row_ && ql_write_request_->has_user_timestamp_usec()) ||
ql_write_request_->has_if_expr();
}
bool YBqlWriteOp::WritesStaticRow() const {
return writes_static_row_;
}
bool YBqlWriteOp::WritesPrimaryRow() const {
return writes_primary_row_;
}
// YBqlWriteOp::HashHash/Equal ---------------------------------------------------------------
size_t YBqlWriteOp::HashKeyComparator::operator() (const YBqlWriteOpPtr& op) const {
size_t hash = 0;
// Hash the table id.
boost::hash_combine(hash, op->table()->id());
// Hash the hash key.
string key;
for (const auto& value : op->request().hashed_column_values()) {
AppendToKey(value.value(), &key);
}
boost::hash_combine(hash, key);
return hash;
}
bool YBqlWriteOp::HashKeyComparator::operator() (const YBqlWriteOpPtr& op1,
const YBqlWriteOpPtr& op2) const {
// Check if two write ops overlap that they apply to the same hash key in the same table.
if (op1->table() != op2->table() && op1->table()->id() != op2->table()->id()) {
return false;
}
const QLWriteRequestPB& req1 = op1->request();
const QLWriteRequestPB& req2 = op2->request();
if (req1.hashed_column_values_size() != req2.hashed_column_values_size()) {
return false;
}
for (int i = 0; i < req1.hashed_column_values().size(); i++) {
DCHECK(req1.hashed_column_values()[i].has_value());
DCHECK(req2.hashed_column_values()[i].has_value());
if (req1.hashed_column_values()[i].value() != req2.hashed_column_values()[i].value())
return false;
}
return true;
}
// YBqlWriteOp::PrimaryHash/Equal ---------------------------------------------------------------
size_t YBqlWriteOp::PrimaryKeyComparator::operator() (const YBqlWriteOpPtr& op) const {
size_t hash = YBqlWriteOp::HashKeyComparator::operator()(op);
// Hash the range key also.
string key;
for (const auto& value : op->request().range_column_values()) {
AppendToKey(value.value(), &key);
}
boost::hash_combine(hash, key);
return hash;
}
bool YBqlWriteOp::PrimaryKeyComparator::operator() (const YBqlWriteOpPtr& op1,
const YBqlWriteOpPtr& op2) const {
if (!YBqlWriteOp::HashKeyComparator::operator()(op1, op2)) {
return false;
}
// Check if two write ops overlap that they apply to the range key also.
const QLWriteRequestPB& req1 = op1->request();
const QLWriteRequestPB& req2 = op2->request();
if (req1.range_column_values_size() != req2.range_column_values_size()) {
return false;
}
for (int i = 0; i < req1.range_column_values().size(); i++) {
DCHECK(req1.range_column_values()[i].has_value());
DCHECK(req2.range_column_values()[i].has_value());
if (req1.range_column_values()[i].value() != req2.range_column_values()[i].value())
return false;
}
return true;
}
// YBqlReadOp -----------------------------------------------------------------
YBqlReadOp::YBqlReadOp(const shared_ptr<YBTable>& table)
: YBqlOp(table),
ql_read_request_(new QLReadRequestPB()),
yb_consistency_level_(YBConsistencyLevel::STRONG) {
}
YBqlReadOp::~YBqlReadOp() {}
YBqlReadOp *YBqlReadOp::NewSelect(const shared_ptr<YBTable>& table) {
YBqlReadOp *op = new YBqlReadOp(table);
QLReadRequestPB *req = op->mutable_request();
req->set_client(YQL_CLIENT_CQL);
// TODO: Request ID should be filled with CQL stream ID. Query ID should be replaced too.
req->set_request_id(reinterpret_cast<uint64_t>(op));
req->set_query_id(reinterpret_cast<int64_t>(op));
req->set_schema_version(table->schema().version());
return op;
}
std::string YBqlReadOp::ToString() const {
return "QL_READ " + ql_read_request_->DebugString();
}
void YBqlReadOp::SetHashCode(const uint16_t hash_code) {
ql_read_request_->set_hash_code(hash_code);
}
Status YBqlReadOp::GetPartitionKey(string* partition_key) const {
if (!ql_read_request_->hashed_column_values().empty()) {
// If hashed columns are set, use them to compute the exact key and set the bounds
RETURN_NOT_OK(table_->partition_schema().EncodeKey(ql_read_request_->hashed_column_values(),
partition_key));
// TODO: If user specified token range doesn't contain the hash columns specified then the query
// will have no effect. We need to implement an exit path rather than requesting the tablets.
// For now, we set point query some value that is not equal to the hash to the hash columns
// Which will return no result.
// Make sure given key is not smaller than lower bound (if any)
if (ql_read_request_->has_hash_code()) {
uint16 hash_code = static_cast<uint16>(ql_read_request_->hash_code());
auto lower_bound = PartitionSchema::EncodeMultiColumnHashValue(hash_code);
if (*partition_key < lower_bound) *partition_key = std::move(lower_bound);
}
// Make sure given key is not bigger than upper bound (if any)
if (ql_read_request_->has_max_hash_code()) {
uint16 hash_code = static_cast<uint16>(ql_read_request_->max_hash_code());
auto upper_bound = PartitionSchema::EncodeMultiColumnHashValue(hash_code);
if (*partition_key > upper_bound) *partition_key = std::move(upper_bound);
}
// Set both bounds to equal partition key now, because this is a point get
ql_read_request_->set_hash_code(
PartitionSchema::DecodeMultiColumnHashValue(*partition_key));
ql_read_request_->set_max_hash_code(
PartitionSchema::DecodeMultiColumnHashValue(*partition_key));
} else {
// Otherwise, set the partition key to the hash_code (lower bound of the token range).
if (ql_read_request_->has_hash_code()) {
uint16 hash_code = static_cast<uint16>(ql_read_request_->hash_code());
*partition_key = PartitionSchema::EncodeMultiColumnHashValue(hash_code);
} else {
// Default to empty key, this will start a scan from the beginning.
partition_key->clear();
}
}
// If this is a continued query use the partition key from the paging state
// If paging state is there, set hash_code = paging state. This is only supported for forward
// scans.
if (ql_read_request_->has_paging_state() &&
ql_read_request_->paging_state().has_next_partition_key() &&
!ql_read_request_->paging_state().next_partition_key().empty()) {
*partition_key = ql_read_request_->paging_state().next_partition_key();
ql_read_request_->set_hash_code(
PartitionSchema::DecodeMultiColumnHashValue(*partition_key));
}
return Status::OK();
}
std::vector<ColumnSchema> MakeColumnSchemasFromColDesc(
const google::protobuf::RepeatedPtrField<QLRSColDescPB>& rscol_descs) {
std::vector<ColumnSchema> column_schemas;
column_schemas.reserve(rscol_descs.size());
for (const auto& rscol_desc : rscol_descs) {
column_schemas.emplace_back(rscol_desc.name(), QLType::FromQLTypePB(rscol_desc.ql_type()));
}
return column_schemas;
}
std::vector<ColumnSchema> YBqlReadOp::MakeColumnSchemasFromRequest() const {
// Tests don't have access to the QL internal statement object, so they have to use rsrow
// descriptor from the read request.
return MakeColumnSchemasFromColDesc(request().rsrow_desc().rscol_descs());
}
Result<QLRowBlock> YBqlReadOp::MakeRowBlock() const {
Schema schema(MakeColumnSchemasFromRequest(), 0);
QLRowBlock result(schema);
Slice data(rows_data_);
if (!data.empty()) {
RETURN_NOT_OK(result.Deserialize(request().client(), &data));
}
return result;
}
//--------------------------------------------------------------------------------------------------
// YBPgsql Operators
//--------------------------------------------------------------------------------------------------
YBPgsqlOp::YBPgsqlOp(const shared_ptr<YBTable>& table)
: YBOperation(table) , response_(new PgsqlResponsePB()) {
}
YBPgsqlOp::~YBPgsqlOp() {
}
//--------------------------------------------------------------------------------------------------
// YBPgsqlWriteOp
YBPgsqlWriteOp::YBPgsqlWriteOp(const shared_ptr<YBTable>& table)
: YBPgsqlOp(table), write_request_(new PgsqlWriteRequestPB()) {
}
YBPgsqlWriteOp::~YBPgsqlWriteOp() {}
static YBPgsqlWriteOp *NewYBPgsqlWriteOp(const shared_ptr<YBTable>& table,
PgsqlWriteRequestPB::PgsqlStmtType stmt_type) {
YBPgsqlWriteOp *op = new YBPgsqlWriteOp(table);
PgsqlWriteRequestPB *req = op->mutable_request();
req->set_stmt_type(stmt_type);
req->set_client(YQL_CLIENT_PGSQL);
req->set_schema_version(table->schema().version());
return op;
}
YBPgsqlWriteOp *YBPgsqlWriteOp::NewInsert(const std::shared_ptr<YBTable>& table) {
return NewYBPgsqlWriteOp(table, PgsqlWriteRequestPB::PGSQL_INSERT);
}
YBPgsqlWriteOp *YBPgsqlWriteOp::NewUpdate(const std::shared_ptr<YBTable>& table) {
return NewYBPgsqlWriteOp(table, PgsqlWriteRequestPB::PGSQL_UPDATE);
}
YBPgsqlWriteOp *YBPgsqlWriteOp::NewDelete(const std::shared_ptr<YBTable>& table) {
return NewYBPgsqlWriteOp(table, PgsqlWriteRequestPB::PGSQL_DELETE);
}
std::string YBPgsqlWriteOp::ToString() const {
return "PGSQL_WRITE " + write_request_->ShortDebugString();
}
Status YBPgsqlWriteOp::GetPartitionKey(string* partition_key) const {
return table_->partition_schema().EncodeKey(write_request_->partition_column_values(),
partition_key);
}
void YBPgsqlWriteOp::SetHashCode(const uint16_t hash_code) {
write_request_->set_hash_code(hash_code);
}
//--------------------------------------------------------------------------------------------------
// YBPgsqlReadOp
YBPgsqlReadOp::YBPgsqlReadOp(const shared_ptr<YBTable>& table)
: YBPgsqlOp(table),
read_request_(new PgsqlReadRequestPB()),
yb_consistency_level_(YBConsistencyLevel::STRONG) {
}
YBPgsqlReadOp::~YBPgsqlReadOp() {}
YBPgsqlReadOp *YBPgsqlReadOp::NewSelect(const shared_ptr<YBTable>& table) {
YBPgsqlReadOp *op = new YBPgsqlReadOp(table);
PgsqlReadRequestPB *req = op->mutable_request();
req->set_client(YQL_CLIENT_PGSQL);
req->set_schema_version(table->schema().version());
return op;
}
std::string YBPgsqlReadOp::ToString() const {
return "PGSQL_READ " + read_request_->DebugString();
}
void YBPgsqlReadOp::SetHashCode(const uint16_t hash_code) {
read_request_->set_hash_code(hash_code);
}
Status YBPgsqlReadOp::GetPartitionKey(string* partition_key) const {
if (!read_request_->partition_column_values().empty()) {
// If hashed columns are set, use them to compute the exact key and set the bounds
RETURN_NOT_OK(table_->partition_schema().EncodeKey(read_request_->partition_column_values(),
partition_key));
// TODO(neil) We borrow "EncodeMultiColumnHashValue" for now. For postgresql, this encoding
// is up to us to choose whatever that make sense.
//
// Make sure given key is not smaller than lower bound (if any)
if (read_request_->has_hash_code()) {
uint16 hash_code = static_cast<uint16>(read_request_->hash_code());
auto lower_bound = PartitionSchema::EncodeMultiColumnHashValue(hash_code);
if (*partition_key < lower_bound) *partition_key = std::move(lower_bound);
}
// Make sure given key is not bigger than upper bound (if any)
if (read_request_->has_max_hash_code()) {
uint16 hash_code = static_cast<uint16>(read_request_->max_hash_code());
auto upper_bound = PartitionSchema::EncodeMultiColumnHashValue(hash_code);
if (*partition_key > upper_bound) *partition_key = std::move(upper_bound);
}
// Set both bounds to equal partition key now, because this is a point get
uint16 hash_code = PartitionSchema::DecodeMultiColumnHashValue(*partition_key);
read_request_->set_hash_code(hash_code);
read_request_->set_max_hash_code(hash_code);
} else {
// Otherwise, set the partition key to the hash_code (lower bound of the token range).
if (read_request_->has_hash_code()) {
uint16 hash_code = static_cast<uint16>(read_request_->hash_code());
*partition_key = PartitionSchema::EncodeMultiColumnHashValue(hash_code);
} else {
// Default to empty key, this will start a scan from the beginning.
partition_key->clear();
}
}
// If this is a continued query use the partition key from the paging state
// If paging state is there, set hash_code = paging state. This is only supported for forward
// scans.
if (read_request_->has_paging_state() &&
read_request_->paging_state().has_next_partition_key() &&
!read_request_->paging_state().next_partition_key().empty()) {
*partition_key = read_request_->paging_state().next_partition_key();
read_request_->set_hash_code(
PartitionSchema::DecodeMultiColumnHashValue(*partition_key));
}
return Status::OK();
}
std::vector<ColumnSchema> YBPgsqlReadOp::MakeColumnSchemasFromColDesc(
const google::protobuf::RepeatedPtrField<PgsqlRSColDescPB>& rscol_descs) {
std::vector<ColumnSchema> column_schemas;
column_schemas.reserve(rscol_descs.size());
for (const auto& rscol_desc : rscol_descs) {
column_schemas.emplace_back(rscol_desc.name(), QLType::FromQLTypePB(rscol_desc.ql_type()));
}
return column_schemas;
}
std::vector<ColumnSchema> YBPgsqlReadOp::MakeColumnSchemasFromRequest() const {
// Tests don't have access to the QL internal statement object, so they have to use rsrow
// descriptor from the read request.
return MakeColumnSchemasFromColDesc(request().rsrow_desc().rscol_descs());
}
Result<QLRowBlock> YBPgsqlReadOp::MakeRowBlock() const {
Schema schema(MakeColumnSchemasFromRequest(), 0);
QLRowBlock result(schema);
Slice data(rows_data_);
if (!data.empty()) {
RETURN_NOT_OK(result.Deserialize(request().client(), &data));
}
return result;
}
} // namespace client
} // namespace yb
|
#ifndef IDOCP_UNCONSTR_STATE_EQUATION_HPP_
#define IDOCP_UNCONSTR_STATE_EQUATION_HPP_
#include "Eigen/Core"
#include "idocp/ocp/split_solution.hpp"
#include "idocp/ocp/split_kkt_residual.hpp"
#include "idocp/ocp/split_kkt_matrix.hpp"
namespace idocp {
namespace unconstr {
namespace stateequation {
///
/// @brief Linearizes the state equation of forward Euler.
/// @param[in] dt Time step.
/// @param[in] s Solution at the current stage.
/// @param[in] s_next Solution at the next time stage.
/// @param[in, out] kkt_matrix Split KKT matrix at the current time stage.
/// @param[in, out] kkt_residual Split KKT residual at the current time stage.
///
void linearizeForwardEuler(const double dt, const SplitSolution& s,
const SplitSolution& s_next,
SplitKKTMatrix& kkt_matrix,
SplitKKTResidual& kkt_residual);
///
/// @brief Linearizes the state equation of backward Euler.
/// @param[in] dt Time step.
/// @param[in] q_prev Configuration at the previous time stage.
/// @param[in] v_prev Generalized velocity at the previous time stage.
/// @param[in] s Solution at the current tiem stage.
/// @param[in] s_next Solution at the next time stage.
/// @param[in, out] kkt_matrix Split KKT matrix at the current time stage.
/// @param[in, out] kkt_residual Split KKT reisdual at the current time stage.
///
template <typename ConfigVectorType, typename TangentVectorType>
void linearizeBackwardEuler(
const double dt, const Eigen::MatrixBase<ConfigVectorType>& q_prev,
const Eigen::MatrixBase<TangentVectorType>& v_prev,
const SplitSolution& s, const SplitSolution& s_next,
SplitKKTMatrix& kkt_matrix, SplitKKTResidual& kkt_residual);
///
/// @brief Linearizes the state equation of backward Euler at the terminal stage.
/// @param[in] dt Time step.
/// @param[in] q_prev Configuration at the previous time stage.
/// @param[in] v_prev Generalized velocity at the previous time stage.
/// @param[in] s Solution at the current tiem stage.
/// @param[in, out] kkt_matrix Split KKT matrix at the current time stage.
/// @param[in, out] kkt_residual Split KKT reisdual at the current time stage.
///
template <typename ConfigVectorType, typename TangentVectorType>
void linearizeBackwardEulerTerminal(
const double dt, const Eigen::MatrixBase<ConfigVectorType>& q_prev,
const Eigen::MatrixBase<TangentVectorType>& v_prev,
const SplitSolution& s, SplitKKTMatrix& kkt_matrix,
SplitKKTResidual& kkt_residual);
///
/// @brief Computes the residual in the state equation of forward Euler.
/// @param[in] dt Time step.
/// @param[in] s Solution at the current time stage.
/// @param[in] q_next Configuration at the next time stage.
/// @param[in] v_next Generalized velocity at the next time stage.
/// @param[in, out] kkt_residual Split KKT residual at the current time stage.
///
template <typename ConfigVectorType, typename TangentVectorType>
void computeForwardEulerResidual(
const double dt, const SplitSolution& s,
const Eigen::MatrixBase<ConfigVectorType>& q_next,
const Eigen::MatrixBase<TangentVectorType>& v_next,
SplitKKTResidual& kkt_residual);
///
/// @brief Computes the residual in the state equation of backward Euler.
/// @param[in] dt Time step.
/// @param[in] q_prev Configuration at the previous time stage.
/// @param[in] v_prev Generalized velocity at the previous time stage.
/// @param[in] s Solution at the current time stage.
/// @param[in, out] kkt_residual Split KKT residual at the current time stage.
///
template <typename ConfigVectorType, typename TangentVectorType>
void computeBackwardEulerResidual(
const double dt, const Eigen::MatrixBase<ConfigVectorType>& q_prev,
const Eigen::MatrixBase<TangentVectorType>& v_prev,
const SplitSolution& s, SplitKKTResidual& kkt_residual);
} // namespace stateequation
} // namespace unconstr
} // namespace idocp
#include "idocp/unconstr/unconstr_state_equation.hxx"
#endif // IDOCP_UNCONSTR_STATE_EQUATION_HPP_
|
/*
* Copyright (C) 2021-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/command_container/command_encoder.h"
#include "shared/test/common/helpers/debug_manager_state_restore.h"
#include "shared/test/common/helpers/default_hw_info.h"
#include "shared/test/common/test_macros/test.h"
using namespace NEO;
using WalkerDispatchTestsXeHpcCore = ::testing::Test;
XE_HPC_CORETEST_F(WalkerDispatchTestsXeHpcCore, givenXeHpcWhenEncodeAdditionalWalkerFieldsIsCalledThenComputeDispatchAllIsCorrectlySet) {
using COMPUTE_WALKER = typename FamilyType::COMPUTE_WALKER;
DebugManagerStateRestore debugRestorer;
auto walkerCmd = FamilyType::cmdInitGpgpuWalker;
auto hwInfo = *defaultHwInfo;
{
EncodeDispatchKernel<FamilyType>::encodeAdditionalWalkerFields(hwInfo, walkerCmd, KernelExecutionType::Default);
EXPECT_FALSE(walkerCmd.getComputeDispatchAllWalkerEnable());
}
{
DebugManager.flags.ComputeDispatchAllWalkerEnableInComputeWalker.set(1);
EncodeDispatchKernel<FamilyType>::encodeAdditionalWalkerFields(hwInfo, walkerCmd, KernelExecutionType::Default);
EXPECT_TRUE(walkerCmd.getComputeDispatchAllWalkerEnable());
}
}
|
/* Transportation
You are making a program for a bus service.
A bus can transport 50 passengers at once.
Given the number of passengers waiting in the bus station as input,
you need to calculate and output how many empty seats the last bus will have.
Sample Input:
126
Sample Output:
24
Explanation: The first bus will transport 50 passengers, leaving 126-50=76 in the station.
The next one will leave 26 in the station, thus, the last bus will take all of the 26 passengers,
having 50-26=24 seats left empty. */
#include <iostream>
using namespace std;
int main() {
//your code goes here
int num_passengrs, num_seats_empty;
int total_seats = 50;
cin >> num_passengrs;
cout << (total_seats - (num_passengrs % total_seats));
return 0;
}
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/odeconfig.h>
#include "config.h"
#include "contact.h"
#include "joint_internal.h"
//****************************************************************************
// contact
dxJointContact::dxJointContact( dxWorld *w ) :
dxJoint( w )
{
}
void
dxJointContact::getSureMaxInfo( SureMaxInfo* info )
{
// ...as the actual m is very likely to hit the maximum
info->max_m = (contact.surface.mode&dContactRolling)?6:3;
}
void
dxJointContact::getInfo1( dxJoint::Info1 *info )
{
// make sure mu's >= 0, then calculate number of constraint rows and number
// of unbounded rows.
int m = 1, nub = 0;
int roll = (contact.surface.mode&dContactRolling)!=0;
if ( contact.surface.mu < 0 ) contact.surface.mu = 0;
// Anisotropic sliding and rolling and spinning friction
if ( contact.surface.mode & dContactAxisDep )
{
if ( contact.surface.mu2 < 0 ) contact.surface.mu2 = 0;
if ( contact.surface.mu > 0 ) m++;
if ( contact.surface.mu2 > 0 ) m++;
if ( contact.surface.mu == dInfinity ) nub ++;
if ( contact.surface.mu2 == dInfinity ) nub ++;
if (roll) {
if ( contact.surface.rho < 0 ) contact.surface.rho = 0;
else m++;
if ( contact.surface.rho2 < 0 ) contact.surface.rho2 = 0;
else m++;
if ( contact.surface.rhoN < 0 ) contact.surface.rhoN = 0;
else m++;
if ( contact.surface.rho == dInfinity ) nub++;
if ( contact.surface.rho2 == dInfinity ) nub++;
if ( contact.surface.rhoN == dInfinity ) nub++;
}
}
else
{
if ( contact.surface.mu > 0 ) m += 2;
if ( contact.surface.mu == dInfinity ) nub += 2;
if (roll) {
if ( contact.surface.rho < 0 ) contact.surface.rho = 0;
else m+=3;
if ( contact.surface.rho == dInfinity ) nub += 3;
}
}
the_m = m;
info->m = m;
info->nub = nub;
}
void
dxJointContact::getInfo2( dReal worldFPS, dReal worldERP, const Info2Descr *info )
{
int s = info->rowskip;
int s2 = 2 * s;
const int rowNormal = 0;
const int rowFriction1 = 1;
int rowFriction2 = 2; // we might decrease it to 1, so no const
int rollRow=3;
// get normal, with sign adjusted for body1/body2 polarity
dVector3 normal;
if ( flags & dJOINT_REVERSE )
{
normal[0] = - contact.geom.normal[0];
normal[1] = - contact.geom.normal[1];
normal[2] = - contact.geom.normal[2];
}
else
{
normal[0] = contact.geom.normal[0];
normal[1] = contact.geom.normal[1];
normal[2] = contact.geom.normal[2];
}
normal[3] = 0; // @@@ hmmm
// c1,c2 = contact points with respect to body PORs
dVector3 c1, c2 = {0,0,0};
dxBody *b0 = node[0].body;
c1[0] = contact.geom.pos[0] - b0->posr.pos[0];
c1[1] = contact.geom.pos[1] - b0->posr.pos[1];
c1[2] = contact.geom.pos[2] - b0->posr.pos[2];
// set jacobian for normal
info->J1l[0] = normal[0];
info->J1l[1] = normal[1];
info->J1l[2] = normal[2];
dCalcVectorCross3( info->J1a, c1, normal );
dxBody *b1 = node[1].body;
if ( b1 )
{
c2[0] = contact.geom.pos[0] - b1->posr.pos[0];
c2[1] = contact.geom.pos[1] - b1->posr.pos[1];
c2[2] = contact.geom.pos[2] - b1->posr.pos[2];
info->J2l[0] = -normal[0];
info->J2l[1] = -normal[1];
info->J2l[2] = -normal[2];
dCalcVectorCross3( info->J2a, c2, normal );
dNegateVector3( info->J2a );
}
// set right hand side and cfm value for normal
dReal erp = worldERP;
if ( contact.surface.mode & dContactSoftERP )
erp = contact.surface.soft_erp;
dReal k = worldFPS * erp;
dReal depth = contact.geom.depth - world->contactp.min_depth;
if ( depth < 0 ) depth = 0;
if ( contact.surface.mode & dContactSoftCFM )
info->cfm[rowNormal] = contact.surface.soft_cfm;
dReal motionN = 0;
if ( contact.surface.mode & dContactMotionN )
motionN = contact.surface.motionN;
const dReal pushout = k * depth + motionN;
info->c[rowNormal] = pushout;
// note: this cap should not limit bounce velocity
const dReal maxvel = world->contactp.max_vel;
if ( info->c[rowNormal] > maxvel )
info->c[rowNormal] = maxvel;
// deal with bounce
if ( contact.surface.mode & dContactBounce )
{
// calculate outgoing velocity (-ve for incoming contact)
dReal outgoing = dCalcVectorDot3( info->J1l, node[0].body->lvel )
+ dCalcVectorDot3( info->J1a, node[0].body->avel );
if ( b1 )
{
outgoing += dCalcVectorDot3( info->J2l, node[1].body->lvel )
+ dCalcVectorDot3( info->J2a, node[1].body->avel );
}
outgoing -= motionN;
// only apply bounce if the outgoing velocity is greater than the
// threshold, and if the resulting c[rowNormal] exceeds what we already have.
if ( contact.surface.bounce_vel >= 0 &&
( -outgoing ) > contact.surface.bounce_vel )
{
const dReal newc = - contact.surface.bounce * outgoing + motionN;
if ( newc > info->c[rowNormal] ) info->c[rowNormal] = newc;
}
}
// set LCP limits for normal
info->lo[0] = 0;
info->hi[0] = dInfinity;
if ( the_m == 1 ) // no friction, there is nothing else to do
return;
// now do jacobian for tangential forces
dVector3 t1, t2; // two vectors tangential to normal
if ( contact.surface.mode & dContactFDir1 ) // use fdir1 ?
{
t1[0] = contact.fdir1[0];
t1[1] = contact.fdir1[1];
t1[2] = contact.fdir1[2];
dCalcVectorCross3( t2, normal, t1 );
}
else
{
dPlaneSpace( normal, t1, t2 );
}
// first friction direction
if ( contact.surface.mu > 0 )
{
info->J1l[s+0] = t1[0];
info->J1l[s+1] = t1[1];
info->J1l[s+2] = t1[2];
dCalcVectorCross3( info->J1a + s, c1, t1 );
if ( node[1].body )
{
info->J2l[s+0] = -t1[0];
info->J2l[s+1] = -t1[1];
info->J2l[s+2] = -t1[2];
dReal *J2a_plus_s = info->J2a + s;
dCalcVectorCross3( J2a_plus_s, c2, t1 );
dNegateVector3( J2a_plus_s );
}
// set right hand side
if ( contact.surface.mode & dContactMotion1 )
{
info->c[rowFriction1] = contact.surface.motion1;
}
// set LCP bounds and friction index. this depends on the approximation
// mode
info->lo[rowFriction1] = -contact.surface.mu;
info->hi[rowFriction1] = contact.surface.mu;
if ( contact.surface.mode & dContactApprox1_1 )
info->findex[rowFriction1] = 0;
// set slip (constraint force mixing)
if ( contact.surface.mode & dContactSlip1 )
info->cfm[rowFriction1] = contact.surface.slip1;
} else {
// there was no friction for direction 1, so the second friction constraint
// has to be on this line instead
s2 = s;
rowFriction2 = rowFriction1;
}
const dReal mu2 = contact.surface.mode & dContactMu2 ? contact.surface.mu2 : contact.surface.mu;
// second friction direction
if ( mu2 > 0 )
{
info->J1l[s2+0] = t2[0];
info->J1l[s2+1] = t2[1];
info->J1l[s2+2] = t2[2];
dCalcVectorCross3( info->J1a + s2, c1, t2 );
if ( node[1].body )
{
info->J2l[s2+0] = -t2[0];
info->J2l[s2+1] = -t2[1];
info->J2l[s2+2] = -t2[2];
dReal *J2a_plus_s2 = info->J2a + s2;
dCalcVectorCross3( J2a_plus_s2, c2, t2 );
dNegateVector3( J2a_plus_s2 );
}
// set right hand side
if ( contact.surface.mode & dContactMotion2 )
{
info->c[rowFriction2] = contact.surface.motion2;
}
// set LCP bounds and friction index. this depends on the approximation
// mode
info->lo[rowFriction2] = -mu2;
info->hi[rowFriction2] = mu2;
if ( contact.surface.mode & dContactApprox1_2 )
info->findex[rowFriction2] = 0;
// set slip (constraint force mixing)
if ( contact.surface.mode & dContactSlip2 )
info->cfm[rowFriction2] = contact.surface.slip2;
rollRow = rowFriction2+1;
} else {
rollRow = rowFriction2;
}
// Handle rolling/spinning friction
if (contact.surface.mode&dContactRolling) {
dReal rho[3];
const dReal* ax[3];
int approx[3];
// Get the coefficients
rho[0] = contact.surface.rho;
if (contact.surface.mode&dContactAxisDep) {
rho[1] = contact.surface.rho2;
rho[2] = contact.surface.rhoN;
} else {
rho[1] = rho[0];
rho[2] = rho[0];
}
ax[0] = t1; // Rolling around t1 creates movement parallel to t2
ax[1] = t2;
ax[2] = normal; // Spinning axis
// Should we use proportional force?
approx[0] = contact.surface.mode & dContactApprox1_1;
approx[1] = contact.surface.mode & dContactApprox1_2;
approx[2] = contact.surface.mode & dContactApprox1_N;
for (int ii=0;ii<3;++ii) {
if (rho[ii]>0) {
// Set the angular axis
dCopyVector3(&(info->J1a[ rollRow*s ]),ax[ii]);
if ( b1 ) {
dCopyNegatedVector3(&(info->J2a[ rollRow*s ]),ax[ii]);
}
// Set the lcp limits
info->lo[ rollRow ] = -rho[ii];
info->hi[ rollRow ] = rho[ii];
// Make limits proportional to normal force
if (approx[ii]) info->findex[ rollRow ] = 0;
rollRow++;
}
}
}
}
dJointType
dxJointContact::type() const
{
return dJointTypeContact;
}
size_t
dxJointContact::size() const
{
return sizeof( *this );
}
|
/*
Copyright 2020 The OneFlow 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 "oneflow/core/memory/memory_case_util.h"
namespace oneflow {
namespace {
// MemCaseId int64_t encode
// | | device_type | device_index | |
// | | ---- 5 ---- | ----- 7 ----- | |
// | | MemZoneId | pglck | reg_by_net |
// | | ----------- 12 ------------ | --- 5 --- | ---- 1 ---- |
// | reserved | MemCaseId |
// | ---- 46 ---- | ------------------------ 18 ------------------------- |
// | ----------------------------- 64 bit ------------------------------- |
// GlobalMemCaseId int64_t encode
// | | rank | MemCaseId |
// | | -- 19 -- | --- 18 --- |
// | reserved | GlobalMemCaseId |
// | -- 27 -- | -------- 37 --------- |
// | ------------ 64 bit ------------ |
constexpr size_t kRegByNetBits = 1;
constexpr size_t kPageLockedTypeBits = 5;
constexpr size_t kDeviceIndexBits = MemZoneId::kDeviceIndexBits;
constexpr size_t kDeviceTypeBits = MemZoneId::kDeviceTypeBits;
constexpr size_t kPageLockedTypeShift = kRegByNetBits;
constexpr size_t kDeviceIndexShift = kPageLockedTypeShift + kPageLockedTypeBits;
constexpr size_t kDeviceTypeShift = kDeviceIndexShift + kDeviceIndexBits;
constexpr size_t kRankShift = kDeviceTypeShift + kDeviceTypeBits;
} // namespace
MemCaseId::MemCaseId(const MemoryCase& mem_case) {
// TODO: consider migrate to registry
DeviceType device_type = DeviceType::kInvalidDevice;
device_index_t device_index = 0;
DeviceType page_locked_device_type = DeviceType::kInvalidDevice;
bool host_mem_registered_by_network = false;
if (mem_case.has_host_mem()) {
device_type = DeviceType::kCPU;
if (mem_case.host_mem().has_cuda_pinned_mem()) {
page_locked_device_type = DeviceType::kGPU;
device_index = mem_case.host_mem().cuda_pinned_mem().device_id();
} else if (mem_case.host_mem().has_fake_dev_pinned_mem()) {
page_locked_device_type = DeviceType::kFAKEDEVICE;
} else {
// host mem is pageable
}
if (mem_case.host_mem().has_used_by_network() && mem_case.host_mem().used_by_network()) {
host_mem_registered_by_network = true;
}
} else if (mem_case.has_device_cuda_mem()) {
device_type = DeviceType::kGPU;
device_index = mem_case.device_cuda_mem().device_id();
} else if (mem_case.has_fake_dev_mem()) {
device_type = DeviceType::kFAKEDEVICE;
} else if (mem_case.has_device_cambricon_mem()) {
device_type = DeviceType::kCambricon;
device_index = mem_case.device_cambricon_mem().device_id();
} else {
// Uninitialized MemoryCase, all member are set to default
}
mem_zone_id_ = MemZoneId{device_type, device_index};
host_mem_page_locked_device_type_ = page_locked_device_type;
host_mem_registered_by_network_ = host_mem_registered_by_network;
}
int64_t SerializeMemCaseIdToInt64(const MemCaseId& mem_case_id) {
int64_t id = static_cast<int64_t>(mem_case_id.is_host_mem_registered_by_network());
id |= static_cast<int64_t>(mem_case_id.host_mem_page_locked_device_type())
<< kPageLockedTypeShift;
id |= static_cast<int64_t>(mem_case_id.mem_zone_id().device_index()) << kDeviceIndexShift;
id |= static_cast<int64_t>(mem_case_id.mem_zone_id().device_type()) << kDeviceTypeShift;
return id;
}
int64_t SerializeGlobalMemCaseIdToInt64(const GlobalMemCaseId& global_mem_case_id) {
int64_t id = SerializeMemCaseIdToInt64(global_mem_case_id.mem_case_id());
id |= static_cast<int64_t>(global_mem_case_id.rank()) << kRankShift;
return id;
}
void SerializeMemCaseIdToMemCase(const MemCaseId& mem_case_id, MemoryCase* mem_case) {
// TODO: consider migrate to registry
if (mem_case_id.mem_zone_id().device_type() == DeviceType::kCPU) {
auto* host_mem = mem_case->mutable_host_mem();
if (mem_case_id.host_mem_page_locked_device_type() == DeviceType::kGPU) {
host_mem->mutable_cuda_pinned_mem()->set_device_id(mem_case_id.mem_zone_id().device_index());
} else if (mem_case_id.host_mem_page_locked_device_type() == DeviceType::kFAKEDEVICE) {
host_mem->mutable_fake_dev_pinned_mem();
} else {
host_mem->Clear();
}
if (mem_case_id.is_host_mem_registered_by_network()) { host_mem->set_used_by_network(true); }
} else if (mem_case_id.mem_zone_id().device_type() == DeviceType::kGPU) {
mem_case->mutable_device_cuda_mem()->set_device_id(mem_case_id.mem_zone_id().device_index());
} else if (mem_case_id.mem_zone_id().device_type() == DeviceType::kFAKEDEVICE) {
mem_case->mutable_fake_dev_mem();
} else if (mem_case_id.mem_zone_id().device_type() == DeviceType::kCambricon) {
mem_case->mutable_device_cambricon_mem()->set_device_id(
mem_case_id.mem_zone_id().device_index());
} else {
UNIMPLEMENTED();
}
}
// Patch the source memory case to destination memory case.
// Patch failed when src_mem_case and dst_mem_case have different device_type
// or one of them has invalid device_type.
// Patch failed when src_mem_case and dst_mem_case have the same non-cpu device_type
// but have different device_index.
// When src_mem_case and dst_mem_case have the same cpu device_type
// and src_mem_case has more constrain than dst_mem_case(page-locked by other device,
// such as gpu or network device), patch the constrain of src_mem_case to dst_mem_case.
bool PatchMemCaseId(MemCaseId* dst_mem_case_id, const MemCaseId& src_mem_case_id) {
DeviceType device_type = src_mem_case_id.mem_zone_id().device_type();
if (device_type == DeviceType::kInvalidDevice) { return false; }
if (device_type != dst_mem_case_id->mem_zone_id().device_type()) { return false; }
if (device_type == DeviceType::kCPU) {
MemCaseId::device_index_t device_index = dst_mem_case_id->mem_zone_id().device_index();
auto page_locked_device_type = dst_mem_case_id->host_mem_page_locked_device_type();
bool registered_by_network = dst_mem_case_id->is_host_mem_registered_by_network();
if (src_mem_case_id.host_mem_page_locked_device_type() == DeviceType::kGPU) {
page_locked_device_type = DeviceType::kGPU;
device_index = src_mem_case_id.mem_zone_id().device_index();
} else if (src_mem_case_id.host_mem_page_locked_device_type() == DeviceType::kFAKEDEVICE) {
page_locked_device_type = DeviceType::kFAKEDEVICE;
} else {
// do nothing
}
if (src_mem_case_id.is_host_mem_registered_by_network()) { registered_by_network = true; }
*dst_mem_case_id =
MemCaseId{device_type, device_index, page_locked_device_type, registered_by_network};
} else {
if (dst_mem_case_id->mem_zone_id().device_index()
!= src_mem_case_id.mem_zone_id().device_index()) {
return false;
}
}
return true;
}
bool PatchMemCase(MemoryCase* dst_mem_case, const MemoryCase& src_mem_case) {
MemCaseId src_mem_case_id{src_mem_case};
MemCaseId dst_mem_case_id{*dst_mem_case};
bool result = PatchMemCaseId(&dst_mem_case_id, src_mem_case_id);
SerializeMemCaseIdToMemCase(dst_mem_case_id, dst_mem_case);
return result;
}
MemCaseId GenerateCorrespondingPageLockedHostMemCaseId(const MemCaseId& mem_case_id) {
CHECK_NE(mem_case_id.mem_zone_id().device_type(), DeviceType::kInvalidDevice);
CHECK_NE(mem_case_id.mem_zone_id().device_type(), DeviceType::kCPU);
DeviceType page_locked_device_type = DeviceType::kInvalidDevice;
MemCaseId::device_index_t device_index = 0;
if (mem_case_id.mem_zone_id().device_type() == DeviceType::kGPU) {
page_locked_device_type = DeviceType::kGPU;
device_index = mem_case_id.mem_zone_id().device_index();
} else if (mem_case_id.mem_zone_id().device_type() == DeviceType::kFAKEDEVICE) {
page_locked_device_type = DeviceType::kFAKEDEVICE;
} else {
// do nothing
}
return MemCaseId{DeviceType::kCPU, device_index, page_locked_device_type};
}
MemoryCase GenerateCorrespondingPageLockedHostMemoryCase(const MemoryCase& mem_case) {
MemCaseId host_mem_case_id = GenerateCorrespondingPageLockedHostMemCaseId(MemCaseId{mem_case});
MemoryCase host_mem_case;
SerializeMemCaseIdToMemCase(host_mem_case_id, &host_mem_case);
return host_mem_case;
}
} // namespace oneflow
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/spanner/admin/instance_admin_client.h"
#include "google/cloud/spanner/create_instance_request_builder.h"
#include "google/cloud/spanner/testing/cleanup_stale_instances.h"
#include "google/cloud/spanner/testing/pick_instance_config.h"
#include "google/cloud/spanner/testing/random_instance_name.h"
#include "google/cloud/spanner/update_instance_request_builder.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include "google/cloud/testing_util/integration_test.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
#include <algorithm>
#include <regex>
#include <string>
#include <vector>
namespace google {
namespace cloud {
namespace spanner {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {
using ::google::cloud::testing_util::IsOk;
using ::google::cloud::testing_util::StatusIs;
using ::testing::AnyOf;
using ::testing::HasSubstr;
using ::testing::UnorderedElementsAre;
std::string const& ProjectId() {
static std::string project_id =
internal::GetEnv("GOOGLE_CLOUD_PROJECT").value_or("");
return project_id;
}
std::string const& InstanceId() {
static std::string instance_id =
internal::GetEnv("GOOGLE_CLOUD_CPP_SPANNER_TEST_INSTANCE_ID")
.value_or("");
return instance_id;
}
bool RunSlowInstanceTests() {
static bool run_slow_instance_tests =
internal::GetEnv("GOOGLE_CLOUD_CPP_SPANNER_SLOW_INTEGRATION_TESTS")
.value_or("")
.find("instance") != std::string::npos;
return run_slow_instance_tests;
}
bool Emulator() {
static bool emulator = internal::GetEnv("SPANNER_EMULATOR_HOST").has_value();
return emulator;
}
class CleanupStaleInstances : public ::testing::Environment {
public:
void SetUp() override {
std::regex instance_name_regex(
R"(projects/.+/instances/)"
R"((temporary-instance-(\d{4}-\d{2}-\d{2})-.+))");
// Make sure we're using a correct regex.
EXPECT_EQ(2, instance_name_regex.mark_count());
auto generator = internal::MakeDefaultPRNG();
Instance in(ProjectId(), spanner_testing::RandomInstanceName(generator));
auto fq_instance_name = in.FullName();
std::smatch m;
EXPECT_TRUE(std::regex_match(fq_instance_name, m, instance_name_regex));
EXPECT_EQ(3, m.size());
EXPECT_STATUS_OK(spanner_testing::CleanupStaleInstances(
in.project_id(), instance_name_regex));
}
};
::testing::Environment* const kCleanupEnv =
::testing::AddGlobalTestEnvironment(new CleanupStaleInstances);
class InstanceAdminClientTest
: public ::google::cloud::testing_util::IntegrationTest {
public:
InstanceAdminClientTest()
: generator_(internal::MakeDefaultPRNG()),
client_(spanner_admin::MakeInstanceAdminConnection()) {
static_cast<void>(kCleanupEnv);
}
protected:
void SetUp() override {
if (Emulator()) {
// We expect test instances to exist when running against real services,
// but if we are running against the emulator we're happy to create one.
Instance in(ProjectId(), InstanceId());
auto create_instance_request =
CreateInstanceRequestBuilder(
in, in.project().FullName() + "/instanceConfigs/emulator-config")
.Build();
auto instance = client_.CreateInstance(create_instance_request).get();
if (!instance) {
ASSERT_THAT(instance, StatusIs(StatusCode::kAlreadyExists));
}
}
}
internal::DefaultPRNG generator_;
spanner_admin::InstanceAdminClient client_;
};
/// @test Verify the basic read operations for instances work.
TEST_F(InstanceAdminClientTest, InstanceReadOperations) {
Instance in(ProjectId(), InstanceId());
ASSERT_FALSE(in.project_id().empty());
ASSERT_FALSE(in.instance_id().empty());
auto instance = client_.GetInstance(in.FullName());
ASSERT_STATUS_OK(instance);
EXPECT_EQ(instance->name(), in.FullName());
EXPECT_NE(instance->node_count(), 0);
auto instance_names = [&in, this]() mutable {
std::vector<std::string> names;
auto const parent = in.project().FullName();
for (auto const& instance : client_.ListInstances(parent)) {
EXPECT_STATUS_OK(instance);
if (!instance) break;
names.push_back(instance->name());
}
return names;
}();
EXPECT_EQ(1, std::count(instance_names.begin(), instance_names.end(),
instance->name()));
}
/// @test Verify the basic CRUD operations for instances work.
TEST_F(InstanceAdminClientTest, InstanceCRUDOperations) {
if (!Emulator() && !RunSlowInstanceTests()) {
GTEST_SKIP() << "skipping slow instance tests; set "
<< "GOOGLE_CLOUD_CPP_SPANNER_SLOW_INTEGRATION_TESTS=instance"
<< " to override";
}
std::string instance_id = spanner_testing::RandomInstanceName(generator_);
Instance in(ProjectId(), instance_id);
ASSERT_FALSE(in.project_id().empty());
ASSERT_FALSE(in.instance_id().empty());
auto instance_config = spanner_testing::PickInstanceConfig(
in.project_id(), std::regex(".*us-west.*"), generator_);
ASSERT_FALSE(instance_config.empty()) << "could not get an instance config";
auto instance =
client_
.CreateInstance(CreateInstanceRequestBuilder(in, instance_config)
.SetDisplayName("test-display-name")
.SetNodeCount(1)
.SetLabels({{"label-key", "label-value"}})
.Build())
.get();
ASSERT_STATUS_OK(instance);
EXPECT_EQ(instance->name(), in.FullName());
EXPECT_EQ(instance->display_name(), "test-display-name");
EXPECT_NE(instance->node_count(), 0);
EXPECT_EQ(instance->config(), instance_config);
EXPECT_EQ(instance->labels().at("label-key"), "label-value");
// Then update the instance
instance = client_
.UpdateInstance(UpdateInstanceRequestBuilder(*instance)
.SetDisplayName("New display name")
.AddLabels({{"new-key", "new-value"}})
.SetNodeCount(2)
.Build())
.get();
if (!Emulator() || instance) {
EXPECT_STATUS_OK(instance);
if (instance) {
EXPECT_EQ(instance->display_name(), "New display name");
EXPECT_EQ(instance->labels_size(), 2);
EXPECT_EQ(instance->labels().at("new-key"), "new-value");
EXPECT_EQ(instance->node_count(), 2);
}
}
EXPECT_STATUS_OK(client_.DeleteInstance(in.FullName()));
}
TEST_F(InstanceAdminClientTest, InstanceConfig) {
auto project_id = ProjectId();
ASSERT_FALSE(project_id.empty());
auto instance_config_names = [&project_id, this]() mutable {
std::vector<std::string> names;
auto const parent = Project(project_id).FullName();
for (auto const& instance_config : client_.ListInstanceConfigs(parent)) {
EXPECT_STATUS_OK(instance_config);
if (!instance_config) break;
names.push_back(instance_config->name());
}
return names;
}();
ASSERT_FALSE(instance_config_names.empty());
// Use the name of the first element from the list of instance configs.
auto instance_config = client_.GetInstanceConfig(instance_config_names[0]);
EXPECT_THAT(instance_config->name(), HasSubstr(project_id));
EXPECT_EQ(
1, std::count(instance_config_names.begin(), instance_config_names.end(),
instance_config->name()));
}
TEST_F(InstanceAdminClientTest, InstanceIam) {
Instance in(ProjectId(), InstanceId());
ASSERT_FALSE(in.project_id().empty());
ASSERT_FALSE(in.instance_id().empty());
ASSERT_FALSE(internal::GetEnv("GOOGLE_CLOUD_CPP_SPANNER_TEST_SERVICE_ACCOUNT")
.value_or("")
.empty());
auto actual_policy = client_.GetIamPolicy(in.FullName());
if (Emulator() &&
actual_policy.status().code() == StatusCode::kUnimplemented) {
GTEST_SKIP() << "emulator does not support IAM policies";
}
ASSERT_STATUS_OK(actual_policy);
EXPECT_FALSE(actual_policy->etag().empty());
if (RunSlowInstanceTests()) {
// Set the policy to the existing value of the policy. While this
// changes nothing, it tests all the code in the client library.
auto updated_policy = client_.SetIamPolicy(in.FullName(), *actual_policy);
ASSERT_THAT(updated_policy, AnyOf(IsOk(), StatusIs(StatusCode::kAborted)));
if (updated_policy) {
EXPECT_FALSE(updated_policy->etag().empty());
}
// Repeat the test using the OCC API.
updated_policy = client_.SetIamPolicy(
in.FullName(), [](google::iam::v1::Policy p) { return p; });
ASSERT_STATUS_OK(updated_policy);
EXPECT_FALSE(updated_policy->etag().empty());
}
auto actual = client_.TestIamPermissions(
in.FullName(), {"spanner.databases.list", "spanner.databases.get"});
ASSERT_STATUS_OK(actual);
EXPECT_THAT(
actual->permissions(),
UnorderedElementsAre("spanner.databases.list", "spanner.databases.get"));
}
} // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace spanner
} // namespace cloud
} // namespace google
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_ModernBed_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ModernBed.ModernBed_C
// 0x0000 (0x0F50 - 0x0F50)
class AModernBed_C : public ABedBaseBP_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass ModernBed.ModernBed_C");
return ptr;
}
void UserConstructionScript();
void ExecuteUbergraph_ModernBed(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
class Solution {
public:
int furthestBuilding(vector<int>& heights, int bricks, int ladders) {
const int N = heights.size();
priority_queue<int, vector<int>, greater<int>> minHeap;
for(int i = 0; i + 1 < N; ++i){
int diff = (heights[i + 1] - heights[i]);
if(diff > 0){
minHeap.push(diff);
}
if(minHeap.size() > ladders){
bricks -= minHeap.top();
minHeap.pop();
}
if(bricks < 0){
return i;
}
}
return N - 1;
}
};
|
#include "CondCore/PopCon/interface/PopConAnalyzer.h"
#include "CondTools/Hcal/interface/HcalLUTCorrsHandler.h"
#include "FWCore/Framework/interface/MakerMacros.h"
//typedef popcon::PopConAnalyzer<HcalLUTCorrsHandler> HcalLUTCorrsPopConAnalyzer;
class HcalLUTCorrsPopConAnalyzer : public popcon::PopConAnalyzer<HcalLUTCorrsHandler> {
public:
typedef HcalLUTCorrsHandler SourceHandler;
HcalLUTCorrsPopConAnalyzer(const edm::ParameterSet& pset)
: popcon::PopConAnalyzer<HcalLUTCorrsHandler>(pset),
m_populator(pset),
m_source(pset.getParameter<edm::ParameterSet>("Source")) {}
private:
void endJob() override {
m_source.initObject(myDBObject);
write();
}
void analyze(const edm::Event& ev, const edm::EventSetup& esetup) override {
//Using ES to get the data:
edm::ESHandle<HcalLUTCorrs> objecthandle;
esetup.get<HcalLUTCorrsRcd>().get(objecthandle);
myDBObject = new HcalLUTCorrs(*objecthandle.product());
}
void write() { m_populator.write(m_source); }
private:
popcon::PopCon m_populator;
SourceHandler m_source;
HcalLUTCorrs* myDBObject;
};
DEFINE_FWK_MODULE(HcalLUTCorrsPopConAnalyzer);
|
#include <iostream>
#include <list>
#include <memory>
#include <sstream>
struct Foo
{
Foo() : m_path_(new std::list<std::string>()) {}
Foo(Foo const& other) : m_path_(new std::list<std::string>(*other.m_path_))
{
std::cout << "Copy construct " << str() << std::endl;
};
Foo(Foo&& other) : m_path_(other.m_path_.release())
{
std::cout << "Move construct " << m_path_.get() << std::endl;
};
~Foo()
{
std::cout << "Deconstruct " << m_path_.get() << std::endl;
// m_path_.reset();
}
Foo operator[](const std::string& key) &&
{
m_path_->push_back(key);
return std::move(*this);
}
Foo operator[](const std::string& key) const&
{
Foo res(*this);
res.m_path_->push_back(key);
std::cout << res.str() << std::endl;
return std::move(res);
}
std::string str() const
{
std::ostringstream os;
if (m_path_ != nullptr)
{
for (auto&& item : *m_path_)
{
os << "/" << item;
}
}
return os.str();
}
std::unique_ptr<std::list<std::string>> m_path_;
};
int main(int argc, char** argv)
{
Foo v;
std::cout << v["a"]["b"]["C"].str() << std::endl;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Copyright (c) 2021 The eTitanium Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <txdb.h>
#include <node/ui_interface.h>
#include <pow.h>
#include <random.h>
#include <shutdown.h>
#include <uint256.h>
#include <util/memory.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/vector.h>
#include <stdint.h>
static const char DB_COIN = 'C';
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_BLOCK_INDEX = 'b';
static const char DB_BEST_BLOCK = 'B';
static const char DB_HEAD_BLOCKS = 'H';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';
namespace {
struct CoinEntry {
COutPoint* outpoint;
char key;
explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}
SERIALIZE_METHODS(CoinEntry, obj) { READWRITE(obj.key, obj.outpoint->hash, VARINT(obj.outpoint->n)); }
};
}
CCoinsViewDB::CCoinsViewDB(fs::path ldb_path, size_t nCacheSize, bool fMemory, bool fWipe) :
m_db(MakeUnique<CDBWrapper>(ldb_path, nCacheSize, fMemory, fWipe, true)),
m_ldb_path(ldb_path),
m_is_memory(fMemory) { }
void CCoinsViewDB::ResizeCache(size_t new_cache_size)
{
// Have to do a reset first to get the original `m_db` state to release its
// filesystem lock.
m_db.reset();
m_db = MakeUnique<CDBWrapper>(
m_ldb_path, new_cache_size, m_is_memory, /*fWipe*/ false, /*obfuscate*/ true);
}
bool CCoinsViewDB::GetCoin(const COutPoint &outpoint, Coin &coin) const {
return m_db->Read(CoinEntry(&outpoint), coin);
}
bool CCoinsViewDB::HaveCoin(const COutPoint &outpoint) const {
return m_db->Exists(CoinEntry(&outpoint));
}
uint256 CCoinsViewDB::GetBestBlock() const {
uint256 hashBestChain;
if (!m_db->Read(DB_BEST_BLOCK, hashBestChain))
return uint256();
return hashBestChain;
}
std::vector<uint256> CCoinsViewDB::GetHeadBlocks() const {
std::vector<uint256> vhashHeadBlocks;
if (!m_db->Read(DB_HEAD_BLOCKS, vhashHeadBlocks)) {
return std::vector<uint256>();
}
return vhashHeadBlocks;
}
bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
CDBBatch batch(*m_db);
size_t count = 0;
size_t changed = 0;
size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize);
int crash_simulate = gArgs.GetArg("-dbcrashratio", 0);
assert(!hashBlock.IsNull());
uint256 old_tip = GetBestBlock();
if (old_tip.IsNull()) {
// We may be in the middle of replaying.
std::vector<uint256> old_heads = GetHeadBlocks();
if (old_heads.size() == 2) {
assert(old_heads[0] == hashBlock);
old_tip = old_heads[1];
}
}
// In the first batch, mark the database as being in the middle of a
// transition from old_tip to hashBlock.
// A vector is used for future extensibility, as we may want to support
// interrupting after partial writes from multiple independent reorgs.
batch.Erase(DB_BEST_BLOCK);
batch.Write(DB_HEAD_BLOCKS, Vector(hashBlock, old_tip));
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
CoinEntry entry(&it->first);
if (it->second.coin.IsSpent())
batch.Erase(entry);
else
batch.Write(entry, it->second.coin);
changed++;
}
count++;
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
if (batch.SizeEstimate() > batch_size) {
LogPrint(BCLog::COINDB, "Writing partial batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
m_db->WriteBatch(batch);
batch.Clear();
if (crash_simulate) {
static FastRandomContext rng;
if (rng.randrange(crash_simulate) == 0) {
LogPrintf("Simulating a crash. Goodbye.\n");
_Exit(0);
}
}
}
}
// In the last batch, mark the database as consistent with hashBlock again.
batch.Erase(DB_HEAD_BLOCKS);
batch.Write(DB_BEST_BLOCK, hashBlock);
LogPrint(BCLog::COINDB, "Writing final batch of %.2f MiB\n", batch.SizeEstimate() * (1.0 / 1048576.0));
bool ret = m_db->WriteBatch(batch);
LogPrint(BCLog::COINDB, "Committed %u changed transaction outputs (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
return ret;
}
size_t CCoinsViewDB::EstimateSize() const
{
return m_db->EstimateSize(DB_COIN, (char)(DB_COIN+1));
}
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
return Read(std::make_pair(DB_BLOCK_FILES, nFile), info);
}
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
if (fReindexing)
return Write(DB_REINDEX_FLAG, '1');
else
return Erase(DB_REINDEX_FLAG);
}
void CBlockTreeDB::ReadReindexing(bool &fReindexing) {
fReindexing = Exists(DB_REINDEX_FLAG);
}
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
return Read(DB_LAST_BLOCK, nFile);
}
CCoinsViewCursor *CCoinsViewDB::Cursor() const
{
CCoinsViewDBCursor *i = new CCoinsViewDBCursor(const_cast<CDBWrapper&>(*m_db).NewIterator(), GetBestBlock());
/* It seems that there are no "const iterators" for LevelDB. Since we
only need read operations on it, use a const-cast to get around
that restriction. */
i->pcursor->Seek(DB_COIN);
// Cache key of first record
if (i->pcursor->Valid()) {
CoinEntry entry(&i->keyTmp.second);
i->pcursor->GetKey(entry);
i->keyTmp.first = entry.key;
} else {
i->keyTmp.first = 0; // Make sure Valid() and GetKey() return false
}
return i;
}
bool CCoinsViewDBCursor::GetKey(COutPoint &key) const
{
// Return cached key
if (keyTmp.first == DB_COIN) {
key = keyTmp.second;
return true;
}
return false;
}
bool CCoinsViewDBCursor::GetValue(Coin &coin) const
{
return pcursor->GetValue(coin);
}
unsigned int CCoinsViewDBCursor::GetValueSize() const
{
return pcursor->GetValueSize();
}
bool CCoinsViewDBCursor::Valid() const
{
return keyTmp.first == DB_COIN;
}
void CCoinsViewDBCursor::Next()
{
pcursor->Next();
CoinEntry entry(&keyTmp.second);
if (!pcursor->Valid() || !pcursor->GetKey(entry)) {
keyTmp.first = 0; // Invalidate cached key after last record so that Valid() and GetKey() return false
} else {
keyTmp.first = entry.key;
}
}
bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
CDBBatch batch(*this);
for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
batch.Write(std::make_pair(DB_BLOCK_FILES, it->first), *it->second);
}
batch.Write(DB_LAST_BLOCK, nLastFile);
for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
batch.Write(std::make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
}
return WriteBatch(batch, true);
}
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
char ch;
if (!Read(std::make_pair(DB_FLAG, name), ch))
return false;
fValue = ch == '1';
return true;
}
bool CBlockTreeDB::LoadBlockIndexGuts(const Consensus::Params& consensusParams, std::function<CBlockIndex*(const uint256&)> insertBlockIndex)
{
std::unique_ptr<CDBIterator> pcursor(NewIterator());
pcursor->Seek(std::make_pair(DB_BLOCK_INDEX, uint256()));
// Load m_block_index
while (pcursor->Valid()) {
if (ShutdownRequested()) return false;
std::pair<char, uint256> key;
if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
CDiskBlockIndex diskindex;
if (pcursor->GetValue(diskindex)) {
// Construct block index object
CBlockIndex* pindexNew = insertBlockIndex(diskindex.GetBlockHash());
pindexNew->pprev = insertBlockIndex(diskindex.hashPrev);
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nFile = diskindex.nFile;
pindexNew->nDataPos = diskindex.nDataPos;
pindexNew->nUndoPos = diskindex.nUndoPos;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
pindexNew->nStatus = diskindex.nStatus;
pindexNew->nTx = diskindex.nTx;
if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, consensusParams))
return error("%s: CheckProofOfWork failed: %s", __func__, pindexNew->ToString());
pcursor->Next();
} else {
return error("%s: failed to read value", __func__);
}
} else {
break;
}
}
return true;
}
namespace {
//! Legacy class to deserialize pre-pertxout database entries without reindex.
class CCoins
{
public:
//! whether transaction is a coinbase
bool fCoinBase;
//! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
std::vector<CTxOut> vout;
//! at which height this transaction was included in the active block chain
int nHeight;
//! empty constructor
CCoins() : fCoinBase(false), vout(0), nHeight(0) { }
template<typename Stream>
void Unserialize(Stream &s) {
unsigned int nCode = 0;
// version
unsigned int nVersionDummy;
::Unserialize(s, VARINT(nVersionDummy));
// header code
::Unserialize(s, VARINT(nCode));
fCoinBase = nCode & 1;
std::vector<bool> vAvail(2, false);
vAvail[0] = (nCode & 2) != 0;
vAvail[1] = (nCode & 4) != 0;
unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
// spentness bitmask
while (nMaskCode > 0) {
unsigned char chAvail = 0;
::Unserialize(s, chAvail);
for (unsigned int p = 0; p < 8; p++) {
bool f = (chAvail & (1 << p)) != 0;
vAvail.push_back(f);
}
if (chAvail != 0)
nMaskCode--;
}
// txouts themself
vout.assign(vAvail.size(), CTxOut());
for (unsigned int i = 0; i < vAvail.size(); i++) {
if (vAvail[i])
::Unserialize(s, Using<TxOutCompression>(vout[i]));
}
// coinbase height
::Unserialize(s, VARINT_MODE(nHeight, VarIntMode::NONNEGATIVE_SIGNED));
}
};
}
/** Upgrade the database from older formats.
*
* Currently implemented: from the per-tx utxo model (0.8..0.14.x) to per-txout.
*/
bool CCoinsViewDB::Upgrade() {
std::unique_ptr<CDBIterator> pcursor(m_db->NewIterator());
pcursor->Seek(std::make_pair(DB_COINS, uint256()));
if (!pcursor->Valid()) {
return true;
}
int64_t count = 0;
LogPrintf("Upgrading utxo-set database...\n");
LogPrintf("[0%%]..."); /* Continued */
uiInterface.ShowProgress(_("Upgrading UTXO database").translated, 0, true);
size_t batch_size = 1 << 24;
CDBBatch batch(*m_db);
int reportDone = 0;
std::pair<unsigned char, uint256> key;
std::pair<unsigned char, uint256> prev_key = {DB_COINS, uint256()};
while (pcursor->Valid()) {
if (ShutdownRequested()) {
break;
}
if (pcursor->GetKey(key) && key.first == DB_COINS) {
if (count++ % 256 == 0) {
uint32_t high = 0x100 * *key.second.begin() + *(key.second.begin() + 1);
int percentageDone = (int)(high * 100.0 / 65536.0 + 0.5);
uiInterface.ShowProgress(_("Upgrading UTXO database").translated, percentageDone, true);
if (reportDone < percentageDone/10) {
// report max. every 10% step
LogPrintf("[%d%%]...", percentageDone); /* Continued */
reportDone = percentageDone/10;
}
}
CCoins old_coins;
if (!pcursor->GetValue(old_coins)) {
return error("%s: cannot parse CCoins record", __func__);
}
COutPoint outpoint(key.second, 0);
for (size_t i = 0; i < old_coins.vout.size(); ++i) {
if (!old_coins.vout[i].IsNull() && !old_coins.vout[i].scriptPubKey.IsUnspendable()) {
Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight, old_coins.fCoinBase);
outpoint.n = i;
CoinEntry entry(&outpoint);
batch.Write(entry, newcoin);
}
}
batch.Erase(key);
if (batch.SizeEstimate() > batch_size) {
m_db->WriteBatch(batch);
batch.Clear();
m_db->CompactRange(prev_key, key);
prev_key = key;
}
pcursor->Next();
} else {
break;
}
}
m_db->WriteBatch(batch);
m_db->CompactRange({DB_COINS, uint256()}, key);
uiInterface.ShowProgress("", 100, false);
LogPrintf("[%s].\n", ShutdownRequested() ? "CANCELLED" : "DONE");
return !ShutdownRequested();
}
|
#include <stdio.h>
int main(){
int matriz[4][7], soma=0, maiorValor=0;
int somaP;
int binario[50];
for(int i = 0; i<4; i++){
for(int j = 0; j < 7; j++){
scanf("%d", &matriz[i][j]);
soma = soma + matriz[i][j];
}
if(soma>maiorValor){
maiorValor = soma;
somaP = soma;
}
soma = 0;
}
int i = 0;
while(maiorValor!=1){
binario[i] = maiorValor%2;
maiorValor = maiorValor/2;
i++;
// printf("o valor de i é: %d \n", i);
}
binario[i] = 1;
int k = i;
printf("%d = ", somaP);
while(k>=0){
printf("%d", binario[k]);
k--;
}
// for(k; k>=0; k--){
// printf("%d", binario[k]);
// }
printf("\n");
return 0;
}
/*printf("i = %d >>", i);
binario[i] = maiorValor%2;
maiorValor = maiorValor/2;
i++;
if(maiorValor==2){
break;}
printf("i = %d\n", i);
printf("VALOR DO maiorValor %d\n", maiorValor);*/
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include "base/auto_reset.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
#include "base/memory/scoped_ptr.h"
#include "base/observer_list.h"
#include "base/posix/eintr_wrapper.h"
#include "base/time.h"
#include "event.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_nsautorelease_pool.h"
#endif
// Lifecycle of struct event
// Libevent uses two main data structures:
// struct event_base (of which there is one per message pump), and
// struct event (of which there is roughly one per socket).
// The socket's struct event is created in
// MessagePumpLibevent::WatchFileDescriptor(),
// is owned by the FileDescriptorWatcher, and is destroyed in
// StopWatchingFileDescriptor().
// It is moved into and out of lists in struct event_base by
// the libevent functions event_add() and event_del().
//
// TODO(dkegel):
// At the moment bad things happen if a FileDescriptorWatcher
// is active after its MessagePumpLibevent has been destroyed.
// See MessageLoopTest.FileDescriptorWatcherOutlivesMessageLoop
// Not clear yet whether that situation occurs in practice,
// but if it does, we need to fix it.
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: event_(NULL),
pump_(NULL),
watcher_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_) {
StopWatchingFileDescriptor();
}
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
event* e = ReleaseEvent();
if (e == NULL)
return true;
// event_del() is a no-op if the event isn't active.
int rv = event_del(e);
delete e;
pump_ = NULL;
watcher_ = NULL;
return (rv == 0);
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e) {
DCHECK(e);
DCHECK(!event_);
event_ = e;
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
struct event *e = event_;
event_ = NULL;
return e;
}
void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanReadWithoutBlocking(
int fd, MessagePumpLibevent* pump) {
// Since OnFileCanWriteWithoutBlocking() gets called first, it can stop
// watching the file descriptor.
if (!watcher_)
return;
pump->WillProcessIOEvent();
watcher_->OnFileCanReadWithoutBlocking(fd);
pump->DidProcessIOEvent();
}
void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking(
int fd, MessagePumpLibevent* pump) {
DCHECK(watcher_);
pump->WillProcessIOEvent();
watcher_->OnFileCanWriteWithoutBlocking(fd);
pump->DidProcessIOEvent();
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
processed_io_events_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
if (wakeup_pipe_in_ >= 0) {
if (HANDLE_EINTR(close(wakeup_pipe_in_)) < 0)
DPLOG(ERROR) << "close";
}
if (wakeup_pipe_out_ >= 0) {
if (HANDLE_EINTR(close(wakeup_pipe_out_)) < 0)
DPLOG(ERROR) << "close";
}
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
int mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK_GE(fd, 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
// WatchFileDescriptor should be called on the pump thread. It is not
// threadsafe, and your watcher may never be registered.
DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread());
int event_mask = persistent ? EV_PERSIST : 0;
if (mode & WATCH_READ) {
event_mask |= EV_READ;
}
if (mode & WATCH_WRITE) {
event_mask |= EV_WRITE;
}
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
// Ownership is transferred to the controller.
evt.reset(new event);
} else {
// Make sure we don't pick up any funky internal libevent masks.
int old_interest_mask = evt.get()->ev_events &
(EV_READ | EV_WRITE | EV_PERSIST);
// Combine old/new event masks.
event_mask |= old_interest_mask;
// Must disarm the event before we can reuse it.
event_del(evt.get());
// It's illegal to use this function to listen on 2 separate fds with the
// same |controller|.
if (EVENT_FD(evt.get()) != fd) {
NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd;
return false;
}
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification, controller);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get())) {
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL)) {
return false;
}
// Transfer ownership of evt to controller.
controller->Init(evt.release());
controller->set_watcher(delegate);
controller->set_pump(this);
return true;
}
void MessagePumpLibevent::AddIOObserver(IOObserver *obs) {
io_observers_.AddObserver(obs);
}
void MessagePumpLibevent::RemoveIOObserver(IOObserver *obs) {
io_observers_.RemoveObserver(obs);
}
// Tell libevent to break out of inner loop.
static void timer_callback(int fd, short events, void *context)
{
event_base_loopbreak((struct event_base *)context);
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
base::AutoReset<bool> auto_reset_in_run(&in_run_, true);
// event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
// Instead, make our own timer and reuse it on each call to event_base_loop().
scoped_ptr<event> timer_event(new event);
for (;;) {
#if defined(OS_MACOSX)
mac::ScopedNSAutoreleasePool autorelease_pool;
#endif
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
event_base_loop(event_base_, EVLOOP_NONBLOCK);
did_work |= processed_io_events_;
processed_io_events_ = false;
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - TimeTicks::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_set(timer_event.get(), -1, 0, timer_callback, event_base_);
event_base_set(event_base_, timer_event.get());
event_add(timer_event.get(), &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
event_del(timer_event.get());
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = TimeTicks();
}
}
}
keep_running_ = true;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = HANDLE_EINTR(write(wakeup_pipe_in_, &buf, 1));
DCHECK(nwrite == 1 || errno == EAGAIN)
<< "[nwrite:" << nwrite << "] [errno:" << errno << "]";
}
void MessagePumpLibevent::ScheduleDelayedWork(
const TimeTicks& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
void MessagePumpLibevent::WillProcessIOEvent() {
FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
}
void MessagePumpLibevent::DidProcessIOEvent() {
FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
// static
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
base::WeakPtr<FileDescriptorWatcher> controller =
static_cast<FileDescriptorWatcher*>(context)->weak_factory_.GetWeakPtr();
DCHECK(controller.get());
MessagePumpLibevent* pump = controller->pump();
pump->processed_io_events_ = true;
if (flags & EV_WRITE) {
controller->OnFileCanWriteWithoutBlocking(fd, pump);
}
// Check |controller| in case it's been deleted in
// controller->OnFileCanWriteWithoutBlocking().
if (controller.get() && flags & EV_READ) {
controller->OnFileCanReadWithoutBlocking(fd, pump);
}
}
// Called if a byte is received on the wakeup pipe.
// static
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = HANDLE_EINTR(read(socket, &buf, 1));
DCHECK_EQ(nread, 1);
that->processed_io_events_ = true;
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
} // namespace base
|
/*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <assert.h>
#include <float.h>
#include "c_types_map.hpp"
#include "memory_tracking.hpp"
#include "mkldnn_thread.hpp"
#include "nstl.hpp"
#include "type_helpers.hpp"
#include "utils.hpp"
#include "cpu_memory.hpp"
#include "cpu_barrier.hpp"
#include "jit_uni_1x1_conv_utils.hpp"
#include "jit_avx512_common_1x1_conv_kernel.hpp"
#define GET_OFF(field) offsetof(jit_1x1_conv_call_s, field)
namespace mkldnn {
namespace impl {
namespace cpu {
using namespace mkldnn::impl::prop_kind;
using namespace mkldnn::impl::memory_format;
using namespace mkldnn::impl::utils;
using namespace Xbyak;
void jit_avx512_common_1x1_conv_kernel::bcast_loop(int load_loop_blk)
{
mov(aux1_reg_bcast_data, reg_bcast_data);
mov(aux_reg_bcast_data, reg_bcast_data);
mov(aux_reg_output_data, reg_output_data);
mov(bcast_loop_iter, EVEX_compress_addr(rsp, bcast_loop_work_offt));
if (jcp.ver == ver_4fma)
{
Label bcast_loop;
Label bcast_loop_wraparound;
Label bcast_loop_out;
Label bcast_loop_ur_full;
cmp(bcast_loop_iter, jcp.ur);
jle(bcast_loop_wraparound, T_NEAR);
L(bcast_loop); {
assert(jcp.bcast_block % jcp.ur == 0);
int num_substeps = jcp.bcast_block / jcp.ur;
assert(num_substeps > 0 && num_substeps < 10);
for (int i = 0; i < num_substeps; i++) {
reduce_loop(load_loop_blk, jcp.ur, i, false);
if (i < num_substeps - 1) {
add(aux1_reg_bcast_data, jcp.bcast_loop_bcast_substep);
add(aux_reg_output_data, jcp.bcast_loop_output_substep);
}
else {
add(aux1_reg_bcast_data, jcp.bcast_loop_bcast_step
- (num_substeps - 1) * jcp.bcast_loop_bcast_substep);
add(aux_reg_output_data, jcp.bcast_loop_output_step
- (num_substeps - 1) * jcp.bcast_loop_output_substep);
}
}
sub(bcast_loop_iter, jcp.bcast_block);
cmp(bcast_loop_iter, jcp.bcast_block);
jg(bcast_loop, T_NEAR);
}
L(bcast_loop_wraparound);
if (jcp.ur_tail) {
je(bcast_loop_ur_full, T_NEAR);
reduce_loop(load_loop_blk, jcp.ur_tail, 0, true);
jmp(bcast_loop_out, T_NEAR);
}
L(bcast_loop_ur_full);
reduce_loop(load_loop_blk, jcp.ur, 0, true);
L(bcast_loop_out);
}
else
{
Label bcast_loop;
Label bcast_loop_tail;
cmp(bcast_loop_iter, jcp.ur);
jl(bcast_loop_tail, T_NEAR);
L(bcast_loop); {
assert(jcp.bcast_block % jcp.ur == 0);
int num_substeps = jcp.bcast_block / jcp.ur;
assert(num_substeps > 0 && num_substeps < 10);
for (int i = 0; i < num_substeps; i++) {
reduce_loop(load_loop_blk, jcp.ur, i, false);
if (i < num_substeps - 1) {
add(aux1_reg_bcast_data, jcp.bcast_loop_bcast_substep);
add(aux_reg_output_data, jcp.bcast_loop_output_substep);
}
else {
add(aux1_reg_bcast_data, jcp.bcast_loop_bcast_step
- (num_substeps - 1) * jcp.bcast_loop_bcast_substep);
add(aux_reg_output_data, jcp.bcast_loop_output_step
- (num_substeps - 1) * jcp.bcast_loop_output_substep);
}
}
sub(bcast_loop_iter, jcp.bcast_block);
cmp(bcast_loop_iter, jcp.bcast_block);
jge(bcast_loop, T_NEAR);
}
L(bcast_loop_tail);
if (jcp.ur_tail) {
Label bcast_loop_tail_out;
cmp(bcast_loop_iter, 0);
jz(bcast_loop_tail_out, T_NEAR);
reduce_loop(load_loop_blk, jcp.ur_tail, 0, true);
L(bcast_loop_tail_out);
}
}
}
void jit_avx512_common_1x1_conv_kernel::reduce_loop(int load_loop_blk,
int ur, int substep, bool wraparound)
{
auto vreg_load = [=](int i_load, int i_fma) {
return Zmm(utils::rnd_up(ur * load_loop_blk, jcp.fma_step)
+ jcp.fma_step * i_load + i_fma);
};
auto vreg_accum = [=](int i_load, int i_ur) {
return Zmm(i_ur + i_load * ur);
};
auto bias_ptr = [=](int i_load) {
return EVEX_compress_addr(reg_bias_data,
jcp.typesize_out * jcp.oc_block * i_load);
};
auto bcast_ptr = [=](int i_reduce, int i_ur, bool bcast) {
assert(i_ur < jcp.ur);
assert(i_reduce <= jcp.reduce_loop_unroll);
int offt;
if (one_of(jcp.prop_kind, forward_training, forward_inference,
backward_data)) {
assert(jcp.reduce_loop_unroll == jcp.reduce_block);
offt = (i_reduce == jcp.reduce_loop_unroll)
? (jcp.bcast_dim + i_ur) * jcp.reduce_loop_unroll
: i_ur * jcp.reduce_loop_unroll + i_reduce;
} else {
if (jcp.transpose_src) {
const int reduce_group = i_reduce / 4;
const int reduce_shift = i_reduce % 4;
offt = 4 * (reduce_group * jcp.ic_block + i_ur) + reduce_shift;
}
else
offt = i_reduce * jcp.ic_block + i_ur;
}
return EVEX_compress_addr(aux_reg_bcast_data, jcp.typesize_in * offt,
bcast);
};
auto load_ptr = [=](int i_reduce, int i_load) {
int offt;
int u0 = i_reduce % jcp.reduce_loop_unroll;
int u1 = i_reduce / jcp.reduce_loop_unroll;
if (jcp.prop_kind == backward_data && jcp.ver == ver_4vnni)
offt = (i_load * jcp.reduce_block + u0) * jcp.load_block;
else
offt = (i_load * jcp.reduce_dim + u0) * jcp.load_block;
return EVEX_compress_addr(aux_reg_load_data,
u1 * jcp.reduce_loop_load_step
+ jcp.typesize_in * offt);
};
auto output_ptr = [=](int i_load, int i_ur) {
if (one_of(jcp.prop_kind, forward_training, forward_inference,
backward_data))
return EVEX_compress_addr(aux_reg_output_data,
(i_load * jcp.bcast_dim + i_ur) * jcp.load_block
* jcp.typesize_out);
else
return ptr[aux_reg_output_data +
(i_load
? reg_output_stride * i_load
: 0) // TODO: Xbyak should allow 0 scale
+ jcp.typesize_out * jcp.load_block * i_ur];
};
auto init = [=]() {
Label init_done;
Label init_zero;
if (jcp.with_sum) {
for (int i_load = 0; i_load < load_loop_blk; ++i_load) {
for (int i_ur = 0; i_ur < ur; ++i_ur) {
mic_prefetcht1(output_ptr(i_load, i_ur));
}
}
}
if (jcp.with_bias
&& one_of(jcp.prop_kind, forward_training, forward_inference)) {
test(reg_reduce_pos_flag, FLAG_REDUCE_FIRST);
jz(init_zero, T_NEAR);
for (int i_load = 0; i_load < load_loop_blk; i_load++)
for (int i_ur = 0; i_ur < ur; ++i_ur)
vmovups(vreg_accum(i_load, i_ur), bias_ptr(i_load));
jmp(init_done, T_NEAR);
}
L(init_zero);
for (int i_load = 0; i_load < load_loop_blk; ++i_load)
for (int i_ur = 0; i_ur < ur; ++i_ur) {
auto r = vreg_accum(i_load, i_ur);
vpxord(r, r, r);
}
L(init_done);
};
auto vadd = [=](const Xmm& x1, const Xmm& x2, const Operand& op) {
if (jcp.ver == ver_4vnni)
vpaddd(x1, x2, op);
else
vaddps(x1, x2, op);
};
auto store = [=]() {
Label store_noadd;
if (!jcp.with_sum) {
test(reg_reduce_pos_flag, FLAG_REDUCE_FIRST);
jnz(store_noadd, T_NEAR);
}
for (int i_ur = 0; i_ur < ur; ++i_ur)
for (int i_load = 0; i_load < load_loop_blk; ++i_load) {
auto r = vreg_accum(i_load, i_ur);
vadd(r, r, output_ptr(i_load, i_ur));
}
L(store_noadd);
Label store_nopostproc;
test(reg_reduce_pos_flag, FLAG_REDUCE_LAST);
jz(store_nopostproc, T_NEAR);
int eltwise_inj_idx = 0;
int depthwise_inj_idx = 0;
const auto &p = attr_.post_ops_;
for (int i = 0; i < p.len_; i++) {
auto& post_op = p.entry_[i];
if (post_op.is_eltwise()) {
if (jcp.ver == ver_4vnni) {
zmm_t zmm_zero = vreg_bcast;
vpxord(zmm_zero, zmm_zero, zmm_zero);
for (int i_ur = 0; i_ur < ur; ++i_ur) {
for (int i_load = 0; i_load < load_loop_blk; ++i_load) {
Zmm zmm = vreg_accum(i_load, i_ur);
vpcmpd(k1, zmm, zmm_zero, _cmp_lt_os);
vpmulld(zmm | k1, zmm, zmm_zero);
}
}
} else {
eltwise_injectors[eltwise_inj_idx]->compute_vector_range(0, ur * load_loop_blk);
}
eltwise_inj_idx++;
} else if (post_op.is_depthwise()) {
mov(reg_d_weights, reinterpret_cast<size_t>(post_op.depthwise.weights_data));
mov(reg_d_bias, reinterpret_cast<size_t>(post_op.depthwise.biases_data));
add(reg_d_weights, reg_oc_off);
add(reg_d_bias, reg_oc_off);
for (int j = 0; j < load_loop_blk; ++j) {
int start_idx = vreg_accum(j, 0).getIdx();
int end_idx = start_idx + ur;
depthwise_injectors[depthwise_inj_idx]->compute_vector_range(
start_idx, end_idx, reg_d_weights, reg_d_bias);
add(reg_d_weights, jcp.oc_block * sizeof(float));
add(reg_d_bias, jcp.oc_block * sizeof(float));
}
depthwise_inj_idx++;
}
}
L(store_nopostproc);
auto store_output = [=](bool output_is_aligned) {
for (int i_ur = 0; i_ur < ur; ++i_ur)
for (int i_load = 0; i_load < load_loop_blk; ++i_load)
if (output_is_aligned && jcp.use_vmovntps)
vmovntps(output_ptr(i_load, i_ur),
vreg_accum(i_load, i_ur));
else
vmovups(output_ptr(i_load, i_ur),
vreg_accum(i_load, i_ur));
};
Label unaligned_store, end_store;
test(aux_reg_output_data, cpu_isa_traits<avx512_common>::vlen - 1);
jnz(unaligned_store, T_NEAR);
store_output(true);
jmp(end_store, T_NEAR);
L(unaligned_store); {
store_output(false);
}
L(end_store);
};
auto prefetch_callback = [=](int ur, int i_reduce, int i_ur, int i_load,
bool last_block, bool wraparound, int reduce_step)
{
bool pf_ker_l1 = true;
bool pf_ker_l2 = wraparound;
int n_ops = (jcp.reduce_loop_unroll / reduce_step) * ur * load_loop_blk;
int i_op = (i_reduce / reduce_step) * ur * load_loop_blk +
i_ur * load_loop_blk + i_load;
int n_pf_ker_l1 = pf_ker_l1 ? jcp.reduce_block : 0;
int n_pf_ker_l2 = pf_ker_l2 && wraparound ? jcp.reduce_block : 0;
int n_pf_out_l1 = jcp.use_vmovntps ? 0 : ur;
int pf_inp_ops = n_ops / 2; // # of operations during which to pf input
int pf_inp_trigger;
if (jcp.prop_kind == backward_weights)
pf_inp_trigger = nstl::max(1, pf_inp_ops / jcp.reduce_block);
else
pf_inp_trigger = nstl::max(1, pf_inp_ops / ur);
int n_other_pf =
load_loop_blk * (n_pf_ker_l1 + n_pf_ker_l2 + n_pf_out_l1);
int n_other_pf_ops = n_ops - pf_inp_ops;
int other_pf_trigger
= n_other_pf ? nstl::max(1, n_other_pf_ops / n_other_pf) : 0;
if (i_op < pf_inp_ops && i_op % pf_inp_trigger == 0) {
// input prefetches have the highest priority b/c the
// first iteration of the kernel block touches all the
// cache lines
int i_pf = i_op / pf_inp_trigger;
auto pf_reg = wraparound && last_block
? reg_bcast_data
: (last_block ? aux1_reg_bcast_data
: aux_reg_bcast_data);
int offt = i_pf;
if (jcp.prop_kind == backward_weights) {
offt += wraparound && last_block
? 0
: (last_block ? jcp.is : jcp.reduce_block);
offt *= jcp.bcast_block;
} else {
offt += wraparound && last_block
? 0
: (last_block ? jcp.ur : jcp.bcast_dim);
offt *= jcp.reduce_block;
}
mic_prefetcht0(ptr[pf_reg + offt * jcp.typesize_in]);
} else if (i_op >= pf_inp_ops && n_other_pf) {
// remaining prefetches are spread among the rest of the
// operations; prefetches for output take priority
// TODO: spread L2 prefetches among L1 prefetches
i_op -= pf_inp_ops;
if (i_op % other_pf_trigger == 0) {
int i_pf = i_op / (load_loop_blk * other_pf_trigger);
if (i_pf < n_pf_ker_l2) {
int offt = (i_pf + (i_load + 1) * jcp.reduce_dim)
* jcp.load_block;
if (jcp.prop_kind == backward_data && jcp.ver == ver_4vnni)
offt = (i_pf + (i_load + 1) * jcp.reduce_block)
* jcp.load_block;
mic_prefetcht1(ptr[aux_reg_load_data
+ offt * jcp.typesize_in]);
} else if (i_pf < n_pf_ker_l2 + n_pf_ker_l1) {
i_pf -= n_pf_ker_l2;
auto pf_reg = last_block ? reg_load_data
: aux_reg_load_data;
int offt = (i_pf + i_load * jcp.reduce_dim
+ (last_block
? (wraparound ? jcp.reduce_dim : 0)
: jcp.reduce_block))
* jcp.load_block;
mic_prefetcht0(ptr[pf_reg + offt * jcp.typesize_in]);
} else if (i_pf < n_pf_ker_l1 + n_pf_ker_l2 + n_pf_out_l1) {
i_pf -= n_pf_ker_l1 + n_pf_ker_l2;
int offt = i_pf * jcp.load_block;
mic_prefetcht0(ptr[aux_reg_output_data
+ offt * jcp.typesize_out]);
}
}
}
};
auto fma_block = [=](bool last_block) {
assert(jcp.reduce_loop_unroll % jcp.fma_step == 0);
int reduce_step = jcp.fma_step;
if (jcp.ver == ver_4vnni)
reduce_step *= 2;
for (int i_reduce = 0; i_reduce < jcp.reduce_loop_unroll;
i_reduce += reduce_step) {
int load_scale = (jcp.ver == ver_4vnni) ? 2 : 1;
for (int i_load = 0; i_load < load_loop_blk; ++i_load) {
// if transposed input data used and if spatial size is
// not divided by transpose step (4) then for last reduce step
// we should load only needed load_registers data
// and clear remaining
if (jcp.transpose_src && jcp.is % jcp.fma_step && last_block
&& i_reduce == jcp.reduce_loop_unroll - reduce_step) {
Label load_all;
Label load_finish;
test(reg_reduce_pos_flag, FLAG_SP_LAST);
jz(load_all, T_NEAR);
const int n_loads = jcp.is % jcp.fma_step;
for (int i_fma = 0; i_fma < jcp.fma_step; i_fma++) {
if (i_fma < n_loads)
vmovups(vreg_load(i_load, i_fma),
load_ptr(i_reduce + load_scale * i_fma,
i_load));
else
vpxord(vreg_load(i_load, i_fma),
vreg_load(i_load, i_fma),
vreg_load(i_load, i_fma));
}
jmp(load_finish);
L(load_all);
for (int i_fma = 0; i_fma < jcp.fma_step; i_fma++) {
vmovups(vreg_load(i_load, i_fma),
load_ptr(i_reduce + load_scale * i_fma, i_load));
}
L(load_finish);
} else {
for (int i_fma = 0; i_fma < jcp.fma_step; i_fma++) {
vmovups(vreg_load(i_load, i_fma),
load_ptr(i_reduce
+ load_scale * i_fma,
i_load));
}
}
}
for (int i_ur = 0; i_ur < ur; ++i_ur) {
if (jcp.ver == ver_avx512_core && jcp.expl_bcast
&& load_loop_blk > 1)
vbroadcastss(vreg_bcast, bcast_ptr(i_reduce, i_ur, false));
for (int i_load = 0; i_load < load_loop_blk; ++i_load) {
if (jcp.ver == ver_4fma)
v4fmaddps(vreg_accum(i_load, i_ur),
vreg_load(i_load, 0),
bcast_ptr(i_reduce, i_ur, false));
else if (jcp.ver == ver_4vnni)
vp4dpwssd(vreg_accum(i_load, i_ur),
vreg_load(i_load, 0),
bcast_ptr(i_reduce, i_ur, false));
else if (jcp.ver == ver_avx512_core && jcp.expl_bcast
&& load_loop_blk > 1)
vfmadd231ps(vreg_accum(i_load, i_ur),
vreg_load(i_load, 0), vreg_bcast);
else
vfmadd231ps(vreg_accum(i_load, i_ur),
vreg_load(i_load, 0),
bcast_ptr(i_reduce, i_ur, true));
prefetch_callback(ur, i_reduce, i_ur, i_load,
last_block, wraparound, reduce_step);
}
}
}
};
Label reduce_loop;
Label reduce_loop_tail;
mov(aux_reg_load_data, reg_load_data);
mov(aux_reg_bcast_data, aux1_reg_bcast_data);
init();
mov(reduce_loop_iter, reg_reduce_loop_work);
sub(reduce_loop_iter, jcp.reduce_loop_unroll);
jle(reduce_loop_tail, T_NEAR);
L(reduce_loop); {
fma_block(false);
add(aux_reg_bcast_data, jcp.reduce_loop_bcast_step);
add(aux_reg_load_data, jcp.reduce_loop_load_step);
sub(reduce_loop_iter, jcp.reduce_loop_unroll);
jg(reduce_loop, T_NEAR);
}
L(reduce_loop_tail);
fma_block(true);
store();
}
void jit_avx512_common_1x1_conv_kernel::generate()
{
const auto &p = attr_.post_ops_;
for (int i = 0; i < p.len_; i++) {
auto &post_op = p.entry_[i];
if (post_op.is_eltwise()) {
eltwise_injectors.push_back(new jit_uni_eltwise_injector_f32<avx512_common>(
this,
post_op.eltwise.alg,
post_op.eltwise.alpha,
post_op.eltwise.beta
));
} else if (post_op.is_depthwise()) {
depthwise_injectors.push_back(new jit_uni_depthwise_injector_f32<avx512_common>(
this,
post_op.depthwise.alg
));
}
}
preamble();
mov(reg_bcast_data, ptr[param1 + GET_OFF(bcast_data)]);
mov(reg_load_data, ptr[param1 + GET_OFF(load_data)]);
mov(reg_output_data, ptr[param1 + GET_OFF(output_data)]);
sub(rsp, stack_space_needed);
if (jcp.with_bias)
mov(reg_bias_data, ptr[param1 + GET_OFF(bias_data)]);
mov(reg_load_loop_work, ptr[param1 + GET_OFF(load_dim)]);
mov(reg_bcast_loop_work, ptr[param1 + GET_OFF(bcast_dim)]);
mov(EVEX_compress_addr(rsp, bcast_loop_work_offt), reg_bcast_loop_work);
mov(reg_reduce_loop_work, ptr[param1 + GET_OFF(reduce_dim)]);
mov(reg_reduce_pos_flag, ptr[param1 + GET_OFF(first_last_flag)]);
if (one_of(jcp.prop_kind, forward_training, forward_inference))
mov(reg_relu_ns, reinterpret_cast<size_t>(&jcp.eltwise.alpha));
if (jcp.prop_kind == backward_weights)
mov(reg_output_stride, ptr[param1 + GET_OFF(output_stride)]);
mov(reg_oc_off, ptr[param1 + GET_OFF(oc_off)]);
auto load_loop_body = [=](int load_loop_blk) {
bcast_loop(load_loop_blk);
add(reg_load_data, load_loop_blk * jcp.load_loop_load_step);
switch (jcp.prop_kind) {
case forward_training:
case forward_inference:
add(reg_bias_data,
load_loop_blk * jcp.load_block * jcp.typesize_out);
add(reg_output_data,
load_loop_blk * jcp.bcast_dim * jcp.load_block *
jcp.typesize_out);
break;
case backward_data:
add(reg_output_data,
load_loop_blk * jcp.bcast_dim * jcp.load_block *
jcp.typesize_out);
break;
case backward_weights:
for (int i_load = 0; i_load < load_loop_blk; i_load++)
add(reg_output_data, reg_output_stride);
break;
default:
assert(!"invalid prop_kind");
}
sub(reg_load_loop_work, load_loop_blk * jcp.load_loop_iter_step);
add(reg_oc_off, load_loop_blk * jcp.oc_block * jcp.typesize_out);
};
const int simd_w = 16;
Label load_loop_blk[7];
static const int ur_cases_fma_embd_bcast[] = { 2, 4, 5, 8, 14, 32 };
static const int ur_cases_fma_expl_bcast[] = { 2, 5, 6, 9, 14, 32 };
static const int ur_cases_4fma[] = { 2, 4, 6, 12, 32 };
const int size_ur_cases_fma
= (jcp.ver == ver_avx512_core && jcp.expl_bcast) ?
sizeof(ur_cases_fma_expl_bcast) :
sizeof(ur_cases_fma_embd_bcast);
const int size_ur_cases_4fma = sizeof(ur_cases_4fma);
const int *ur_cases_fma = (jcp.ver == ver_avx512_core && jcp.expl_bcast) ?
ur_cases_fma_expl_bcast :
ur_cases_fma_embd_bcast;
const int *ur_cases = (jcp.ver == ver_4fma || jcp.ver == ver_4vnni)
? ur_cases_4fma : ur_cases_fma;
const int num_ur_cases = (jcp.ver == ver_4fma || jcp.ver == ver_4vnni ?
size_ur_cases_4fma :
size_ur_cases_fma)
/ sizeof(*ur_cases);
for (int ur_idx = num_ur_cases - 1; ur_idx > 0; ur_idx--) {
int label_idx = num_ur_cases - ur_idx - 1;
if (jcp.ur <= ur_cases[ur_idx]) {
cmp(reg_load_loop_work, simd_w * (label_idx + 1));
jle(load_loop_blk[label_idx], T_NEAR);
}
}
for (int ur_idx = 0; ur_idx < num_ur_cases; ur_idx++) {
if (jcp.ur <= ur_cases[ur_idx]) {
int label_idx = num_ur_cases - ur_idx - 1;
L(load_loop_blk[label_idx]);
{
if (label_idx == 0) {
cmp(reg_load_loop_work, 0);
je(load_loop_blk[num_ur_cases], T_NEAR);
}
load_loop_body(label_idx + 1);
if (label_idx - 1 > 0) {
cmp(reg_load_loop_work, 2 * label_idx * simd_w);
je(load_loop_blk[label_idx - 1], T_NEAR);
}
cmp(reg_load_loop_work, (label_idx + 1) * simd_w);
jge(load_loop_blk[label_idx]);
}
for (int idx = label_idx - 1; idx > 0; --idx) {
cmp(reg_load_loop_work, simd_w * (idx + 1));
je(load_loop_blk[idx], T_NEAR);
}
if (ur_idx < num_ur_cases - 2) {
cmp(reg_load_loop_work, simd_w);
jle(load_loop_blk[0], T_NEAR);
}
}
}
L(load_loop_blk[num_ur_cases]);
add(rsp, stack_space_needed);
postamble();
for (auto& inj : eltwise_injectors)
inj->prepare_table();
}
bool jit_avx512_common_1x1_conv_kernel::post_ops_ok(
jit_1x1_conv_conf_t &jcp, const primitive_attr_t &attr) {
const auto &p = attr.post_ops_;
auto all_post_ops_supported = [&]() {
bool ok = true;
for (int i = 0; i < p.len_; i++) {
ok = ok && utils::one_of(p.entry_[i].kind, primitive_kind::sum, primitive_kind::eltwise, primitive_kind::depthwise);
}
return ok;
};
auto contain = [&](mkldnn::impl::primitive_kind_t kind) { return p.find(kind) != -1; };
auto position = [&](mkldnn::impl::primitive_kind_t kind) { return p.find(kind); };
auto count = [&](mkldnn::impl::primitive_kind_t kind) { return p.count(kind); };
return all_post_ops_supported() &&
count(primitive_kind::sum) <= 1 &&
IMPLICATION(contain(primitive_kind::sum), position(primitive_kind::sum) == 0);
}
status_t jit_avx512_common_1x1_conv_kernel::init_conf(jit_1x1_conv_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &src_d,
const memory_desc_wrapper &weights_d, const memory_desc_wrapper &dst_d,
const primitive_attr_t &attr, int nthreads, bool reduce_src) {
if (!mayiuse(avx512_common)) return status::unimplemented;
const bool with_groups = weights_d.ndims() == src_d.ndims() + 1;
const int simd_w = cpu_isa_traits<avx512_common>::vlen / sizeof(float);
const int ndims = src_d.ndims();
jcp.prop_kind = cd.prop_kind;
jcp.ngroups = with_groups ? weights_d.dims()[0] : 1;
jcp.mb = src_d.dims()[0];
jcp.oc_without_padding = dst_d.dims()[1] / jcp.ngroups;
jcp.oc = dst_d.dims()[1] / jcp.ngroups;
jcp.ic = src_d.dims()[1] / jcp.ngroups;
bool ok_to_pad_channels = true
&& jcp.ngroups == 1
&& src_d.data_type() == data_type::f32;
if (ok_to_pad_channels) {
jcp.oc = rnd_up(jcp.oc, simd_w);
jcp.ic = rnd_up(jcp.ic, simd_w);
}
jcp.ih = (ndims == 3) ? 1 : src_d.dims()[2];
jcp.iw = src_d.dims()[ndims - 1];
jcp.oh = (ndims == 3) ? 1 : dst_d.dims()[2];
jcp.ow = dst_d.dims()[ndims - 1];
jcp.kh = (ndims == 3) ? 1 : weights_d.dims()[with_groups + 2];
jcp.kw = weights_d.dims()[with_groups + ndims - 1];
jcp.t_pad = (ndims == 3) ? 0 : cd.padding[0][0];
jcp.l_pad = cd.padding[0][ndims - 3];
jcp.stride_h = (ndims == 3) ? 1 : cd.strides[0];
jcp.stride_w = cd.strides[ndims - 3];
jcp.src_fmt = src_d.format();
jcp.with_bias = pick_by_prop_kind(jcp.prop_kind, cd.bias_desc.format,
memory_format::undef, cd.diff_bias_desc.format)
!= memory_format::undef;
jcp.os = jcp.oh * jcp.ow;
jcp.is = jcp.ih * jcp.iw;
jcp.tr_is = rnd_up(jcp.is, 4);
if (!post_ops_ok(jcp, attr))
return status::unimplemented;
const auto &p = attr.post_ops_;
jcp.with_sum = p.find(primitive_kind::sum) != -1;
const int eltwise_ind = p.find(primitive_kind::eltwise);
jcp.with_eltwise = eltwise_ind != -1;
if (jcp.with_eltwise) {
jcp.eltwise = p.entry_[eltwise_ind].eltwise;
if (dst_d.data_type() == data_type::s32) return status::unimplemented;
}
bool args_ok = true
&& jcp.ngroups == 1
&& everyone_is(pick(ndims - 3, nCw16c, nChw16c), src_d.format(),
dst_d.format())
&& one_of(cd.bias_desc.format, memory_format::undef, any, x);
if (!args_ok) return status::unimplemented;
args_ok = true
&& jcp.oc % simd_w == 0 && jcp.ic % simd_w == 0
&& jcp.t_pad == 0 && jcp.l_pad == 0
&& jcp.stride_w == 1 && jcp.stride_h == 1 // TODO: support some strides
&& jcp.kh == 1 && jcp.kw == 1;
if (!args_ok) return status::unimplemented;
jcp.ic_block = jcp.oc_block = simd_w;
jcp.transpose_src = false;
if (mayiuse(avx512_mic_4ops)
&& ((one_of(jcp.prop_kind, forward_training, forward_inference)
&& src_d.data_type() == data_type::s16
&& weights_d.data_type() == data_type::s16
&& dst_d.data_type() == data_type::s32)
|| (jcp.prop_kind == backward_data
&& src_d.data_type() == data_type::s32
&& weights_d.data_type() == data_type::s16
&& dst_d.data_type() == data_type::s16)))
{
const int is_bwd_d = jcp.prop_kind == backward_data;
memory_format_t weights_format = with_groups
? pick(2 * ndims - 6 + is_bwd_d, gOIw8i16o2i, gOIw8o16i2o,
gOIhw8i16o2i, gOIhw8o16i2o)
: pick(2 * ndims - 6 + is_bwd_d, OIw8i16o2i, OIw8o16i2o,
OIhw8i16o2i, OIhw8o16i2o);
if (weights_d.format() != weights_format)
return status::unimplemented;
jcp.ver = ver_4vnni;
jcp.fma_step = 4;
jcp.typesize_in = sizeof(prec_traits<data_type::s16>::type);
jcp.typesize_out = sizeof(prec_traits<data_type::s32>::type);
}
else if (everyone_is(data_type::f32, src_d.data_type(),
weights_d.data_type(), dst_d.data_type()))
{
const int is_bwd_d = jcp.prop_kind == backward_data;
memory_format_t weights_format = with_groups
? pick(2 * ndims - 6 + is_bwd_d, gOIw16i16o, gIOw16o16i,
gOIhw16i16o, gIOhw16o16i)
: pick(2 * ndims - 6 + is_bwd_d, OIw16i16o, IOw16o16i,
OIhw16i16o, IOhw16o16i);
if (weights_d.format() != weights_format)
return status::unimplemented;
if (jcp.prop_kind != backward_weights && mayiuse(avx512_mic_4ops) &&
((jcp.prop_kind == backward_data) ? jcp.oc_block : jcp.ic_block) % 4
== 0) {
jcp.ver = ver_4fma;
jcp.fma_step = 4;
} else if (jcp.prop_kind == backward_weights && mayiuse(avx512_mic_4ops)
&& !reduce_src
/* Heuristic condition for relation of src size to oc. Otherwise
the src transposition overhead exceed the benefit from 4fma
*/
&& ((jcp.is * jcp.ic) / jcp.oc <= 2048)
&& mkldnn_thr_syncable()
)
{
jcp.transpose_src = true;
jcp.ver = ver_4fma;
jcp.fma_step = 4;
} else {
jcp.ver = (mayiuse(avx512_core)) ? ver_avx512_core : ver_fma;
jcp.fma_step = 1;
}
jcp.typesize_in = sizeof(prec_traits<data_type::f32>::type);
jcp.typesize_out = sizeof(prec_traits<data_type::f32>::type);
} else {
return status::unimplemented;
}
/* once all the formats are set, check the padding consistency */
args_ok = true
&& jcp.ic <= src_d.blocking_desc().padding_dims[1]
&& jcp.oc <= dst_d.blocking_desc().padding_dims[1]
&& jcp.ic <= weights_d.blocking_desc().padding_dims[with_groups + 1]
&& jcp.oc <= weights_d.blocking_desc().padding_dims[with_groups + 0];
if (!args_ok) return status::unimplemented;
const int SMALL_SPATIAL = 10;
const int BIG_SPATIAL = 28;
const int BIG_REDUCE_DIM = 1024;
const int BIG_LOAD_DIM = 256;
int load_blocking{ 0 };
int load_blocking_max{ 0 };
int bcast_blocking{ 0 };
int bcast_blocking_max{ 0 };
int reduce_blocking{ 0 };
int reduce_blocking_max{ 0 };
jcp.load_grp_count = 1;
const int L1_capacity = get_cache_size(1, true) / sizeof(float);
const int L2_size = get_cache_size(2, true) / sizeof(float);
const int L2_capacity = (L2_size * 3) / 4;
if (one_of(jcp.prop_kind, forward_training, forward_inference,
backward_data)) {
if (one_of(jcp.prop_kind, forward_training, forward_inference)) {
jcp.reduce_dim = jcp.ic;
jcp.reduce_block = jcp.ic_block;
jcp.load_dim = jcp.oc;
jcp.load_block = jcp.oc_block;
jcp.bcast_dim = jcp.is;
} else {
jcp.reduce_dim = jcp.oc;
jcp.reduce_block = jcp.oc_block;
jcp.load_dim = jcp.ic;
jcp.load_block = jcp.ic_block;
jcp.bcast_dim = jcp.os;
}
jcp.reduce_loop_unroll = jcp.reduce_block;
jcp.reduce_loop_bcast_step
= jcp.reduce_loop_unroll * jcp.bcast_dim * jcp.typesize_in;
if (jcp.prop_kind == backward_data && jcp.ver == ver_4vnni) {
jcp.reduce_loop_load_step
= jcp.reduce_loop_unroll * jcp.ic * jcp.typesize_in;
jcp.load_loop_load_step
= jcp.oc_block * jcp.ic_block * jcp.typesize_in;
} else {
jcp.reduce_loop_load_step
= jcp.reduce_loop_unroll * jcp.load_block * jcp.typesize_in;
jcp.load_loop_load_step
= jcp.reduce_dim * jcp.load_block * jcp.typesize_in;
}
// adjusting registry blocking
int max_regs, min_regs, size_treshold, ur_step;
const int spatial
= (one_of(jcp.prop_kind, forward_training, forward_inference)) ?
jcp.oh :
jcp.ih;
if (jcp.ver == ver_avx512_core && (8 * jcp.mb) / nthreads >= 1) {
max_regs = 9;
min_regs = 6;
size_treshold = 14;
ur_step = 1;
jcp.expl_bcast = true;
if (jcp.load_dim > 128 && jcp.load_dim < BIG_LOAD_DIM
&& spatial > SMALL_SPATIAL && spatial < BIG_SPATIAL) {
max_regs = 6;
min_regs = 5;
}
} else {
bool is4ops = (jcp.ver == ver_4fma || jcp.ver == ver_4vnni);
max_regs = is4ops ? 28 : 30;
min_regs = 9;
size_treshold = is4ops ? 28 : 14;
ur_step = is4ops ? 4 : 1;
jcp.expl_bcast = false;
jcp.use_vmovntps = true;
}
jcp.ur = 1;
for (int ur_w = max_regs; ur_w >= min_regs; ur_w -= ur_step) {
if ((spatial >= size_treshold && spatial % ur_w == 0)
|| (spatial < size_treshold && jcp.os % ur_w == 0)) {
jcp.ur = ur_w;
break;
}
}
if (jcp.ur == 1) {
jcp.ur = nstl::min(max_regs, jcp.os);
int os_tail = jcp.os % max_regs;
for (int i = max_regs; i >= min_regs; i -= ur_step) {
int i_tail = jcp.os % i;
if (i_tail > os_tail || i_tail == 0) {
jcp.ur = i;
os_tail = i_tail;
if (i_tail == 0)
break;
}
}
}
jcp.reduce_loop_unroll = jcp.reduce_block;
jcp.reduce_loop_bcast_step
= jcp.reduce_loop_unroll * jcp.bcast_dim * jcp.typesize_in;
jcp.bcast_block = jcp.ur;
jcp.bcast_loop_output_step = jcp.ur * jcp.load_block * jcp.typesize_out;
jcp.bcast_loop_output_substep = -1; // unused
jcp.bcast_loop_bcast_step = jcp.ur * jcp.reduce_block * jcp.typesize_in;
jcp.bcast_loop_bcast_substep = -1; // unused
jcp.load_loop_iter_step = jcp.load_block;
if (jcp.prop_kind == backward_data)
jcp.loop_order = loop_lbr;
else
jcp.loop_order = reduce_src ? loop_blr : loop_lbr;
int nb_bcast = div_up(jcp.bcast_dim, jcp.bcast_block);
int nb_reduce = div_up(jcp.reduce_dim, jcp.reduce_block);
int nb_load = div_up(jcp.load_dim, jcp.load_block);
if (jcp.ver == ver_avx512_core && jcp.expl_bcast) {
if (jcp.load_dim <= BIG_LOAD_DIM && spatial > SMALL_SPATIAL
&& spatial < BIG_SPATIAL)
reduce_blocking = nstl::min(jcp.reduce_dim, 80);
else if (spatial > SMALL_SPATIAL)
reduce_blocking = nstl::min(jcp.reduce_dim, 512);
else
reduce_blocking = nstl::min(jcp.reduce_dim, 256);
if ((jcp.mb > 28 && spatial >= 28)
|| (jcp.mb > 112 && spatial >= 17))
jcp.use_vmovntps = true;
else
jcp.use_vmovntps = false;
} else {
reduce_blocking = nb_reduce;
if (spatial <= SMALL_SPATIAL && jcp.reduce_dim >= BIG_REDUCE_DIM)
reduce_blocking = 16;
else if (spatial > SMALL_SPATIAL
&& jcp.reduce_dim >= BIG_REDUCE_DIM)
reduce_blocking = 8;
reduce_blocking = best_divider(nb_reduce, 1, reduce_blocking, true);
reduce_blocking *= jcp.reduce_block;
}
// Check input data cache aliasing.
// For other ISA constants may be updated.
// 64 * 1024 is chosen due to 1MB L2 16-way cache.
// 7 is empirical value. It is about half of 16.
// So we leave about half of the set for other data - weights, dst
int way_size = (64 * 1024) / jcp.typesize_in;
int max_hits = 7;
if (jcp.bcast_dim * reduce_blocking > way_size * max_hits) {
int nrb = reduce_blocking / simd_w;
int sp = jcp.bcast_dim;
int wl = way_size / simd_w;
for (int start_off = 0; start_off < jcp.ur; start_off++) {
for (int off = start_off, hits = 0; off < sp * nrb; off += wl) {
if (off % sp >= jcp.ur || ++hits < max_hits)
continue;
int max_r_blocking = simd_w * nstl::max(1, (off + wl) / sp);
reduce_blocking
= nstl::min(reduce_blocking, max_r_blocking);
break;
}
}
}
if (reduce_blocking < jcp.reduce_dim) {
jcp.use_vmovntps = false;
if (jcp.prop_kind == backward_data)
jcp.loop_order = reduce_src ? loop_lbr : loop_rlb;
else
jcp.loop_order = reduce_src ? loop_rbl : loop_rlb;
}
load_blocking = jcp.load_dim;
int load_size = jcp.load_dim * jcp.reduce_dim;
int bcast_size = jcp.mb * jcp.ngroups * jcp.bcast_dim * jcp.reduce_dim;
if (jcp.ver == ver_avx512_core && nthreads <= 28 && jcp.mb < nthreads
&& nb_load * nb_bcast > nthreads) {
// Some heuristic here
float calc_koef = 0.01, best_cost = FLT_MAX;
int n_lgc = nthreads;
float ratio = (float)load_size / (float)bcast_size;
int best_lgc = ratio > 1 ? n_lgc : 1;
auto calc_job_cost = [&](int lb, int tg, float mem_k) {
int bb_size = jcp.mb * div_up(nb_bcast, tg);
float calc_size = (float)(bb_size * jcp.ur)
* (lb * jcp.load_block) * jcp.reduce_dim;
float mem_size = (float)(bb_size * jcp.ur + lb * jcp.load_block)
* jcp.reduce_dim;
return calc_koef * calc_size + mem_k * mem_size;
};
for (int lgc, ilgc = 0; ilgc < n_lgc; ilgc++) {
lgc = ratio > 1 ? n_lgc - ilgc : ilgc + 1;
int min_lb = nb_load / lgc;
int max_lb = div_up(nb_load, lgc);
int min_tg = nthreads / lgc;
int max_tg = div_up(nthreads, lgc);
// Some heuristic here
float mem_koef = (max_tg == 1) ? 1.f : 1.3f;
float job_cost = 0.;
if (nthreads % lgc < nb_load % lgc) {
job_cost = calc_job_cost(max_lb, min_tg, mem_koef);
} else {
auto job_cost1 = calc_job_cost(max_lb, max_tg, mem_koef);
auto job_cost2 = calc_job_cost(min_lb, min_tg, mem_koef);
job_cost = nstl::max(job_cost1, job_cost2);
}
if (job_cost < best_cost) {
best_lgc = lgc;
best_cost = job_cost;
}
}
jcp.load_grp_count = best_lgc;
load_blocking = div_up(nb_load, jcp.load_grp_count) * jcp.load_block;
} else {
jcp.load_grp_count = div_up(nthreads, jcp.mb * jcp.ngroups * nb_bcast);
jcp.load_grp_count = best_divider(
nthreads, jcp.load_grp_count, 2 * jcp.load_grp_count, false);
}
if (jcp.ver == ver_avx512_core && jcp.expl_bcast && jcp.bcast_dim <= 64
&& load_size >= L2_size) {
jcp.load_grp_count = nstl::max(jcp.load_grp_count, 4);
} else if (jcp.bcast_dim <= 49 && jcp.mb <= nthreads
&& jcp.load_dim > 512 && jcp.load_dim / jcp.reduce_dim >= 4) {
jcp.load_grp_count = nstl::max(jcp.load_grp_count, 2);
load_blocking = jcp.load_block;
}
if (jcp.ver == ver_4fma && jcp.bcast_dim * jcp.mb < jcp.load_dim
&& jcp.oh * jcp.ow > 64
&& IMPLICATION(reduce_src, jcp.load_dim < 1024)) {
/* Looking for best loading dimension blocking
* to get the best thread and data read/write efficiency
* by finding the optimal 'load_chunk' value
* Example:
* for 72 threads and convolution with mb=1, ih=iw=7, oc = 512
* the 'best' load_chunk value should be 1
* TODO: remove heuristic constants in above condition
* TODO: check this blocking for other ISA
*/
float best_eff = -1.f;
int best_lgc = 1;
for (int load_chunk = 1; load_chunk <= nb_load; load_chunk++) {
int lgc = div_up(nb_load, load_chunk);
if (lgc > nthreads)
continue;
int thr_per_grp = div_up(nthreads, lgc);
int bcast_per_thr = div_up(jcp.mb * nb_bcast, thr_per_grp)
* jcp.bcast_block;
int load_per_thr = load_chunk * simd_w;
float data_norm = (bcast_per_thr + load_per_thr) / 2.f;
float data_eff = (bcast_per_thr * load_per_thr)
/ (data_norm * data_norm);
float thr_eff_over_grp = (float)nstl::max(1, nthreads / lgc)
/ div_up(nthreads, lgc);
float thr_eff_in_grp = ((float)jcp.mb * nb_bcast)
/ rnd_up(jcp.mb * nb_bcast, thr_per_grp);
float thr_eff = thr_eff_over_grp * thr_eff_in_grp;
float load_eff = (float)nb_load / rnd_up(nb_load, lgc);
float overall_eff = data_eff + thr_eff + load_eff;
if (overall_eff > best_eff) {
best_eff = overall_eff;
best_lgc = lgc;
}
}
jcp.load_grp_count = best_lgc;
load_blocking
= div_up(nb_load, jcp.load_grp_count) * jcp.load_block;
}
bcast_blocking = div_up(jcp.mb * jcp.ngroups * nb_bcast,
div_up(nthreads, jcp.load_grp_count))
* jcp.bcast_block;
bcast_blocking = nstl::min(jcp.bcast_dim, bcast_blocking);
bcast_blocking = rnd_up(bcast_blocking, jcp.bcast_block);
int space_for_bcast
= (L2_capacity - /* kernel_size - */
2 * jcp.load_block * reduce_blocking
- jcp.ur * reduce_blocking - 3 * 1024);
if (jcp.reduce_dim * jcp.bcast_dim > L2_capacity)
space_for_bcast /= 2;
int bcast_in_cache
= nstl::max(jcp.bcast_block, space_for_bcast / reduce_blocking);
bcast_blocking = nstl::min(
bcast_blocking, rnd_dn(bcast_in_cache, jcp.bcast_block));
load_blocking_max = load_blocking;
bcast_blocking_max = bcast_blocking * 3 / 2;
reduce_blocking_max = reduce_blocking;
} else if (jcp.prop_kind == backward_weights) {
jcp.use_vmovntps = false;
if (jcp.is > SMALL_SPATIAL * SMALL_SPATIAL && jcp.ver == ver_4fma)
jcp.use_vmovntps = true;
if (jcp.transpose_src)
jcp.reduce_dim = jcp.tr_is;
else
jcp.reduce_dim = jcp.is;
if (jcp.ver == ver_4fma) {
// reduce_block should be divided by fma_step
jcp.reduce_block = best_divider(jcp.reduce_dim, 4, 16, true, 4);
} else {
jcp.reduce_block = best_divider(jcp.reduce_dim, 7, 16, true);
if (jcp.reduce_dim % jcp.reduce_block != 0)
jcp.reduce_block = best_divider(jcp.iw, 4, jcp.iw, false);
if (jcp.reduce_block > 256) {
jcp.reduce_block = 1;
}
}
jcp.load_dim = jcp.oc;
jcp.load_block = jcp.oc_block;
jcp.bcast_dim = jcp.ic;
jcp.bcast_block = jcp.ic_block;
if (jcp.ver == ver_avx512_core && jcp.reduce_block <= 19) {
// if reduce_block is big then generated JIT code may be big
// for small values of ur because reduce_loop_unroll = reduce_block
jcp.ur = jcp.bcast_block / 2;
jcp.expl_bcast = true;
} else {
jcp.ur = jcp.bcast_block;
jcp.expl_bcast = false;
}
jcp.reduce_loop_unroll = jcp.reduce_block;
jcp.reduce_loop_bcast_step
= jcp.reduce_loop_unroll * jcp.ic_block * jcp.typesize_in;
jcp.reduce_loop_load_step
= jcp.reduce_loop_unroll * jcp.oc_block * jcp.typesize_in;
jcp.bcast_loop_output_step =
jcp.oc_block * jcp.ic_block * jcp.typesize_out;
jcp.bcast_loop_output_substep =
jcp.oc_block * jcp.ur * jcp.typesize_out;
jcp.bcast_loop_bcast_step =
jcp.ic_block * jcp.reduce_dim * jcp.typesize_in;
jcp.bcast_loop_bcast_substep = jcp.ur * jcp.typesize_in;
jcp.load_loop_load_step = jcp.oc_block * jcp.os * jcp.typesize_in;
jcp.load_loop_iter_step = jcp.oc_block;
/* --- */
balance(jcp, nthreads);
load_blocking = div_up(jcp.load_dim, jcp.load_block);
load_blocking = best_divider(load_blocking, 16, load_blocking, false);
load_blocking *= jcp.load_block;
load_blocking_max = load_blocking;
assert(jcp.load_dim % load_blocking == 0);
int max_bcast_blocking = div_up(jcp.bcast_dim, jcp.bcast_block);
int min_bcast_blocking = 5;
bcast_blocking = div_up(jcp.bcast_dim, jcp.bcast_block);
bcast_blocking = best_divider(
bcast_blocking, min_bcast_blocking, max_bcast_blocking, false);
bcast_blocking *= jcp.bcast_block;
bcast_blocking_max = bcast_blocking;
assert(jcp.bcast_dim % bcast_blocking == 0);
// for reduction balance
if (jcp.ver == ver_avx512_core) {
int max_reduce_blocking
= nstl::min(L1_capacity / jcp.ur, jcp.reduce_dim);
int min_reduce_blocking = nstl::min(
L1_capacity / jcp.ur, nstl::max(jcp.iw, jcp.ih));
reduce_blocking = best_divider(jcp.reduce_dim, min_reduce_blocking,
max_reduce_blocking, true);
reduce_blocking
= nstl::max(rnd_dn(reduce_blocking, jcp.reduce_block),
jcp.reduce_block);
} else {
int max_reduce_blocking = L2_capacity
/ ((bcast_blocking + load_blocking) * jcp.reduce_block);
max_reduce_blocking = nstl::min(max_reduce_blocking,
(L1_capacity / (jcp.bcast_block)) / jcp.reduce_block);
int num_jobs = div_up(jcp.load_dim, load_blocking)
* div_up(jcp.bcast_dim, bcast_blocking);
int threads_per_job = nstl::max(1, nthreads / num_jobs);
reduce_blocking = div_up(jcp.mb * jcp.reduce_dim, jcp.reduce_block);
reduce_blocking = div_up(reduce_blocking, threads_per_job);
reduce_blocking = best_divider(reduce_blocking,
max_reduce_blocking - 2, max_reduce_blocking, true);
reduce_blocking *= jcp.reduce_block;
}
reduce_blocking_max = rnd_dn(reduce_blocking * 3 / 2, jcp.reduce_block);
} else
return status::unimplemented;
assert(load_blocking);
assert(load_blocking_max);
assert(bcast_blocking);
assert(bcast_blocking_max);
assert(reduce_blocking);
assert(reduce_blocking_max);
assert(load_blocking % jcp.load_block == 0);
assert(reduce_blocking % jcp.reduce_block == 0);
assert(load_blocking_max % jcp.load_block == 0);
assert(reduce_blocking_max % jcp.reduce_block == 0);
if (jcp.ver == ver_4fma || jcp.ver == ver_4vnni) {
if (jcp.ver == ver_4fma)
assert(jcp.reduce_loop_unroll % jcp.fma_step == 0);
if (jcp.ver == ver_4vnni)
assert(jcp.reduce_loop_unroll % (2 * jcp.fma_step) == 0);
assert(jcp.reduce_dim % jcp.reduce_loop_unroll == 0);
}
assert(jcp.bcast_block % jcp.ur == 0);
assert(jcp.reduce_dim % jcp.reduce_block == 0);
jcp.ur_tail = jcp.bcast_dim % jcp.ur;
jcp.nb_bcast_blocking = bcast_blocking / jcp.bcast_block;
jcp.nb_bcast_blocking_max = bcast_blocking_max / jcp.bcast_block;
jcp.nb_load_blocking = load_blocking / jcp.load_block;
jcp.nb_load_blocking_max = load_blocking_max / jcp.load_block;
jcp.nb_reduce_blocking = reduce_blocking / jcp.reduce_block;
jcp.nb_reduce_blocking_max = reduce_blocking_max / jcp.reduce_block;
jcp.nb_bcast = div_up(jcp.bcast_dim, jcp.bcast_block);
jcp.nb_load = div_up(jcp.load_dim, jcp.load_block);
jcp.nb_reduce = div_up(jcp.reduce_dim, jcp.reduce_block);
return status::success;
}
void jit_avx512_common_1x1_conv_kernel::init_scratchpad(
memory_tracking::registrar_t &scratchpad,
const jit_1x1_conv_conf_t &jcp) {
using namespace mkldnn::impl::memory_tracking::names;
if (jcp.prop_kind != backward_data && jcp.with_bias
&& jcp.oc != jcp.oc_without_padding)
scratchpad.book(key_conv_padded_bias, jcp.typesize_out * jcp.oc);
if (jcp.prop_kind == backward_weights) {
const size_t wei_size = (size_t)jcp.ngroups * jcp.oc * jcp.ic;
scratchpad.book(key_conv_wei_reduction,
jcp.typesize_out * wei_size * (jcp.nthr_mb - 1));
}
if (jcp.transpose_src) {
const size_t tr_src_size =
(size_t)jcp.nthr_mb * jcp.ngroups * jcp.ic * jcp.tr_is;
scratchpad.book(key_conv_tr_src, jcp.typesize_out * tr_src_size);
scratchpad.book(key_conv_tr_src_bctx,
sizeof(simple_barrier::ctx_t) * jcp.nthr);
}
}
void jit_avx512_common_1x1_conv_kernel::balance(jit_1x1_conv_conf_t &jcp,
int nthreads)
{
// initialize jcp reduction threading properties
jcp.nthr = jcp.nthr_mb = jcp.nthr_g = jcp.nthr_oc_b = jcp.nthr_ic_b = 1;
if (nthreads < jcp.ngroups) {
/* simplification... fortunately it doesn't hurt much */
return;
}
const int nb_bcast = div_up(jcp.bcast_dim, jcp.bcast_block);
const int nb_load = div_up(jcp.load_dim, jcp.load_block);
const int nb_reduce = div_up(jcp.reduce_dim, jcp.reduce_block);
jcp.nthr_g = jcp.ngroups;
const int nthr = nthreads / jcp.nthr_g;
auto calc_mem_cost = [=](int nthr_mb, int nthr_oc_b, int nthr_ic_b) {
/* calculate per thread memory cost (read/write). high level
* optimizer tries to minimize memory consumption. few notes: (n1)
* unclear why, but that essentially helps first convolution...
* (n2) assuming the reduction over minibatch is always there:
* - instead of 8 it should be 5 here (write ~= 2 read):
* kernel: temporal workspace 1 write
* reduction: 1 read from workspace and 1 write to the diff_wei
* - but experiments showed 8 works better than 5 or 6... */
int bcast_koeff = 1;
int load_koeff = 1;
int output_koeff = 12;
if (jcp.transpose_src) {
bcast_koeff = 5;
load_koeff = 1;
output_koeff = 8;
}
return 0
+ (size_t)bcast_koeff * div_up(jcp.mb * nb_reduce, nthr_mb)
* div_up(jcp.ngroups, jcp.nthr_g)
* div_up(nb_bcast, nthr_ic_b) * jcp.ic_block * jcp.reduce_block
/ jcp.stride_h / jcp.stride_w /* (n1) */
+ (size_t)load_koeff * div_up(jcp.mb * nb_reduce, nthr_mb)
* div_up(jcp.ngroups, jcp.nthr_g)
* div_up(nb_load, nthr_oc_b) * jcp.oc_block * jcp.reduce_block
+ (size_t)output_koeff /* (n2) */
* div_up(jcp.ngroups, jcp.nthr_g) * div_up(nb_load, nthr_oc_b)
* div_up(nb_bcast, nthr_ic_b) * jcp.ic_block
* jcp.oc_block;
};
int nthr_mb = 1, nthr_oc_b = 1, nthr_ic_b = 1;
auto best_mem_cost = calc_mem_cost(nthr_mb, nthr_oc_b, nthr_ic_b);
/* step 1: find the best thread distribution with lowest memory cost */
const int nthr_mb_max = nstl::min(nthr, jcp.mb * nb_reduce);
for (nthr_mb = 1; nthr_mb <= nthr_mb_max; ++nthr_mb) {
const int nthr_par = nthr / nthr_mb;
const int nthr_oc_b_max = nstl::min(nthr_par, nb_load);
for (nthr_oc_b = 1; nthr_oc_b <= nthr_oc_b_max; ++nthr_oc_b) {
nthr_ic_b = nstl::min(nthr_par / nthr_oc_b, nb_bcast);
auto mem_cost = calc_mem_cost(nthr_mb, nthr_oc_b, nthr_ic_b);
if (mem_cost <= best_mem_cost) {
best_mem_cost = mem_cost;
jcp.nthr_mb = nthr_mb;
jcp.nthr_oc_b = nthr_oc_b;
jcp.nthr_ic_b = nthr_ic_b;
}
}
if (!mkldnn_thr_syncable()) { assert(nthr_mb == 1); break; }
}
if (jcp.nthr_mb > nthreads / 2 && jcp.nthr_mb < nthreads)
jcp.nthr_mb = nstl::min(jcp.mb, nthreads);
jcp.nthr = jcp.nthr_mb * jcp.nthr_g * jcp.nthr_oc_b * jcp.nthr_ic_b;
assert(jcp.nthr <= nthreads);
}
}
}
}
|
// Copyright 2016, Tobias Hermann.
// https://github.com/Dobiasd/frugally-deep
// Distributed under the MIT License.
// (See accompanying LICENSE file or at
// https://opensource.org/licenses/MIT)
#pragma once
#include "fdeep/convolution.hpp"
#include "fdeep/filter.hpp"
#include "fdeep/shape2.hpp"
#include "fdeep/tensor_shape.hpp"
#include "fdeep/layers/layer.hpp"
#include <fplus/fplus.hpp>
#include <algorithm>
#include <cstddef>
#include <string>
#include <vector>
namespace fdeep { namespace internal
{
// Convolve depth slices separately.
class depthwise_conv_2d_layer : public layer
{
public:
explicit depthwise_conv_2d_layer(
const std::string& name, std::size_t input_depth,
const tensor_shape& filter_shape,
std::size_t k, const shape2& strides, padding p,
const shape2& dilation_rate,
const float_vec& depthwise_weights,
const float_vec& bias)
: layer(name),
filters_depthwise_(fplus::transform(generate_im2col_single_filter_matrix,
generate_filters(dilation_rate, filter_shape,
input_depth, depthwise_weights, bias))),
strides_(strides),
padding_(p)
{
assertion(filter_shape.volume() > 0, "filter must have volume");
assertion(strides.area() > 0, "invalid strides");
assertion(k == input_depth, "number of filters must match input depth");
assertion(filters_depthwise_.size() == input_depth,
"invalid number of filters");
}
protected:
tensors apply_impl(const tensors& inputs) const override
{
const auto& input = single_tensor_from_tensors(inputs);
const auto input_slices = tensor_to_depth_slices(input);
assertion(input_slices.size() == filters_depthwise_.size(),
"invalid input depth");
const auto convolve_slice =
[&](const tensor& slice, const convolution_filter_matrices& f) -> tensor
{
assertion(f.filter_shape_.depth_ == 1, "invalid filter depth");
const auto result = convolve(strides_, padding_, f, slice);
assertion(result.shape().depth_ == 1, "invalid conv output");
return result;
};
assertion(input_slices.size() == filters_depthwise_.size(),
"invalid depthwise filter count");
return {concatenate_tensors_depth(fplus::zip_with(
convolve_slice, input_slices, filters_depthwise_))};
}
std::vector<convolution_filter_matrices> filters_depthwise_;
shape2 strides_;
padding padding_;
};
} } // namespace fdeep, namespace internal
|
extern "C" {
#include "sai.h"
#include "saistatus.h"
}
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <map>
#include <memory>
#include <thread>
#include <chrono>
#include <getopt.h>
#include <unistd.h>
#include <sys/time.h>
#include "timestamp.h"
#include <sairedis.h>
#include <logger.h>
#include "orchdaemon.h"
#include "saihelper.h"
#include "notifications.h"
#include <signal.h>
#include "warm_restart.h"
using namespace std;
using namespace swss;
extern sai_switch_api_t *sai_switch_api;
extern sai_router_interface_api_t *sai_router_intfs_api;
#define UNREFERENCED_PARAMETER(P) (P)
/* Global variables */
sai_object_id_t gVirtualRouterId;
sai_object_id_t gUnderlayIfId;
sai_object_id_t gSwitchId = SAI_NULL_OBJECT_ID;
MacAddress gMacAddress;
#define DEFAULT_BATCH_SIZE 128
int gBatchSize = DEFAULT_BATCH_SIZE;
bool gSairedisRecord = true;
bool gSwssRecord = true;
bool gLogRotate = false;
ofstream gRecordOfs;
string gRecordFile;
void usage()
{
cout << "usage: orchagent [-h] [-r record_type] [-d record_location] [-b batch_size] [-m MAC]" << endl;
cout << " -h: display this message" << endl;
cout << " -r record_type: record orchagent logs with type (default 3)" << endl;
cout << " 0: do not record logs" << endl;
cout << " 1: record SAI call sequence as sairedis.rec" << endl;
cout << " 2: record SwSS task sequence as swss.rec" << endl;
cout << " 3: enable both above two records" << endl;
cout << " -d record_location: set record logs folder location (default .)" << endl;
cout << " -b batch_size: set consumer table pop operation batch size (default 128)" << endl;
cout << " -m MAC: set switch MAC address" << endl;
}
void sighup_handler(int signo)
{
/*
* Don't do any logging since they are using mutexes.
*/
gLogRotate = true;
sai_attribute_t attr;
attr.id = SAI_REDIS_SWITCH_ATTR_PERFORM_LOG_ROTATE;
attr.value.booldata = true;
if (sai_switch_api != NULL)
{
sai_switch_api->set_switch_attribute(gSwitchId, &attr);
}
}
void syncd_apply_view()
{
SWSS_LOG_NOTICE("Notify syncd APPLY_VIEW");
sai_status_t status;
sai_attribute_t attr;
attr.id = SAI_REDIS_SWITCH_ATTR_NOTIFY_SYNCD;
attr.value.s32 = SAI_REDIS_NOTIFY_SYNCD_APPLY_VIEW;
status = sai_switch_api->set_switch_attribute(gSwitchId, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to notify syncd APPLY_VIEW %d", status);
exit(EXIT_FAILURE);
}
}
int main(int argc, char **argv)
{
swss::Logger::linkToDbNative("orchagent");
SWSS_LOG_ENTER();
WarmStart::initialize("orchagent", "swss");
WarmStart::checkWarmStart("orchagent", "swss");
if (signal(SIGHUP, sighup_handler) == SIG_ERR)
{
SWSS_LOG_ERROR("failed to setup SIGHUP action");
exit(1);
}
int opt;
sai_status_t status;
string record_location = ".";
while ((opt = getopt(argc, argv, "b:m:r:d:h")) != -1)
{
switch (opt)
{
case 'b':
gBatchSize = atoi(optarg);
break;
case 'm':
gMacAddress = MacAddress(optarg);
break;
case 'r':
if (!strcmp(optarg, "0"))
{
gSairedisRecord = false;
gSwssRecord = false;
}
else if (!strcmp(optarg, "1"))
{
gSwssRecord = false;
}
else if (!strcmp(optarg, "2"))
{
gSairedisRecord = false;
}
else if (!strcmp(optarg, "3"))
{
continue; /* default behavior */
}
else
{
usage();
exit(EXIT_FAILURE);
}
break;
case 'd':
record_location = optarg;
if (access(record_location.c_str(), W_OK))
{
SWSS_LOG_ERROR("Failed to access writable directory %s", record_location.c_str());
exit(EXIT_FAILURE);
}
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default: /* '?' */
exit(EXIT_FAILURE);
}
}
SWSS_LOG_NOTICE("--- Starting Orchestration Agent ---");
initSaiApi();
initSaiRedis(record_location);
sai_attribute_t attr;
vector<sai_attribute_t> attrs;
attr.id = SAI_SWITCH_ATTR_INIT_SWITCH;
attr.value.booldata = true;
attrs.push_back(attr);
attr.id = SAI_SWITCH_ATTR_FDB_EVENT_NOTIFY;
attr.value.ptr = (void *)on_fdb_event;
attrs.push_back(attr);
/* Disable/enable SwSS recording */
if (gSwssRecord)
{
gRecordFile = record_location + "/" + "swss.rec";
gRecordOfs.open(gRecordFile, std::ofstream::out | std::ofstream::app);
if (!gRecordOfs.is_open())
{
SWSS_LOG_ERROR("Failed to open SwSS recording file %s", gRecordFile.c_str());
exit(EXIT_FAILURE);
}
gRecordOfs << getTimestamp() << "|recording started" << endl;
}
attr.id = SAI_SWITCH_ATTR_PORT_STATE_CHANGE_NOTIFY;
attr.value.ptr = (void *)on_port_state_change;
attrs.push_back(attr);
attr.id = SAI_SWITCH_ATTR_SHUTDOWN_REQUEST_NOTIFY;
attr.value.ptr = (void *)on_switch_shutdown_request;
attrs.push_back(attr);
if (gMacAddress)
{
attr.id = SAI_SWITCH_ATTR_SRC_MAC_ADDRESS;
memcpy(attr.value.mac, gMacAddress.getMac(), 6);
attrs.push_back(attr);
}
status = sai_switch_api->create_switch(&gSwitchId, (uint32_t)attrs.size(), attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to create a switch, rv:%d", status);
exit(EXIT_FAILURE);
}
SWSS_LOG_NOTICE("Create a switch");
/* Get switch source MAC address if not provided */
if (!gMacAddress)
{
attr.id = SAI_SWITCH_ATTR_SRC_MAC_ADDRESS;
status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get MAC address from switch, rv:%d", status);
exit(EXIT_FAILURE);
}
else
{
gMacAddress = attr.value.mac;
}
}
/* Get the default virtual router ID */
attr.id = SAI_SWITCH_ATTR_DEFAULT_VIRTUAL_ROUTER_ID;
status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Fail to get switch virtual router ID %d", status);
exit(EXIT_FAILURE);
}
gVirtualRouterId = attr.value.oid;
SWSS_LOG_NOTICE("Get switch virtual router ID %lx", gVirtualRouterId);
/* Create a loopback underlay router interface */
vector<sai_attribute_t> underlay_intf_attrs;
sai_attribute_t underlay_intf_attr;
underlay_intf_attr.id = SAI_ROUTER_INTERFACE_ATTR_VIRTUAL_ROUTER_ID;
underlay_intf_attr.value.oid = gVirtualRouterId;
underlay_intf_attrs.push_back(underlay_intf_attr);
underlay_intf_attr.id = SAI_ROUTER_INTERFACE_ATTR_TYPE;
underlay_intf_attr.value.s32 = SAI_ROUTER_INTERFACE_TYPE_LOOPBACK;
underlay_intf_attrs.push_back(underlay_intf_attr);
status = sai_router_intfs_api->create_router_interface(&gUnderlayIfId, gSwitchId, (uint32_t)underlay_intf_attrs.size(), underlay_intf_attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to create underlay router interface %d", status);
exit(EXIT_FAILURE);
}
SWSS_LOG_NOTICE("Created underlay router interface ID %lx", gUnderlayIfId);
/* Initialize orchestration components */
DBConnector appl_db(APPL_DB, DBConnector::DEFAULT_UNIXSOCKET, 0);
DBConnector config_db(CONFIG_DB, DBConnector::DEFAULT_UNIXSOCKET, 0);
DBConnector state_db(STATE_DB, DBConnector::DEFAULT_UNIXSOCKET, 0);
auto orchDaemon = make_shared<OrchDaemon>(&appl_db, &config_db, &state_db);
try
{
if (!orchDaemon->init())
{
SWSS_LOG_ERROR("Failed to initialize orchstration daemon");
exit(EXIT_FAILURE);
}
/*
* In syncd view comparison solution, apply view has been sent
* immediately after restore is done
*/
if (!WarmStart::isWarmStart())
{
syncd_apply_view();
}
orchDaemon->start();
}
catch (char const *e)
{
SWSS_LOG_ERROR("Exception: %s", e);
}
catch (exception& e)
{
SWSS_LOG_ERROR("Failed due to exception: %s", e.what());
}
return 0;
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, PickNik LLC
* 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 PickNik LLC 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: Dave Coleman
Desc: Demonstrate how to use the imarker simple interface
*/
#ifndef RVIZ_VISUAL_TOOLS_IMARKER_SIMPLE_DEMO_H
#define RVIZ_VISUAL_TOOLS_IMARKER_SIMPLE_DEMO_H
// ROS
#include <ros/ros.h>
#include <rviz_visual_tools/rviz_visual_tools.h>
#include <rviz_visual_tools/imarker_simple.h>
namespace rviz_visual_tools
{
class IMarkerSimpleDemo
{
public:
/** \brief Constructor */
IMarkerSimpleDemo() : nh_("~")
{
visual_tools_.reset(new rviz_visual_tools::RvizVisualTools("world", "/rviz_visual_tools"));
visual_tools_->loadMarkerPub();
// Create a random initial pose
geometry_msgs::Pose init_pose;
visual_tools_->generateRandomPose(init_pose);
// Create a 6DOF interactive marker
static const double SCALE = 0.2;
imarker_simple_.reset(new rviz_visual_tools::IMarkerSimple("imarker", SCALE, init_pose));
// Add callback to this class
imarker_simple_->setIMarkerCallback(std::bind(&IMarkerSimpleDemo::processIMarkerPose, this, std::placeholders::_1));
ROS_INFO_STREAM_NAMED(name_, "IMarkerSimpleDemo Ready.");
}
void processIMarkerPose(const visualization_msgs::InteractiveMarkerFeedbackConstPtr& feedback)
{
// Show some spheres for fun
visual_tools_->publishSphere(feedback->pose, visual_tools_->getRandColor());
visual_tools_->trigger();
}
private:
// --------------------------------------------------------
// The short name of this class
std::string name_ = "imarker_simple_demo";
// A shared node handle
ros::NodeHandle nh_;
rviz_visual_tools::RvizVisualToolsPtr visual_tools_;
rviz_visual_tools::IMarkerSimplePtr imarker_simple_;
}; // end class
// Create std pointers for this class
typedef std::shared_ptr<IMarkerSimpleDemo> IMarkerSimpleDemoPtr;
typedef std::shared_ptr<const IMarkerSimpleDemo> IMarkerSimpleDemoConstPtr;
} // namespace rviz_visual_tools
#endif // RVIZ_VISUAL_TOOLS_IMARKER_SIMPLE_DEMO_H
int main(int argc, char** argv)
{
// Initialize ROS
ros::init(argc, argv, "imarker_simple_demo");
ROS_INFO_STREAM_NAMED("main", "Starting IMarkerSimpleDemo...");
// Seed random number generator
// srand (time(NULL));
// Allow the action server to recieve and send ros messages
ros::AsyncSpinner spinner(2);
spinner.start();
// Initialize main class
rviz_visual_tools::IMarkerSimpleDemo server;
ros::waitForShutdown();
// Shutdown
ROS_INFO_STREAM_NAMED("main", "Shutting down.");
ros::shutdown();
return 0;
}
|
/*******************************************************************************
* Copyright 2019-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef CPU_X64_JIT_UNI_BINARY_HPP
#define CPU_X64_JIT_UNI_BINARY_HPP
#include "common/primitive.hpp"
#include "cpu/cpu_eltwise_pd.hpp"
#include "cpu/x64/jit_uni_binary_kernel.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
namespace x64 {
struct binary_kernel_t;
using op_t = binary_op_t;
using bcast_t = binary_bcast_t;
struct jit_uni_binary_t : public primitive_t {
struct pd_t : public cpu_binary_pd_t {
using cpu_binary_pd_t::cpu_binary_pd_t;
DECLARE_COMMON_PD_T("jit:uni", jit_uni_binary_t);
status_t init(engine_t *engine);
jit_binary_conf_t get_conf() const { return conf_; };
private:
op_t get_op_type(const memory_desc_wrapper &src0_d);
bool is_only_dim0_bcasted(const dims_t &bcast_dims, const int ndims);
bcast_t get_bcast_type(
const memory_desc_wrapper &src1_d, const dims_t &bcast_dims);
// alg_preserves_zero returns true if operation preserves zero in case
// of both inputs contain zero.
bool alg_preserves_zero() const;
bool check_scales_mask() const;
bool is_bcast_pattern(const dims_t &bcast_dims, const dim_t ndims,
const dim_t N_bcast, const dim_t C_bcast,
const dim_t W_bcast) const;
bool is_bcast_pattern(const dims_t &bcast_dims, const dim_t N_bcast,
const dim_t C_bcast) const;
bool is_bcast_allowed(const int ndims) const;
bool is_format_non_blocked(const memory_desc_wrapper &mdw) const;
bool is_different_layouts_allowed(const memory_desc_wrapper &src0_d,
const memory_desc_wrapper &src1_d) const;
bool is_applicable();
jit_binary_conf_t conf_;
};
jit_uni_binary_t(const pd_t *apd);
~jit_uni_binary_t() = default;
status_t init(engine_t *engine) override;
using data_t = int8_t;
void execute_no_bcast_strategy(const data_t *src0, const data_t *src1,
data_t *dst, const float *scale0, const float *scale1,
const std::vector<const void *> &post_ops_binary_rhs_arg_vec,
const bcast_t bcast_type) const;
void execute_bcast_per_batch_strategy(const data_t *src0,
const data_t *src1, data_t *dst, const float *scale0,
const float *scale1,
const std::vector<const void *> &post_ops_binary_rhs_arg_vec) const;
void execute_bcast_per_c_strategy(const data_t *src0, const data_t *src1,
data_t *dst, const float *scale0, const float *scale1,
const std::vector<const void *> &post_ops_binary_rhs_arg_vec,
const op_t op_type, const bcast_t bcast_type,
const bool blocked_oc_tail) const;
void execute_bcast_per_w_strategy(const data_t *src0, const data_t *src1,
data_t *dst, const float *scale0, const float *scale1,
const std::vector<const void *> &post_ops_binary_rhs_arg_vec,
const op_t op_type, const bool blocked_oc_tail) const;
status_t execute(const exec_ctx_t &ctx) const override;
private:
const pd_t *pd() const { return (const pd_t *)primitive_t::pd().get(); }
static bool post_ops_ok(const primitive_attr_t *attr,
const memory_desc_wrapper &src0_d, const memory_desc_wrapper &dst_d,
const bool is_src1_different_layouts);
std::unique_ptr<binary_kernel_t> kernel_;
// used only in bcast_c_blocked strategy if tail exists
std::unique_ptr<binary_kernel_t> kernel_tail_;
};
} // namespace x64
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
// vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// bthread - A M:N threading library to make applications more concurrent.
// Date: Tue Jul 22 17:30:12 CST 2014
#include "butil/atomicops.h" // butil::atomic
#include "butil/scoped_lock.h" // BAIDU_SCOPED_LOCK
#include "butil/macros.h"
#include "butil/containers/linked_list.h" // LinkNode
#ifdef SHOW_BTHREAD_BUTEX_WAITER_COUNT_IN_VARS
#include "butil/memory/singleton_on_pthread_once.h"
#endif
#include "butil/logging.h"
#include "butil/object_pool.h"
#include "bthread/errno.h" // EWOULDBLOCK
#include "bthread/sys_futex.h" // futex_*
#include "bthread/processor.h" // cpu_relax
#include "bthread/task_control.h" // TaskControl
#include "bthread/task_group.h" // TaskGroup
#include "bthread/timer_thread.h"
#include "bthread/butex.h"
#include "bthread/mutex.h"
// This file implements butex.h
// Provides futex-like semantics which is sequenced wait and wake operations
// and guaranteed visibilities.
//
// If wait is sequenced before wake:
// [thread1] [thread2]
// wait() value = new_value
// wake()
// wait() sees unmatched value(fail to wait), or wake() sees the waiter.
//
// If wait is sequenced after wake:
// [thread1] [thread2]
// value = new_value
// wake()
// wait()
// wake() must provide some sort of memory fence to prevent assignment
// of value to be reordered after it. Thus the value is visible to wait()
// as well.
namespace bthread {
#ifdef SHOW_BTHREAD_BUTEX_WAITER_COUNT_IN_VARS
struct ButexWaiterCount : public bvar::Adder<int64_t> {
ButexWaiterCount() : bvar::Adder<int64_t>("bthread_butex_waiter_count") {}
};
inline bvar::Adder<int64_t>& butex_waiter_count() {
return *butil::get_leaky_singleton<ButexWaiterCount>();
}
#endif
// If a thread would suspend for less than so many microseconds, return
// ETIMEDOUT directly.
// Use 1: sleeping for less than 2 microsecond is inefficient and useless.
static const int64_t MIN_SLEEP_US = 2;
enum WaiterState {
WAITER_STATE_NONE,
WAITER_STATE_READY,
WAITER_STATE_TIMEDOUT,
WAITER_STATE_UNMATCHEDVALUE,
WAITER_STATE_INTERRUPTED,
};
struct Butex;
struct ButexWaiter : public butil::LinkNode<ButexWaiter> {
// tids of pthreads are 0
bthread_t tid;
// Erasing node from middle of LinkedList is thread-unsafe, we need
// to hold its container's lock.
butil::atomic<Butex*> container;
};
// non_pthread_task allocates this structure on stack and queue it in
// Butex::waiters.
struct ButexBthreadWaiter : public ButexWaiter {
TaskMeta* task_meta; // 待wait的tm
TimerThread::TaskId sleep_id; // 如果需要sleep,加入到timer_thread后得到的sleep_id
WaiterState waiter_state;
int expected_value; // butex_wait的期望值
Butex* initial_butex; // 真正被wait和wake的butex,被多个ButexBthreadWaiter共享
TaskControl* control; // tg, 全局唯一
};
// pthread_task or main_task allocates this structure on stack and queue it
// in Butex::waiters.
struct ButexPthreadWaiter : public ButexWaiter {
butil::atomic<int> sig;
};
typedef butil::LinkedList<ButexWaiter> ButexWaiterList;
enum ButexPthreadSignal { PTHREAD_NOT_SIGNALLED, PTHREAD_SIGNALLED };
struct BAIDU_CACHELINE_ALIGNMENT Butex { // TODO(xcy)
Butex() {}
~Butex() {}
butil::atomic<int> value; // butex_wait时用到的expected_value
ButexWaiterList waiters; // 链表,记录在该butex上挂起的bthread/pthread
internal::FastPthreadMutex waiter_lock; // 锁, butex_wait后需要把bthread挂到waiters上。
// wait过程:加锁 -> 判断value -> 挂起到 waiters -> 解锁。 没有锁的话,判断value完了以后,可能就有其他地方调用了butex_wake,导致wake信号丢失
// 也就是value判断和挂起waiters需要在同一个临界区,也就是waiter_lock
};
BAIDU_CASSERT(offsetof(Butex, value) == 0, offsetof_value_must_0);
BAIDU_CASSERT(sizeof(Butex) == BAIDU_CACHELINE_SIZE, butex_fits_in_one_cacheline);
static void wakeup_pthread(ButexPthreadWaiter* pw) {
// release fence makes wait_pthread see changes before wakeup.
pw->sig.store(PTHREAD_SIGNALLED, butil::memory_order_release);
// At this point, wait_pthread() possibly has woken up and destroyed `pw'.
// In which case, futex_wake_private() should return EFAULT.
// If crash happens in future, `pw' can be made TLS and never destroyed
// to solve the issue.
futex_wake_private(&pw->sig, 1);
}
bool erase_from_butex(ButexWaiter*, bool, WaiterState);
int wait_pthread(ButexPthreadWaiter& pw, timespec* ptimeout) {
while (true) {
const int rc = futex_wait_private(&pw.sig, PTHREAD_NOT_SIGNALLED, ptimeout);
if (PTHREAD_NOT_SIGNALLED != pw.sig.load(butil::memory_order_acquire)) {
// If `sig' is changed, wakeup_pthread() must be called and `pw'
// is already removed from the butex.
// Acquire fence makes this thread sees changes before wakeup.
return rc;
}
if (rc != 0 && errno == ETIMEDOUT) {
// Note that we don't handle the EINTR from futex_wait here since
// pthreads waiting on a butex should behave similarly as bthreads
// which are not able to be woken-up by signals.
// EINTR on butex is only producible by TaskGroup::interrupt().
// `pw' is still in the queue, remove it.
if (!erase_from_butex(&pw, false, WAITER_STATE_TIMEDOUT)) {
// Another thread is erasing `pw' as well, wait for the signal.
// Acquire fence makes this thread sees changes before wakeup.
if (pw.sig.load(butil::memory_order_acquire) == PTHREAD_NOT_SIGNALLED) {
ptimeout = NULL; // already timedout, ptimeout is expired.
continue;
}
}
return rc;
}
}
}
extern BAIDU_THREAD_LOCAL TaskGroup* tls_task_group;
// Returns 0 when no need to unschedule or successfully unscheduled,
// -1 otherwise.
inline int unsleep_if_necessary(ButexBthreadWaiter* w,
TimerThread* timer_thread) {
if (!w->sleep_id) {
return 0; // 不需要unschedule
}
if (timer_thread->unschedule(w->sleep_id) > 0) {
// the callback is running.
return -1; // unschedule失败
}
w->sleep_id = 0;
return 0; // unschedule成功
}
// TODO(xcy)
// Use ObjectPool(which never frees memory) to solve the race between
// butex_wake() and butex_destroy(). The race is as follows:
//
// class Event {
// public:
// void wait() {
// _mutex.lock();
// if (!_done) {
// _cond.wait(&_mutex);
// }
// _mutex.unlock();
// }
// void signal() {
// _mutex.lock();
// if (!_done) {
// _done = true;
// _cond.signal();
// }
// _mutex.unlock(); /*1*/
// }
// private:
// bool _done = false;
// Mutex _mutex;
// Condition _cond;
// };
//
// [Thread1] [Thread2]
// foo() {
// Event event;
// pass_to_thread2(&event); ---> event.signal();
// event.wait();
// } <-- event destroyed
//
// Summary: Thread1 passes a stateful condition to Thread2 and waits until
// the condition being signalled, which basically means the associated
// job is done and Thread1 can release related resources including the mutex
// and condition. The scenario is fine and the code is correct.
// The race needs a closer look. The unlock at /*1*/ may have different
// implementations, but in which the last step is probably an atomic store
// and butex_wake(), like this:
//
// locked->store(0);
// butex_wake(locked);
//
// The `locked' represents the locking status of the mutex. The issue is that
// just after the store(), the mutex is already unlocked and the code in
// Event.wait() may successfully grab the lock and go through everything
// left and leave foo() function, destroying the mutex and butex, making
// the butex_wake(locked) crash.
// To solve this issue, one method is to add reference before store and
// release the reference after butex_wake. However reference countings need
// to be added in nearly every user scenario of butex_wake(), which is very
// error-prone. Another method is never freeing butex, with the side effect
// that butex_wake() may wake up an unrelated butex(the one reuses the memory)
// and cause spurious wakeups. According to our observations, the race is
// infrequent, even rare. The extra spurious wakeups should be acceptable.
void* butex_create() {
Butex* b = butil::get_object<Butex>();
if (b) {
return &b->value; // 对使用者只需要知道value就够了,bthread根据value的地址通过container_of这个宏来重新获取Butex
}
return NULL;
}
void butex_destroy(void* butex) {
if (!butex) {
return;
}
Butex* b = static_cast<Butex*>(
container_of(static_cast<butil::atomic<int>*>(butex), Butex, value));
butil::return_object(b);
}
inline TaskGroup* get_task_group(TaskControl* c) {
TaskGroup* g = tls_task_group;
return g ? g : c->choose_one_group(); // 如果当前线程没有tg就从tc中选一个
}
int butex_wake(void* arg) { // wake一个任务,注意只有"一个"
Butex* b = container_of(static_cast<butil::atomic<int>*>(arg), Butex, value); // 通过value在Butex结构中的偏移量计算出Butex的其实地址
ButexWaiter* front = NULL;
{
BAIDU_SCOPED_LOCK(b->waiter_lock);
if (b->waiters.empty()) { // waiter list上没有任何需要wake的,直接返回
return 0;
}
front = b->waiters.head()->value(); // 取出waiter list的head,下面wake这个front
front->RemoveFromList(); // 将front从waiter_list中移除
front->container.store(NULL, butil::memory_order_relaxed); // 将butex设置为NULL
}
if (front->tid == 0) { // 这是一个运行在pthread上的任务
wakeup_pthread(static_cast<ButexPthreadWaiter*>(front)); // 通过futex_wake唤醒一个任务
return 1;
}
ButexBthreadWaiter* bbw = static_cast<ButexBthreadWaiter*>(front);
unsleep_if_necessary(bbw, get_global_timer_thread()); // 把tm从timer_thread中拿出来
TaskGroup* g = tls_task_group;
if (g) { // 如果当前线程是tg,那就『立刻』在这个线程执行
TaskGroup::exchange(&g, bbw->tid);
} else { // 如果当前线程不是tg,那就从tc中选一个来『准备』执行tm。 上面是立刻开始,这里是准备开始
bbw->control->choose_one_group()->ready_to_run_remote(bbw->tid);
}
return 1;
}
int butex_wake_all(void* arg) {
Butex* b = container_of(static_cast<butil::atomic<int>*>(arg), Butex, value);
ButexWaiterList bthread_waiters;
ButexWaiterList pthread_waiters;
{
BAIDU_SCOPED_LOCK(b->waiter_lock);
while (!b->waiters.empty()) {
ButexWaiter* bw = b->waiters.head()->value();
bw->RemoveFromList();
bw->container.store(NULL, butil::memory_order_relaxed);
if (bw->tid) {
bthread_waiters.Append(bw);
} else {
pthread_waiters.Append(bw);
}
}
}
int nwakeup = 0;
while (!pthread_waiters.empty()) {
ButexPthreadWaiter* bw = static_cast<ButexPthreadWaiter*>(
pthread_waiters.head()->value());
bw->RemoveFromList();
wakeup_pthread(bw);
++nwakeup;
}
if (bthread_waiters.empty()) {
return nwakeup;
}
// We will exchange with first waiter in the end.
// 在将除了这个next任务之外的其他任务ready_to_run_general之后,如果 g == tls_task_group
// 那就直接在这个tg上执行next,也就是下面的 TaskGroup::exchange(&g, next->tid)
ButexBthreadWaiter* next = static_cast<ButexBthreadWaiter*>(
bthread_waiters.head()->value());
next->RemoveFromList();
unsleep_if_necessary(next, get_global_timer_thread());
++nwakeup;
TaskGroup* g = get_task_group(next->control);
const int saved_nwakeup = nwakeup;
while (!bthread_waiters.empty()) {
// pop reversely
ButexBthreadWaiter* w = static_cast<ButexBthreadWaiter*>(
bthread_waiters.tail()->value());
w->RemoveFromList();
unsleep_if_necessary(w, get_global_timer_thread());
g->ready_to_run_general(w->tid, true);
++nwakeup;
}
if (saved_nwakeup != nwakeup) { // 除了next之外还有其他的任务被wakeup
g->flush_nosignal_tasks_general(); // 上面ready_to_run_general把任务又重新放到了tg的队列中,如果这句话不执行的话,任务需要在队列里面排队,这里flush一下是为了让其他tg来偷任务(比如可能有些tg正在休眠)
}
if (g == tls_task_group) {
TaskGroup::exchange(&g, next->tid);
} else {
g->ready_to_run_remote(next->tid);
}
return nwakeup;
}
int butex_wake_except(void* arg, bthread_t excluded_bthread) {
Butex* b = container_of(static_cast<butil::atomic<int>*>(arg), Butex, value);
ButexWaiterList bthread_waiters;
ButexWaiterList pthread_waiters;
{
ButexWaiter* excluded_waiter = NULL;
BAIDU_SCOPED_LOCK(b->waiter_lock);
while (!b->waiters.empty()) {
ButexWaiter* bw = b->waiters.head()->value();
bw->RemoveFromList();
if (bw->tid) {
if (bw->tid != excluded_bthread) {
bthread_waiters.Append(bw);
bw->container.store(NULL, butil::memory_order_relaxed);
} else {
excluded_waiter = bw;
}
} else {
bw->container.store(NULL, butil::memory_order_relaxed);
pthread_waiters.Append(bw);
}
}
if (excluded_waiter) {
b->waiters.Append(excluded_waiter); // 重新放到waiter list
}
}
int nwakeup = 0;
while (!pthread_waiters.empty()) {
ButexPthreadWaiter* bw = static_cast<ButexPthreadWaiter*>(
pthread_waiters.head()->value());
bw->RemoveFromList();
wakeup_pthread(bw);
++nwakeup;
}
if (bthread_waiters.empty()) {
return nwakeup;
}
ButexBthreadWaiter* front = static_cast<ButexBthreadWaiter*>(
bthread_waiters.head()->value());
// 下面的实现和butex_wakeup_all不一样,具体原因我也不知道
TaskGroup* g = get_task_group(front->control);
const int saved_nwakeup = nwakeup;
do {
// pop reversely
ButexBthreadWaiter* w = static_cast<ButexBthreadWaiter*>(
bthread_waiters.tail()->value());
w->RemoveFromList();
unsleep_if_necessary(w, get_global_timer_thread());
g->ready_to_run_general(w->tid, true);
++nwakeup;
} while (!bthread_waiters.empty());
if (saved_nwakeup != nwakeup) {
g->flush_nosignal_tasks_general();
}
return nwakeup;
}
// wake_up arg所在的list中的第一个任务,并将剩下的任务append到arg2所在的waiter list中
int butex_requeue(void* arg, void* arg2) {
Butex* b = container_of(static_cast<butil::atomic<int>*>(arg), Butex, value);
Butex* m = container_of(static_cast<butil::atomic<int>*>(arg2), Butex, value);
ButexWaiter* front = NULL;
{
std::unique_lock<internal::FastPthreadMutex> lck1(b->waiter_lock, std::defer_lock);
std::unique_lock<internal::FastPthreadMutex> lck2(m->waiter_lock, std::defer_lock);
butil::double_lock(lck1, lck2);
if (b->waiters.empty()) {
return 0;
}
front = b->waiters.head()->value();
front->RemoveFromList();
front->container.store(NULL, butil::memory_order_relaxed);
while (!b->waiters.empty()) {
ButexWaiter* bw = b->waiters.head()->value();
bw->RemoveFromList();
m->waiters.Append(bw);
bw->container.store(m, butil::memory_order_relaxed);
}
}
if (front->tid == 0) { // which is a pthread
wakeup_pthread(static_cast<ButexPthreadWaiter*>(front));
return 1;
}
ButexBthreadWaiter* bbw = static_cast<ButexBthreadWaiter*>(front);
unsleep_if_necessary(bbw, get_global_timer_thread());
TaskGroup* g = tls_task_group;
if (g) {
TaskGroup::exchange(&g, front->tid);
} else {
bbw->control->choose_one_group()->ready_to_run_remote(front->tid);
}
return 1;
}
// Callable from multiple threads, at most one thread may wake up the waiter.
static void erase_from_butex_and_wakeup(void* arg) {
erase_from_butex(static_cast<ButexWaiter*>(arg), true, WAITER_STATE_TIMEDOUT);
}
// Used in task_group.cpp
bool erase_from_butex_because_of_interruption(ButexWaiter* bw) {
return erase_from_butex(bw, true, WAITER_STATE_INTERRUPTED);
}
inline bool erase_from_butex(ButexWaiter* bw, bool wakeup, WaiterState state) {
// `bw' is guaranteed to be valid inside this function because waiter
// will wait until this function being cancelled or finished.
// NOTE: This function must be no-op when bw->container is NULL.
bool erased = false;
Butex* b;
int saved_errno = errno;
while ((b = bw->container.load(butil::memory_order_acquire))) {
// b can be NULL when the waiter is scheduled but queued.
BAIDU_SCOPED_LOCK(b->waiter_lock);
if (b == bw->container.load(butil::memory_order_relaxed)) {
bw->RemoveFromList(); // 把bw从butex的链表中移除
bw->container.store(NULL, butil::memory_order_relaxed);
if (bw->tid) {
static_cast<ButexBthreadWaiter*>(bw)->waiter_state = state;
}
erased = true;
break;
}
}
if (erased && wakeup) { // 如果移除成功并且需要wakeup(wakeup就是需要执行的意思),那就准备开始执行
if (bw->tid) { // 如果有tid,那就是bthread,放到tg中执行
ButexBthreadWaiter* bbw = static_cast<ButexBthreadWaiter*>(bw);
get_task_group(bbw->control)->ready_to_run_general(bw->tid);
} else { // 如果没有牛就是在pthread上执行的,wakeup_pthread调用futex_wake
ButexPthreadWaiter* pw = static_cast<ButexPthreadWaiter*>(bw);
wakeup_pthread(pw);
}
}
errno = saved_errno;
return erased;
}
static void wait_for_butex(void* arg) {
ButexBthreadWaiter* const bw = static_cast<ButexBthreadWaiter*>(arg);
Butex* const b = bw->initial_butex;
// 1: waiter with timeout should have waiter_state == WAITER_STATE_READY
// before they're queued, otherwise the waiter is already timedout
// and removed by TimerThread, in which case we should stop queueing.
//
// Visibility of waiter_state:
// [bthread] [TimerThread]
// waiter_state = TIMED
// tt_lock { add task }
// tt_lock { get task }
// waiter_lock { waiter_state=TIMEDOUT }
// waiter_lock { use waiter_state }
// tt_lock represents TimerThread::_mutex. Visibility of waiter_state is
// sequenced by two locks, both threads are guaranteed to see the correct
// value.
{
BAIDU_SCOPED_LOCK(b->waiter_lock);
if (b->value.load(butil::memory_order_relaxed) != bw->expected_value) {
bw->waiter_state = WAITER_STATE_UNMATCHEDVALUE;
} else if (bw->waiter_state == WAITER_STATE_READY/*1*/ &&
!bw->task_meta->interrupted) { // 除了waiter的状态,这里还需要判断tm的状态,也就是1、我还要不要wait? 2、这个tm还要不要执行?
b->waiters.Append(bw); // bw加到b->waiters这个链表上(这里相当于就是wait了)
bw->container.store(b, butil::memory_order_relaxed);
return;
}
}
// b->container is NULL which makes erase_from_butex_and_wakeup() and
// TaskGroup::interrupt() no-op, there's no race between following code and
// the two functions. The on-stack ButexBthreadWaiter is safe to use and
// bw->waiter_state will not change again.
unsleep_if_necessary(bw, get_global_timer_thread()); // 把tm从timer_thread中拿出来,因为前面判断的状态不对,已经不需要sleep了
tls_task_group->ready_to_run(bw->tid); // 不需要wait,准备开始开始执行(如果需要wait前面肯定已经return了)
// FIXME: jump back to original thread is buggy.
// // Value unmatched or waiter is already woken up by TimerThread, jump
// // back to original bthread.
// TaskGroup* g = tls_task_group;
// ReadyToRunArgs args = { g->current_tid(), false };
// g->set_remained(TaskGroup::ready_to_run_in_worker, &args);
// // 2: Don't run remained because we're already in a remained function
// // otherwise stack may overflow.
// TaskGroup::sched_to(&g, bw->tid, false/*2*/);
}
static int butex_wait_from_pthread(TaskGroup* g, Butex* b, int expected_value,
const timespec* abstime) {
// sys futex needs relative timeout.
// Compute diff between abstime and now.
timespec* ptimeout = NULL;
timespec timeout;
if (abstime != NULL) {
const int64_t timeout_us = butil::timespec_to_microseconds(*abstime) -
butil::gettimeofday_us();
if (timeout_us < MIN_SLEEP_US) {
errno = ETIMEDOUT;
return -1;
}
timeout = butil::microseconds_to_timespec(timeout_us);
ptimeout = &timeout;
}
TaskMeta* task = NULL;
ButexPthreadWaiter pw;
pw.tid = 0;
pw.sig.store(PTHREAD_NOT_SIGNALLED, butil::memory_order_relaxed);
int rc = 0;
if (g) {
task = g->current_task();
task->current_waiter.store(&pw, butil::memory_order_release);
}
b->waiter_lock.lock();
if (b->value.load(butil::memory_order_relaxed) != expected_value) {
b->waiter_lock.unlock();
errno = EWOULDBLOCK;
rc = -1;
} else if (task != NULL && task->interrupted) {
b->waiter_lock.unlock();
// Race with set and may consume multiple interruptions, which are OK.
task->interrupted = false;
errno = EINTR;
rc = -1;
} else {
b->waiters.Append(&pw);
pw.container.store(b, butil::memory_order_relaxed);
b->waiter_lock.unlock();
#ifdef SHOW_BTHREAD_BUTEX_WAITER_COUNT_IN_VARS
bvar::Adder<int64_t>& num_waiters = butex_waiter_count();
num_waiters << 1;
#endif
rc = wait_pthread(pw, ptimeout);
#ifdef SHOW_BTHREAD_BUTEX_WAITER_COUNT_IN_VARS
num_waiters << -1;
#endif
}
if (task) {
// If current_waiter is NULL, TaskGroup::interrupt() is running and
// using pw, spin until current_waiter != NULL.
BT_LOOP_WHEN(task->current_waiter.exchange(
NULL, butil::memory_order_acquire) == NULL,
30/*nops before sched_yield*/);
if (task->interrupted) {
task->interrupted = false;
if (rc == 0) {
errno = EINTR;
return -1;
}
}
}
return rc;
}
// 参考:https://blog.csdn.net/KIDGIN7439/article/details/106219059
int butex_wait(void* arg, int expected_value, const timespec* abstime) {
Butex* b = container_of(static_cast<butil::atomic<int>*>(arg), Butex, value); // arg必须是某个创建好的Butex中的value才行(使用container_of的前提条件)
if (b->value.load(butil::memory_order_relaxed) != expected_value) {
errno = EWOULDBLOCK;
// Sometimes we may take actions immediately after unmatched butex,
// this fence makes sure that we see changes before changing butex.
// TODO(xcy): 什么叫sometimes,这里什么也没干啊。是不是说这里没有unmatched也希望其他地方看到unmatched
butil::atomic_thread_fence(butil::memory_order_acquire);
return -1;
}
TaskGroup* g = tls_task_group;
if (NULL == g || g->is_current_pthread_task()) { // 当前任务运行在pthread上
return butex_wait_from_pthread(g, b, expected_value, abstime); // futex_wait
}
ButexBthreadWaiter bbw;
// tid is 0 iff the thread is non-bthread
bbw.tid = g->current_tid();
bbw.container.store(NULL, butil::memory_order_relaxed);
bbw.task_meta = g->current_task();
bbw.sleep_id = 0;
bbw.waiter_state = WAITER_STATE_READY;
bbw.expected_value = expected_value;
bbw.initial_butex = b;
bbw.control = g->control();
if (abstime != NULL) {
// Schedule timer before queueing. If the timer is triggered before
// queueing, cancel queueing. This is a kind of optimistic locking.
if (butil::timespec_to_microseconds(*abstime) <
(butil::gettimeofday_us() + MIN_SLEEP_US)) {
// Already timed out.
errno = ETIMEDOUT;
return -1;
}
bbw.sleep_id = get_global_timer_thread()->schedule(
erase_from_butex_and_wakeup, &bbw, *abstime); // wakeup任务放到timer_thread中
if (!bbw.sleep_id) { // TimerThread stopped.
errno = ESTOP;
return -1;
}
}
#ifdef SHOW_BTHREAD_BUTEX_WAITER_COUNT_IN_VARS
bvar::Adder<int64_t>& num_waiters = butex_waiter_count();
num_waiters << 1;
#endif
// release fence matches with acquire fence in interrupt_and_consume_waiters
// in task_group.cpp to guarantee visibility of `interrupted'.
// TODO(xcy)
bbw.task_meta->current_waiter.store(&bbw, butil::memory_order_release);
g->set_remained(wait_for_butex, &bbw);
TaskGroup::sched(&g); // tg开始执行下一个tm,当前正在运行的tm通过上面的wait_for_butex开始wait
// erase_from_butex_and_wakeup (called by TimerThread) is possibly still
// running and using bbw. The chance is small, just spin until it's done.
// TODO(xcy): bbw使用情况。上面sched已经切走了任务,当执行到这里的时候,说明tm已经恢复执行了
// tm被wake后,需要把erase_from_butex_and_wakeup从timer_thread中拿出来
BT_LOOP_WHEN(unsleep_if_necessary(&bbw, get_global_timer_thread()) < 0,
30/*nops before sched_yield*/);
// If current_waiter is NULL, TaskGroup::interrupt() is running and using bbw.
// Spin until current_waiter != NULL.
BT_LOOP_WHEN(bbw.task_meta->current_waiter.exchange(
NULL, butil::memory_order_acquire) == NULL,
30/*nops before sched_yield*/);
#ifdef SHOW_BTHREAD_BUTEX_WAITER_COUNT_IN_VARS
num_waiters << -1;
#endif
bool is_interrupted = false;
if (bbw.task_meta->interrupted) {
// Race with set and may consume multiple interruptions, which are OK.
bbw.task_meta->interrupted = false;
is_interrupted = true;
}
// If timed out as well as value unmatched, return ETIMEDOUT.
if (WAITER_STATE_TIMEDOUT == bbw.waiter_state) {
errno = ETIMEDOUT;
return -1;
} else if (WAITER_STATE_UNMATCHEDVALUE == bbw.waiter_state) {
errno = EWOULDBLOCK;
return -1;
} else if (is_interrupted) {
errno = EINTR;
return -1;
} // 代码执行到这里,说明tm重新执行,timeout、unmatched、interrupted都属于没有被正常的wakeup,所以返回-1
return 0;
}
} // namespace bthread
namespace butil {
template <> struct ObjectPoolBlockMaxItem<bthread::Butex> {
static const size_t value = 128;
};
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include "ImGuiManager.h"
#include <AzCore/PlatformIncl.h>
#include <platform_impl.h>
#ifdef IMGUI_ENABLED
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzFramework/Input/Buses/Requests/InputTextEntryRequestBus.h>
#include <AzFramework/Input/Devices/Mouse/InputDeviceMouse.h>
#include <AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard.h>
#include <AzFramework/Input/Devices/Gamepad/InputDeviceGamepad.h>
#include <AzFramework/Input/Devices/Touch/InputDeviceTouch.h>
#include <AzFramework/Input/Devices/VirtualKeyboard/InputDeviceVirtualKeyboard.h>
#include <IHardwareMouse.h>
#include <imgui/imgui_internal.h>
#include <sstream>
#include <string>
using namespace AzFramework;
using namespace ImGui;
// Wheel Delta const value.
const constexpr uint32_t IMGUI_WHEEL_DELTA = 120; // From WinUser.h, for Linux
// Typedef and local static map to hold LyInput->ImGui Nav mappings ( filled up in Initialize() )
typedef AZStd::pair<AzFramework::InputChannelId, ImGuiNavInput_> LyButtonImGuiNavIndexPair;
typedef AZStd::unordered_map<AzFramework::InputChannelId, ImGuiNavInput_> LyButtonImGuiNavIndexMap;
static LyButtonImGuiNavIndexMap s_lyInputToImGuiNavIndexMap;
/**
An anonymous namespace containing helper functions for interoperating with AzFrameworkInput.
*/
namespace
{
/**
Utility function to map an AzFrameworkInput device key to its integer index.
@param inputChannelId the ID for an AzFrameworkInput device key.
@return the index of the indicated key, or -1 if not found.
*/
unsigned int GetAzKeyIndex(const InputChannelId& inputChannelId)
{
const auto& keys = InputDeviceKeyboard::Key::All;
const auto& it = AZStd::find(keys.cbegin(), keys.cend(), inputChannelId);
return it != keys.cend() ? static_cast<unsigned int>(it - keys.cbegin()) : UINT_MAX;
}
/**
Utility function to map an AzFrameworkInput mouse device button to its integer index.
@param inputChannelId the ID for an AzFrameworkInput mouse device button.
@return the index of the indicated button, or -1 if not found.
*/
unsigned int GetAzMouseButtonIndex(const InputChannelId& inputChannelId)
{
const auto& buttons = InputDeviceMouse::Button::All;
const auto& it = AZStd::find(buttons.cbegin(), buttons.cend(), inputChannelId);
return it != buttons.cend() ? static_cast<unsigned int>(it - buttons.cbegin()) : UINT_MAX;
}
/**
Utility function to map an AzFrameworkInput touch input to its integer index.
@param inputChannelId the ID for an AzFrameworkInput touch input.
@return the index of the indicated touch, or -1 if not found.
*/
unsigned int GetAzTouchIndex(const InputChannelId& inputChannelId)
{
const auto& touches = InputDeviceTouch::Touch::All;
const auto& it = AZStd::find(touches.cbegin(), touches.cend(), inputChannelId);
return it != touches.cend() ? static_cast<unsigned int>(it - touches.cbegin()) : UINT_MAX;
}
/**
Utility function to map an AzFrameworkInput controller button to its integer index.
@param inputChannelId the ID for an AzFrameworkInput controller button.
@return the index of the indicated button, or -1 if not found.
*/
unsigned int GetAzControllerButtonIndex(const InputChannelId& inputChannelId)
{
const auto& buttons = InputDeviceGamepad::Button::All;
const auto& triggers = InputDeviceGamepad::Trigger::All;
const auto& it = AZStd::find(buttons.cbegin(), buttons.cend(), inputChannelId);
if (it != buttons.cend())
{
return static_cast<unsigned int>(it - buttons.cbegin());
}
else
{
const auto& it2 = AZStd::find(triggers.cbegin(), triggers.cend(), inputChannelId);
if (it2 != triggers.cend())
{
return static_cast<unsigned int>(it2 - triggers.cbegin()) + AZ_ARRAY_SIZE(InputDeviceGamepad::Button::All);
}
}
return UINT_MAX;
}
/**
Utility function to map an AzFrameworkInput thumbstick movement to its integer index.
@param inputChannelId the ID for an AzFrameworkInput thumbstick movement.
@return the index of the indicated button, or -1 if not found.
*/
unsigned int GetAzControllerThumbstickIndex(const InputChannelId& inputChannelId)
{
const auto& thumbstickMovements = InputDeviceGamepad::ThumbStickDirection::All;
const auto& it = AZStd::find(thumbstickMovements.cbegin(), thumbstickMovements.cend(), inputChannelId);
return it != thumbstickMovements.cend() ? static_cast<unsigned int>(it - thumbstickMovements.cbegin()) : UINT_MAX;
}
/**
Utility function to map an AzFrameworkInput thumbstick movement amountto its integer index.
@param inputChannelId the ID for an AzFrameworkInput thumbstick movement amount.
@return the index of the indicated button, or -1 if not found.
*/
unsigned int GetAzControllerThumbstickAmountIndex(const InputChannelId& inputChannelId)
{
const auto& thumbstickMovementAmounts = InputDeviceGamepad::ThumbStickAxis1D::All;
const auto& it = AZStd::find(thumbstickMovementAmounts.cbegin(), thumbstickMovementAmounts.cend(), inputChannelId);
return it != thumbstickMovementAmounts.cend() ? static_cast<unsigned int>(it - thumbstickMovementAmounts.cbegin()) : UINT_MAX;
}
}
void ImGuiManager::Initialize()
{
if (!gEnv || !gEnv->pGame || !gEnv->pRenderer)
{
AZ_Warning("ImGuiManager", false, "%s %s", __func__, "gEnv Invalid -- Skipping ImGui Initialization.");
return;
}
// Register for Game Framework Notifications
auto framework = gEnv->pGame->GetIGameFramework();
framework->RegisterListener(this, "ImGuiManager", FRAMEWORKLISTENERPRIORITY_HUD);
ImGuiManagerListenerBus::Handler::BusConnect();
// Register for Input Notifications
InputChannelEventListener::Connect();
InputTextEventListener::Connect();
// Dynamically Load ImGui
#if defined(LOAD_IMGUI_LIB_DYNAMICALLY)
AZ::OSString imgGuiLibPath = "imguilib";
// Let the application process the path
AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::ResolveModulePath, imgGuiLibPath);
m_imgSharedLib = AZ::DynamicModuleHandle::Create(imgGuiLibPath.c_str());
if (!m_imgSharedLib->Load(false))
{
AZ_Warning("ImGuiManager", false, "%s %s", __func__, "Unable to load " AZ_DYNAMIC_LIBRARY_PREFIX "imguilib" AZ_DYNAMIC_LIBRARY_EXTENSION "-- Skipping ImGui Initialization.");
return;
}
#endif // defined(LOAD_IMGUI_LIB_DYNAMICALLY)
// Create ImGui Context
ImGui::CreateContext();
// Set config file
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = "imgui.ini";
// Enable Nav Keyboard by default and allow
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableSetMousePos;
// Config Keyboard Mapping keys.
io.KeyMap[ImGuiKey_Tab] = GetAzKeyIndex(InputDeviceKeyboard::Key::EditTab);
io.KeyMap[ImGuiKey_LeftArrow] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationArrowLeft);
io.KeyMap[ImGuiKey_RightArrow] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationArrowRight);
io.KeyMap[ImGuiKey_UpArrow] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationArrowUp);
io.KeyMap[ImGuiKey_DownArrow] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationArrowDown);
io.KeyMap[ImGuiKey_PageUp] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationPageUp);
io.KeyMap[ImGuiKey_PageDown] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationPageDown);
io.KeyMap[ImGuiKey_Home] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationHome);
io.KeyMap[ImGuiKey_End] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationEnd);
io.KeyMap[ImGuiKey_Insert] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationInsert);
io.KeyMap[ImGuiKey_Delete] = GetAzKeyIndex(InputDeviceKeyboard::Key::NavigationDelete);
io.KeyMap[ImGuiKey_Backspace] = GetAzKeyIndex(InputDeviceKeyboard::Key::EditBackspace);
io.KeyMap[ImGuiKey_Space] = GetAzKeyIndex(InputDeviceKeyboard::Key::EditSpace);
io.KeyMap[ImGuiKey_Enter] = GetAzKeyIndex(InputDeviceKeyboard::Key::EditEnter);
io.KeyMap[ImGuiKey_Escape] = GetAzKeyIndex(InputDeviceKeyboard::Key::Escape);
io.KeyMap[ImGuiKey_A] = GetAzKeyIndex(InputDeviceKeyboard::Key::AlphanumericA);
io.KeyMap[ImGuiKey_C] = GetAzKeyIndex(InputDeviceKeyboard::Key::AlphanumericC);
io.KeyMap[ImGuiKey_V] = GetAzKeyIndex(InputDeviceKeyboard::Key::AlphanumericV);
io.KeyMap[ImGuiKey_X] = GetAzKeyIndex(InputDeviceKeyboard::Key::AlphanumericX);
io.KeyMap[ImGuiKey_Y] = GetAzKeyIndex(InputDeviceKeyboard::Key::AlphanumericY);
io.KeyMap[ImGuiKey_Z] = GetAzKeyIndex(InputDeviceKeyboard::Key::AlphanumericZ);
// Initialize controller button mapping
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::A, ImGuiNavInput_Activate));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::B, ImGuiNavInput_Cancel));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::X, ImGuiNavInput_Menu));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::Y, ImGuiNavInput_Input));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::DU, ImGuiNavInput_DpadUp));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::DD, ImGuiNavInput_DpadDown));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::DL, ImGuiNavInput_DpadLeft));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::DR, ImGuiNavInput_DpadRight));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::R1, ImGuiNavInput_FocusNext));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Button::L1, ImGuiNavInput_FocusPrev));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Trigger::L2, ImGuiNavInput_TweakSlow));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::Trigger::R2, ImGuiNavInput_TweakFast));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::ThumbStickDirection::LU, ImGuiNavInput_LStickUp));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::ThumbStickDirection::LD, ImGuiNavInput_LStickDown));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::ThumbStickDirection::LL, ImGuiNavInput_LStickLeft));
s_lyInputToImGuiNavIndexMap.insert(LyButtonImGuiNavIndexPair(InputDeviceGamepad::ThumbStickDirection::LR, ImGuiNavInput_LStickRight));
// Set the Display Size
IRenderer* renderer = gEnv->pRenderer;
io.DisplaySize.x = static_cast<float>(renderer->GetWidth());
io.DisplaySize.y = static_cast<float>(renderer->GetHeight());
// Create Font Texture
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height);
ITexture* fontTexture =
renderer->Create2DTexture("ImGuiFont", width, height, 1, FT_ALPHA, pixels, eTF_A8);
if (fontTexture)
{
m_fontTextureId = fontTexture->GetTextureID();
io.Fonts->SetTexID(static_cast<void*>(fontTexture));
}
// Broadcast ImGui Ready to Listeners
ImGuiUpdateListenerBus::Broadcast(&IImGuiUpdateListener::OnImGuiInitialize);
m_currentControllerIndex = -1;
m_button1Pressed = m_button2Pressed = false;
m_menuBarStatusChanged = false;
// See if a hardware mouse device is connected on startup, we will use it to help determine if we should draw the mouse cursor and turn on controller support by default if one is not found.
// Future work here could include responding to the mouse being connected and disconnected at run-time, but this is fine for now.
const AzFramework::InputDevice* mouseDevice = AzFramework::InputDeviceRequests::FindInputDevice(AzFramework::InputDeviceMouse::Id);
m_hardwardeMouseConnected = mouseDevice && mouseDevice->IsConnected();
}
void ImGuiManager::Shutdown()
{
if (!gEnv || !gEnv->pGame)
{
AZ_Warning("ImGuiManager", false, "%s %s", __func__, "gEnv Invalid -- Skipping ImGui Shutdown.");
return;
}
#if defined(LOAD_IMGUI_LIB_DYNAMICALLY)
if (m_imgSharedLib->IsLoaded())
{
m_imgSharedLib->Unload();
}
#endif
// Unregister from Buses/Game Framework
gEnv->pGame->GetIGameFramework()->UnregisterListener(this);
ImGuiManagerListenerBus::Handler::BusDisconnect();
InputChannelEventListener::Disconnect();
InputTextEventListener::Disconnect();
// Destroy ImGui Font Texture
if (gEnv->pRenderer && m_fontTextureId > 0)
{
ImGuiIO& io = ImGui::GetIO();
io.Fonts->SetTexID(nullptr);
gEnv->pRenderer->RemoveTexture(m_fontTextureId);
}
// Finally, destroy the ImGui Context.
ImGui::DestroyContext();
}
void ImGuiManager::OnPreRender()
{
if (m_clientMenuBarState == DisplayState::Hidden && m_editorWindowState == DisplayState::Hidden)
{
return;
}
// Update Display Size
IRenderer* renderer = gEnv->pRenderer;
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = m_lastRenderResolution;
if ((m_clientMenuBarState == DisplayState::Visible) || (m_editorWindowState != DisplayState::Hidden))
{
if (IsControllerSupportModeEnabled(ImGuiControllerModeFlags::Mouse))
{
// Update Mouse Position from Stick Position
m_controllerMousePosition[0] = AZ::GetClamp(m_controllerMousePosition[0] + ((io.NavInputs[ImGuiNavInput_LStickRight] - io.NavInputs[ImGuiNavInput_LStickLeft]) * m_controllerMouseSensitivity), 0.0f, m_renderResolution.x);
m_controllerMousePosition[1] = AZ::GetClamp(m_controllerMousePosition[1] + ((io.NavInputs[ImGuiNavInput_LStickDown] - io.NavInputs[ImGuiNavInput_LStickUp]) * m_controllerMouseSensitivity), 0.0f, m_renderResolution.y);
io.MousePos.x = m_controllerMousePosition[0];
io.MousePos.y = m_controllerMousePosition[1];
io.MouseDown[0] = (io.NavInputs[ImGuiNavInput_Activate] > 0.1f);
io.MouseDown[1] = (io.NavInputs[ImGuiNavInput_Cancel] > 0.1f);
}
else if (m_useLastPrimaryTouchPosition)
{
io.MousePos.x = m_lastPrimaryTouchPosition[0];
io.MousePos.y = m_lastPrimaryTouchPosition[1];
m_controllerMousePosition[0] = io.MousePos.x;
m_controllerMousePosition[1] = io.MousePos.y;
m_useLastPrimaryTouchPosition = false;
}
else
{
AZ::Vector2 systemCursorPositionNormalized = AZ::Vector2::CreateZero();
InputSystemCursorRequestBus::EventResult(
systemCursorPositionNormalized,
InputDeviceMouse::Id,
&InputSystemCursorRequests::GetSystemCursorPositionNormalized);
io.MousePos.x = systemCursorPositionNormalized.GetX() * m_lastRenderResolution.x;
io.MousePos.y = systemCursorPositionNormalized.GetY() * m_lastRenderResolution.y;
m_controllerMousePosition[0] = io.MousePos.x;
m_controllerMousePosition[1] = io.MousePos.y;
}
// Clear NavInputs if either the mouse is explicitly enabled, or if the contextual controller is explicitly disabled
if (IsControllerSupportModeEnabled(ImGuiControllerModeFlags::Mouse) || !IsControllerSupportModeEnabled(ImGuiControllerModeFlags::Contextual))
{
memset(io.NavInputs, 0, sizeof(io.NavInputs));
}
}
// If no item and no window is focused, we should artificially add focus to the Main Menu Bar, to save 1 step when navigating with a controller.
if (!ImGui::IsAnyItemFocused() && !ImGui::IsAnyWindowFocused())
{
ImGuiWindow* mainMenuWin = ImGui::FindWindowByName("##MainMenuBar");
if (mainMenuWin)
{
ImGui::GetCurrentContext()->NavLayer = ImGuiNavLayer_Menu;
ImGui::GetCurrentContext()->NavWindow = mainMenuWin;
ImGui::NavInitWindow(mainMenuWin, true);
}
}
// Show or hide the virtual keyboard as necessary
bool hasTextEntryStarted = false;
AzFramework::InputTextEntryRequestBus::EventResult(hasTextEntryStarted,
AzFramework::InputDeviceVirtualKeyboard::Id,
&AzFramework::InputTextEntryRequests::HasTextEntryStarted);
if (io.WantTextInput && !hasTextEntryStarted)
{
AzFramework::InputTextEntryRequests::VirtualKeyboardOptions options;
AzFramework::InputTextEntryRequestBus::Broadcast(&AzFramework::InputTextEntryRequests::TextEntryStart, options);
}
else if (!io.WantTextInput && hasTextEntryStarted)
{
AzFramework::InputTextEntryRequestBus::Broadcast(&AzFramework::InputTextEntryRequests::TextEntryStop);
io.KeysDown[GetAzKeyIndex(InputDeviceKeyboard::Key::EditEnter)] = false;
}
// Start New Frame
ImGui::NewFrame();
}
void ImGuiManager::OnPostUpdate(float fDeltaTime)
{
if (m_clientMenuBarState == DisplayState::Hidden && m_editorWindowState == DisplayState::Hidden)
{
return;
}
//// START FROM PREUPDATE
ICVar* consoleDisabled = gEnv->pConsole->GetCVar("sys_DeactivateConsole");
if (consoleDisabled && consoleDisabled->GetIVal() != 0)
{
m_clientMenuBarState = DisplayState::Hidden;
m_editorWindowState = DisplayState::Hidden;
}
// Advance ImGui by Elapsed Frame Time
ImGuiIO& io = ImGui::GetIO();
io.DeltaTime = fDeltaTime;
//// END FROM PREUPDATE
IRenderer* renderer = gEnv->pRenderer;
TransformationMatrices backupSceneMatrices;
// Find ImGui Render Resolution.
int renderRes[2];
switch (m_resolutionMode)
{
default:
break;
case ImGuiResolutionMode::LockToResolution:
renderRes[0] = static_cast<int>(m_renderResolution.x);
renderRes[1] = static_cast<int>(m_renderResolution.y);
break;
case ImGuiResolutionMode::MatchRenderResolution:
renderRes[0] = renderer->GetBackBufferWidth();
renderRes[1] = renderer->GetBackBufferHeight();
break;
case ImGuiResolutionMode::MatchToMaxRenderResolution:
if (renderer->GetBackBufferWidth() <= static_cast<int>(m_renderResolution.x))
{
renderRes[0] = renderer->GetBackBufferWidth();
renderRes[1] = renderer->GetBackBufferHeight();
}
else
{
renderRes[0] = static_cast<int>(m_renderResolution.x);
renderRes[1] = static_cast<int>(m_renderResolution.y);
}
break;
}
ImVec2 scaleRects( static_cast<float>(renderer->GetBackBufferWidth()) / static_cast<float>(renderRes[0]),
static_cast<float>(renderer->GetBackBufferHeight() / static_cast<float>(renderRes[1])));
// Save off the last render resolution for input
m_lastRenderResolution.x = static_cast<float>(renderRes[0]);
m_lastRenderResolution.y = static_cast<float>(renderRes[1]);
// Configure Renderer for 2D ImGui Rendering
renderer->SetCullMode(R_CULL_DISABLE);
renderer->Set2DMode(renderRes[0], renderRes[1], backupSceneMatrices);
renderer->SetColorOp(eCO_REPLACE, eCO_MODULATE, eCA_Diffuse, DEF_TEXARG0);
renderer->SetSrgbWrite(false);
renderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST);
// Render!
RenderImGuiBuffers(scaleRects);
// Cleanup Renderer Settings
renderer->Unset2DMode(backupSceneMatrices);
// Clear the simulated backspace key
if (m_simulateBackspaceKeyPressed)
{
io.KeysDown[GetAzKeyIndex(InputDeviceKeyboard::Key::EditBackspace)] = false;
m_simulateBackspaceKeyPressed = false;
}
}
/**
@return true if input should be consumed, false otherwise.
*/
bool ImGuiManager::OnInputChannelEventFiltered(const InputChannel& inputChannel)
{
ImGuiIO& io = ImGui::GetIO();
const InputChannelId& inputChannelId = inputChannel.GetInputChannelId();
const InputDeviceId& inputDeviceId = inputChannel.GetInputDevice().GetInputDeviceId();
// Handle Keyboard Hotkeys
if (inputDeviceId == InputDeviceKeyboard::Id && inputChannel.IsStateBegan())
{
// Cycle through ImGui Menu Bar States on Home button press
if (inputChannelId == InputDeviceKeyboard::Key::NavigationHome)
{
ToggleThroughImGuiVisibleState(-1);
}
// Cycle through Standalone Editor Window States
if (inputChannel.GetInputChannelId() == InputDeviceKeyboard::Key::NavigationEnd)
{
if (gEnv->IsEditor() && m_editorWindowState == DisplayState::Hidden)
{
ImGuiUpdateListenerBus::Broadcast(&IImGuiUpdateListener::OnOpenEditorWindow);
}
else
{
m_editorWindowState = m_editorWindowState == DisplayState::Visible
? DisplayState::VisibleNoMouse
: DisplayState::Visible;
}
}
}
// Handle Keyboard Modifier Keys
if (inputDeviceId == InputDeviceKeyboard::Id)
{
if (inputChannelId == InputDeviceKeyboard::Key::ModifierShiftL
|| inputChannelId == InputDeviceKeyboard::Key::ModifierShiftR)
{
io.KeyShift = inputChannel.IsActive();
}
else if (inputChannelId == InputDeviceKeyboard::Key::ModifierAltL
|| inputChannelId == InputDeviceKeyboard::Key::ModifierAltR)
{
io.KeyAlt = inputChannel.IsActive();
}
else if (inputChannelId == InputDeviceKeyboard::Key::ModifierCtrlL
|| inputChannelId == InputDeviceKeyboard::Key::ModifierCtrlR)
{
io.KeyCtrl = inputChannel.IsActive();
}
// Set Keydown Flag in ImGui Keys Array
const int keyIndex = GetAzKeyIndex(inputChannelId);
if (0 <= keyIndex && keyIndex < AZ_ARRAY_SIZE(io.KeysDown))
{
io.KeysDown[keyIndex] = inputChannel.IsActive();
}
}
// Handle Controller Inputs
int inputControllerIndex = -1;
bool controllerInput = false;
for (int i = 0; i < MaxControllerNumber; ++i)
{
//Allow only one controller navigating ImGui at the same time. After menu bar dismissed, other controllers could take over
if (inputDeviceId == InputDeviceGamepad::IdForIndexN(i))
{
inputControllerIndex = i;
controllerInput = true;
}
}
if (controllerInput)
{
// Only pipe in Controller Nav Inputs if we are the current Controller Index and at least 1 of the two controller modes are enabled.
if (m_currentControllerIndex == inputControllerIndex && m_controllerModeFlags)
{
const auto lyButtonToImGuiNav = s_lyInputToImGuiNavIndexMap.find(inputChannelId);
if (lyButtonToImGuiNav != s_lyInputToImGuiNavIndexMap.end())
{
const ImGuiNavInput_ imGuiNavInput = lyButtonToImGuiNav->second;
io.NavInputs[imGuiNavInput] = inputChannel.GetValue();
}
}
//Switch menu bar display only if two buttons are pressed at the same time
if (inputChannelId == InputDeviceGamepad::Button::L3)
{
if (inputChannel.IsStateBegan())
{
m_button1Pressed = true;
}
if (inputChannel.IsStateEnded())
{
m_button1Pressed = false;
m_menuBarStatusChanged = false;
}
}
if (inputChannelId == InputDeviceGamepad::Button::R3)
{
if (inputChannel.IsStateBegan())
{
m_button2Pressed = true;
}
if (inputChannel.IsStateEnded())
{
m_button2Pressed = false;
m_menuBarStatusChanged = false;
}
}
if (!m_menuBarStatusChanged && m_button1Pressed && m_button2Pressed)
{
ToggleThroughImGuiVisibleState(inputControllerIndex);
}
// If we have the Discrete Input Mode Enabled.. and we are in the Visible State, then consume input here
if (m_enableDiscreteInputMode && m_clientMenuBarState == DisplayState::Visible)
{
return true;
}
return false;
}
// Handle Mouse Inputs
if (inputDeviceId == InputDeviceMouse::Id)
{
const int mouseButtonIndex = GetAzMouseButtonIndex(inputChannelId);
if (0 <= mouseButtonIndex && mouseButtonIndex < AZ_ARRAY_SIZE(io.MouseDown))
{
io.MouseDown[mouseButtonIndex] = inputChannel.IsActive();
}
else if (inputChannelId == InputDeviceMouse::Movement::Z)
{
io.MouseWheel = inputChannel.GetValue() / static_cast<float>(IMGUI_WHEEL_DELTA);
}
}
// Handle Touch Inputs
if (inputDeviceId == InputDeviceTouch::Id)
{
const int touchIndex = GetAzTouchIndex(inputChannelId);
if (0 <= touchIndex && touchIndex < AZ_ARRAY_SIZE(io.MouseDown))
{
io.MouseDown[touchIndex] = inputChannel.IsActive();
}
if (touchIndex == 0)
{
const AzFramework::InputChannel::PositionData2D* positionData2D = inputChannel.GetCustomData<AzFramework::InputChannel::PositionData2D>();
if (positionData2D)
{
m_lastPrimaryTouchPosition[0] = positionData2D->m_normalizedPosition.GetX() * m_lastRenderResolution.x;
m_lastPrimaryTouchPosition[1] = positionData2D->m_normalizedPosition.GetY() * m_lastRenderResolution.y;
m_useLastPrimaryTouchPosition = true;
}
}
}
// Handle Virtual Keyboard Inputs
if (inputDeviceId == InputDeviceVirtualKeyboard::Id)
{
if (inputChannelId == AzFramework::InputDeviceVirtualKeyboard::Command::EditEnter)
{
// Simulate the enter key being pressed
io.KeysDown[GetAzKeyIndex(InputDeviceKeyboard::Key::EditEnter)] = true;
}
}
if (m_clientMenuBarState == DisplayState::Visible
|| m_editorWindowState == DisplayState::Visible)
{
io.WantCaptureMouse = true;
io.WantCaptureKeyboard = true;
// If we have the Discrete Input Mode Enabled.. then consume the input here.
if (m_enableDiscreteInputMode)
{
return true;
}
}
else
{
io.WantCaptureMouse = false;
io.WantCaptureKeyboard = false;
}
return false;
}
bool ImGuiManager::IsControllerSupportModeEnabled(ImGuiControllerModeFlags::FlagType controllerMode) const
{
return !!(m_controllerModeFlags & controllerMode);
}
void ImGuiManager::EnableControllerSupportMode(ImGuiControllerModeFlags::FlagType controllerMode, bool enable)
{
if (enable)
{
// Enable - Add flag by or'ing in.
m_controllerModeFlags |= controllerMode;
}
else
{
// Disable - Remove flag by and'ing the flag inverse
m_controllerModeFlags &= ~controllerMode;
}
const bool controllerMouseEnabled = IsControllerSupportModeEnabled(ImGuiControllerModeFlags::Mouse);
// Draw the ImGui Mouse cursor if either the hardware mouse is connected, or the controller mouse is enabled.
ImGui::GetIO().MouseDrawCursor = m_hardwardeMouseConnected || controllerMouseEnabled;
// Set or unset ImGui Config flags based on which modes are enabled.
if (controllerMouseEnabled)
{
ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_NavEnableGamepad;
ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_NavEnableKeyboard;
}
else if (IsControllerSupportModeEnabled(ImGuiControllerModeFlags::Contextual))
{
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
}
}
bool ImGuiManager::OnInputTextEventFiltered(const AZStd::string& textUTF8)
{
ImGuiIO& io = ImGui::GetIO();
io.AddInputCharactersUTF8(textUTF8.c_str());
if (textUTF8 == "\b" && !io.KeysDown[GetAzKeyIndex(InputDeviceKeyboard::Key::EditBackspace)])
{
// Simulate the backspace key being pressed
io.KeysDown[GetAzKeyIndex(InputDeviceKeyboard::Key::EditBackspace)] = true;
m_simulateBackspaceKeyPressed = true;
}
return io.WantCaptureKeyboard && m_clientMenuBarState == DisplayState::Visible;
}
void ImGuiManager::ToggleThroughImGuiVisibleState(int controllerIndex)
{
switch (m_clientMenuBarState)
{
case DisplayState::Hidden:
m_currentControllerIndex = controllerIndex;
m_clientMenuBarState = DisplayState::Visible;
// Draw the ImGui Mouse cursor if either the hardware mouse is connected, or the controller mouse is enabled.
ImGui::GetIO().MouseDrawCursor = m_hardwardeMouseConnected || IsControllerSupportModeEnabled(ImGuiControllerModeFlags::Mouse);
break;
case DisplayState::Visible:
m_clientMenuBarState = DisplayState::VisibleNoMouse;
ImGui::GetIO().MouseDrawCursor = false;
if (m_enableDiscreteInputMode)
{
// if we ARE Enabling the Discrete Input Mode, then we want to bail here, if not, we want to just fall below to the default case.
// no worries on setting m_clientMenuBarState twice..
break;
}
default:
m_clientMenuBarState = DisplayState::Hidden;
m_currentControllerIndex = -1;
break;
}
m_menuBarStatusChanged = true;
}
void ImGuiManager::RenderImGuiBuffers(const ImVec2& scaleRects)
{
// Trigger all listeners to run their updates
EBUS_EVENT(ImGuiUpdateListenerBus, OnImGuiUpdate);
// Run imgui's internal render and retrieve resulting draw data
ImGui::Render();
ImDrawData* drawData = ImGui::GetDrawData();
if (!drawData)
{
return;
}
// Supply Scale Rects
drawData->ScaleClipRects(scaleRects);
//@rky: Only render the main ImGui if it is visible
if (m_clientMenuBarState != DisplayState::Hidden)
{
IRenderer* renderer = gEnv->pRenderer;
// Expand vertex buffer if necessary
m_vertBuffer.reserve(drawData->TotalVtxCount);
if (m_vertBuffer.size() < drawData->TotalVtxCount)
{
m_vertBuffer.insert(m_vertBuffer.end(),
drawData->TotalVtxCount - m_vertBuffer.size(),
SVF_P3F_C4B_T2F());
}
// Expand index buffer if necessary
m_idxBuffer.reserve(drawData->TotalIdxCount);
if (m_idxBuffer.size() < drawData->TotalIdxCount)
{
m_idxBuffer.insert(m_idxBuffer.end(), drawData->TotalIdxCount - m_idxBuffer.size(), 0);
}
// Process each draw command list individually
for (int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList* cmd_list = drawData->CmdLists[n];
// Cache max vert count for easy access
int numVerts = cmd_list->VtxBuffer.Size;
// Copy command list verts into buffer
for (int i = 0; i < numVerts; ++i)
{
const ImDrawVert& imguiVert = cmd_list->VtxBuffer[i];
SVF_P3F_C4B_T2F& vert = m_vertBuffer[i];
vert.xyz = Vec3(imguiVert.pos.x, imguiVert.pos.y, 0.0f);
// Convert color from RGBA to ARGB
vert.color.dcolor = (imguiVert.col & 0xFF00FF00)
| ((imguiVert.col & 0xFF0000) >> 16)
| ((imguiVert.col & 0xFF) << 16);
vert.st = Vec2(imguiVert.uv.x, imguiVert.uv.y);
}
// Copy command list indices into buffer
for (int i = 0; i < cmd_list->IdxBuffer.Size; ++i)
{
m_idxBuffer[i] = uint16(cmd_list->IdxBuffer[i]);
}
// Use offset pointer to step along rendering operation
uint16* idxBufferDataOffset = m_idxBuffer.data();
// Process each draw command individually
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
// Defer to user rendering callback, if appropriate
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
// Otherwise render our buffers
else
{
int textureId = ((ITexture*)pcmd->TextureId)->GetTextureID();
renderer->SetTexture(textureId);
renderer->SetScissor((int)pcmd->ClipRect.x,
(int)(pcmd->ClipRect.y),
(int)(pcmd->ClipRect.z - pcmd->ClipRect.x),
(int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
renderer->DrawDynVB(m_vertBuffer.data(),
idxBufferDataOffset,
numVerts,
pcmd->ElemCount,
prtTriangleList);
}
// Update offset pointer into command list's index buffer
idxBufferDataOffset += pcmd->ElemCount;
}
}
// Reset scissor usage on renderer
renderer->SetScissor();
}
}
////// IMGUI CVAR STUFF /////////
namespace ImGuiCVARNames
{
static const char* s_imgui_AutoEnableComponents_Name = "imgui_AutoEnableComponents";
static const char* s_imgui_DiscreteInputMode_Name = "imgui_DiscreteInputMode";
static const char* s_imgui_EnableAssetExplorer_Name = "imgui_EnableAssetExplorer";
static const char* s_imgui_EnableCameraMonitor_Name = "imgui_EnableCameraMonitor";
static const char* s_imgui_EnableEntityOutliner_Name = "imgui_EnableEntityOutliner";
static const char* s_imgui_EnableImGui_Name = "imgui_EnableImGui";
static const char* s_imgui_EnableController_Name = "imgui_EnableController";
static const char* s_imgui_EnableControllerMouse_Name = "imgui_EnableControllerMouse";
static const char* s_imgui_ControllerMouseSensitivity_Name = "imgui_ControllerMouseSensitivity";
}
void OnAutoEnableComponentsCBFunc(ICVar* pArgs)
{
std::string token;
std::istringstream tokenStream(pArgs->GetString());
while (std::getline(tokenStream, token, ','))
{
AZStd::string enableSearchString = token.c_str();
ImGui::ImGuiEntityOutlinerRequestBus::Broadcast(&ImGui::IImGuiEntityOutlinerRequests::AddAutoEnableSearchString, enableSearchString);
}
}
void OnEnableEntityOutlinerCBFunc(ICVar* pArgs)
{
ImGui::ImGuiEntityOutlinerRequestBus::Broadcast(&ImGui::IImGuiEntityOutlinerRequests::SetEnabled, pArgs->GetIVal() != 0);
}
void OnEnableAssetExplorerCBFunc(ICVar* pArgs)
{
ImGui::ImGuiAssetExplorerRequestBus::Broadcast(&ImGui::IImGuiAssetExplorerRequests::SetEnabled, pArgs->GetIVal() != 0);
}
void OnEnableCameraMonitorCBFunc(ICVar* pArgs)
{
ImGui::ImGuiCameraMonitorRequestBus::Broadcast(&ImGui::IImGuiCameraMonitorRequests::SetEnabled, pArgs->GetIVal() != 0);
}
void OnShowImGuiCBFunc(ICVar* pArgs)
{
ImGui::ImGuiManagerListenerBus::Broadcast(&ImGui::IImGuiManagerListener::SetClientMenuBarState, pArgs->GetIVal() != 0 ? ImGui::DisplayState::Visible : ImGui::DisplayState::Hidden);
}
void OnDiscreteInputModeCBFunc(ICVar* pArgs)
{
ImGui::ImGuiManagerListenerBus::Broadcast(&ImGui::IImGuiManagerListener::SetEnableDiscreteInputMode, pArgs->GetIVal() != 0 );
}
void OnEnableControllerCBFunc(ICVar* pArgs)
{
ImGui::ImGuiManagerListenerBus::Broadcast(&ImGui::IImGuiManagerListener::EnableControllerSupportMode, ImGuiControllerModeFlags::Contextual, (pArgs->GetIVal() != 0));
}
void OnEnableControllerMouseCBFunc(ICVar* pArgs)
{
ImGui::ImGuiManagerListenerBus::Broadcast(&ImGui::IImGuiManagerListener::EnableControllerSupportMode, ImGuiControllerModeFlags::Mouse, (pArgs->GetIVal() != 0));
}
void OnControllerMouseSensitivityCBFunc(ICVar* pArgs)
{
ImGui::ImGuiManagerListenerBus::Broadcast(&ImGui::IImGuiManagerListener::SetControllerMouseSensitivity, pArgs->GetFVal());
}
void ImGuiManager::RegisterImGuiCVARs()
{
// These are already checked before we enter this function, but lets make double sure and prevent crashes.
if (!gEnv || !gEnv->pConsole)
{
return;
}
// We should also just make sure we aren't registering these twice. Check by just checking the first one.
if (gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_EnableImGui_Name) != nullptr)
{
return;
}
// Register CVARs
gEnv->pConsole->RegisterString(ImGuiCVARNames::s_imgui_AutoEnableComponents_Name, 0, VF_DEV_ONLY, CVARHELP("Enable ImGui Components by search string, as they are added to the Scene. Comma delimited list."), OnAutoEnableComponentsCBFunc);
gEnv->pConsole->RegisterInt(ImGuiCVARNames::s_imgui_EnableImGui_Name, 0, VF_DEV_ONLY, CVARHELP("Enable ImGui on Startup"), OnShowImGuiCBFunc);
gEnv->pConsole->RegisterInt(ImGuiCVARNames::s_imgui_EnableEntityOutliner_Name, 0, VF_DEV_ONLY, CVARHELP("Enable ImGui Entity Outliner on Startup"), OnEnableEntityOutlinerCBFunc);
gEnv->pConsole->RegisterInt(ImGuiCVARNames::s_imgui_EnableCameraMonitor_Name, 0, VF_DEV_ONLY, CVARHELP("Enable ImGui Camera Monitor on Startup"), OnEnableCameraMonitorCBFunc);
gEnv->pConsole->RegisterInt(ImGuiCVARNames::s_imgui_EnableAssetExplorer_Name, 0, VF_DEV_ONLY, CVARHELP("Enable ImGui Asset Explorer on Startup"), OnEnableAssetExplorerCBFunc);
gEnv->pConsole->RegisterInt(ImGuiCVARNames::s_imgui_DiscreteInputMode_Name, 0, VF_DEV_ONLY, CVARHELP("Enable ImGui Discrete Input Mode, adds a 2nd Visibility Mode, with the 1st having input going toward ImGui and the 2nd having input going toward the game. If not set, Input will go to both ImGui and the game when ImGui is enabled."), OnDiscreteInputModeCBFunc);
// Enable the Contextual Controller support by default when the hardware mouse is not detected.
gEnv->pConsole->RegisterInt(ImGuiCVARNames::s_imgui_EnableController_Name, (m_hardwardeMouseConnected ? 0 : 1), VF_DEV_ONLY, CVARHELP("Enable ImGui Controller support. Default to Off on PC, On on Console."), OnEnableControllerCBFunc);
gEnv->pConsole->RegisterInt(ImGuiCVARNames::s_imgui_EnableControllerMouse_Name, 0, VF_DEV_ONLY, CVARHELP("Enable ImGui Controller Mouse support. Default to Off on PC, On on Console."), OnEnableControllerMouseCBFunc);
gEnv->pConsole->RegisterFloat(ImGuiCVARNames::s_imgui_ControllerMouseSensitivity_Name, 5.0f, VF_DEV_ONLY, CVARHELP("ImGui Controller Mouse Sensitivty. Frame Multiplier for stick mouse sensitivity"), OnControllerMouseSensitivityCBFunc);
// Init CVARs to current values
OnAutoEnableComponentsCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_AutoEnableComponents_Name));
OnShowImGuiCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_EnableImGui_Name));
OnEnableAssetExplorerCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_EnableAssetExplorer_Name));
OnEnableCameraMonitorCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_EnableCameraMonitor_Name));
OnEnableEntityOutlinerCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_EnableEntityOutliner_Name));
OnDiscreteInputModeCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_DiscreteInputMode_Name));
OnEnableControllerCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_EnableController_Name));
OnEnableControllerMouseCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_EnableControllerMouse_Name));
OnControllerMouseSensitivityCBFunc(gEnv->pConsole->GetCVar(ImGuiCVARNames::s_imgui_ControllerMouseSensitivity_Name));
}
////// IMGUI CVAR STUFF /////////
#endif // ~IMGUI_ENABLED
|
/*******************************************************************************
* Copyright 2018-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef CPU_JIT_AVX512_CORE_F32_WINO_CONV_2X3_HPP
#define CPU_JIT_AVX512_CORE_F32_WINO_CONV_2X3_HPP
#include <assert.h>
#include "c_types_map.hpp"
#include "dnnl_thread.hpp"
#include "type_helpers.hpp"
#include "utils.hpp"
#include "cpu_convolution_pd.hpp"
#include "jit_generator.hpp"
#include "jit_primitive_conf.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
struct jit_avx512_core_f32_wino_conv_2x3_fwd_ker_t;
struct jit_avx512_core_f32_wino_conv_2x3_src_trans_t;
struct jit_avx512_core_f32_wino_conv_2x3_dst_trans_t;
struct jit_avx512_core_f32_wino_conv_2x3_fwd_t : public primitive_impl_t {
struct pd_t : public cpu_convolution_fwd_pd_t {
pd_t(engine_t *engine, const convolution_desc_t *adesc,
const primitive_attr_t *attr,
const typename pd_t::base_class *hint_fwd_pd)
: cpu_convolution_fwd_pd_t(engine, adesc, attr, hint_fwd_pd)
, jcp_() {}
DECLARE_COMMON_PD_T(
JIT_IMPL_NAME_HELPER("jit_fp32_wino_2x3:", avx512_core, ""),
jit_avx512_core_f32_wino_conv_2x3_fwd_t);
status_t init() {
bool ok = true && desc()->prop_kind == prop_kind::forward_inference
&& utils::one_of(desc()->alg_kind,
alg_kind::convolution_auto,
alg_kind::convolution_winograd)
&& expect_data_types(data_type::f32, data_type::f32,
data_type::f32, data_type::f32, data_type::f32)
&& attr()->has_default_values(
primitive_attr_t::skip_mask_t::post_ops)
&& set_default_formats();
if (!ok) return status::unimplemented;
memory_desc_t expect_wei_md = *weights_md();
status_t jit_conf_result = jit_conf(expect_wei_md);
if (jit_conf_result != status::success) return jit_conf_result;
set_default_alg_kind(alg_kind::convolution_winograd);
if (weights_md_.format_kind == format_kind::any)
weights_md_ = expect_wei_md;
if (weights_md_ != expect_wei_md) return status::unimplemented;
init_scratchpad();
return status::success;
}
jit_conv_conf_2x3_wino_t jcp_;
protected:
status_t jit_conf(memory_desc_t &expect_wei_md);
void init_scratchpad() {
using namespace memory_tracking::names;
auto scratchpad = scratchpad_registry().registrar();
int wino_size_offset = (jcp_.yb / 2) * (jcp_.xb / 2) + jcp_.xb;
size_t V_sz = (size_t)jcp_.ic * 16 * wino_size_offset * jcp_.nthr;
scratchpad.book(key_wino_V, sizeof(float) * V_sz, PAGE_4K);
size_t M_sz = (size_t)jcp_.oc * 16 * wino_size_offset * jcp_.nthr;
scratchpad.book(key_wino_M, sizeof(float) * M_sz, PAGE_4K);
if (wants_padded_bias()) {
assert(jcp_.ngroups == 1);
scratchpad.book(key_conv_padded_bias, sizeof(float) * jcp_.oc);
}
}
bool set_default_formats() {
using namespace format_tag;
return set_default_formats_common(nChw16c, any, nChw16c);
}
};
jit_avx512_core_f32_wino_conv_2x3_fwd_t(const pd_t *apd);
~jit_avx512_core_f32_wino_conv_2x3_fwd_t();
virtual status_t execute(const exec_ctx_t &ctx) const override {
auto src = CTX_IN_MEM(const float *, DNNL_ARG_SRC);
auto wei = CTX_IN_MEM(const float *, DNNL_ARG_WEIGHTS);
auto bia = CTX_IN_MEM(const float *, DNNL_ARG_BIAS);
auto dst = CTX_OUT_MEM(float *, DNNL_ARG_DST);
if (pd()->jcp_.small_mb)
execute_forward_small_mb(
src, wei, bia, dst, ctx.get_scratchpad_grantor());
else
execute_forward_mbN(
src, wei, bia, dst, ctx.get_scratchpad_grantor());
return status::success;
}
private:
void execute_forward_small_mb(const float *src, const float *wei,
const float *bia, float *dst,
const memory_tracking::grantor_t &scratchpad) const;
void execute_forward_mbN(const float *src, const float *wei,
const float *bia, float *dst,
const memory_tracking::grantor_t &scratchpad) const;
const pd_t *pd() const { return (const pd_t *)primitive_impl_t::pd(); }
jit_avx512_core_f32_wino_conv_2x3_fwd_ker_t *kernel_;
jit_avx512_core_f32_wino_conv_2x3_src_trans_t *src_trans_;
jit_avx512_core_f32_wino_conv_2x3_dst_trans_t *dst_trans_;
};
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
|
template<class T,class IT=int>
struct segtree{
const IT l,r;IT mid;
T fadd,fmul,fsum;
unique_ptr<segtree> ch[2];
segtree(const int l,const int r):l(l),r(r),mid(0),fadd(0),fmul(1),fsum(0){}
void wake(){
if (mid==0){
mid=(l+r)/2;
ch[0].reset(new segtree(l,mid));
ch[1].reset(new segtree(mid+1,r));
}
}
void dmul(const T& v){
fmul*=v;
fadd*=v;
fsum*=v;
}
void dadd(const T& v){
fadd+=v;
fsum+=v*(r-l+1);
}
void download(){
if (fmul!=1){
ch[0]->dmul(fmul);
ch[1]->dmul(fmul);
fmul=1;
}
if (fadd!=0){
ch[0]->dadd(fadd);
ch[1]->dadd(fadd);
fadd=0;
}
}
void upload(){
fsum=ch[0]->fsum+ch[1]->fsum;
}
};
template<class T0,class T1,class T2,class T3=decltype(declval<T0>().l)>
void edit(T0& tree,const T3& L,const T3& R,void (T0::*const& dfunc)(T1),const T2& v){
if (L<=tree.l&&tree.r<=R) return (tree.*dfunc)(v);
tree.wake();
tree.download();
if (L<=tree.mid) edit(*tree.ch[0],L,R,dfunc,v);
if (tree.mid+1<=R) edit(*tree.ch[1],L,R,dfunc,v);
tree.upload();
}
template<class T0,class T1,class T2,class opT,class T3=decltype(declval<T0>().l)>
T2 query(T0& tree,const T3& L,const T3& R,T1 T0::*const& dfunc,const T2& ini,const opT& op){
if (L<=tree.l&&tree.r<=R) return op(ini,tree.*dfunc);
tree.wake();
tree.download();
T2 a=ini;
if (L<=tree.mid) a=op(a,query(*tree.ch[0],L,R,dfunc,ini,op));
if (tree.mid+1<=R) a=op(a,query(*tree.ch[1],L,R,dfunc,ini,op));
return a;
}
#define edit(t,l,r,dfunc,v) edit(t,l,r,&decltype(t)::dfunc,v)
#define query(t,l,r,fobj,v,op) query(t,l,r,&decltype(t)::fobj,v,op)
|
//Language: MS C++
#pragma comment(linker, "/STACK:66777216")
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <queue>
#include <assert.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define sz(a) (int)a.size()
#define fill(a, x) memset(a, x, sizeof(a))
#ifdef _DEBUG
#define Eo(x) {cout << "# " << #x << " = " << (x) << endl;}
#define E(x) {cout << #x << " = " << (x) << "; ";}
#else
#define Eo(x)
#define E(x)
#endif
void sIO();
typedef pair<int, int> pii;
int n, m, x, y, a[111111];
vector< vector<int> > g, gr;
bool w1[111111], w2[111111], w[111111];
void dfs1(int v) {
w1[v] = true;
w[v] = true;
int kk = sz(g[v]), tto;
for (int i = 0; i < kk; ++i) {
tto = g[v][i];
if (!w[tto]) dfs1(tto);
}
}
void dfs2(int v) {
w2[v] = true;
w[v] = true;
if (a[v] == 1) return;
int kk = sz(gr[v]), tto;
for (int i = 0; i < kk; ++i) {
tto = gr[v][i];
if (!w[tto]) dfs2(tto);
}
}
int main() {
sIO();
scanf("%d %d", &n, &m);
g.resize(n + 5);
gr.resize(n + 5);
for (int i = 1; i <= n; ++i)
scanf("%d", a + i);
for (int i = 0; i < m; ++i) {
scanf("%d %d", &x, &y);
g[x].pb(y);
gr[y].pb(x);
}
fill(w1, 0);
fill(w2, 0);
fill(w, 0);
for (int i = 1; i <= n; ++i)
if (a[i] == 1) dfs1(i);
fill(w, 0);
for (int i = 1; i <= n; ++i)
if (a[i] == 2) dfs2(i);
for (int i = 1; i <= n; ++i)
printf("%d ", w1[i] && w2[i]);
return 0;
}
void sIO() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
|
/**
* \file groom.cpp
*
* Defines an algorithm to remove spurious inverting links from the graph
* by exploring the graph from the orientation supported by the most paths.
*/
#include "groom.hpp"
namespace odgi {
namespace algorithms {
std::vector<handle_t>groom(const handlegraph::MutablePathDeletableHandleGraph &graph, bool progress_reporting, bool use_bfs) {
// This (s) is our set of oriented nodes.
//dyn::succinct_bitvector<dyn::spsi<dyn::packed_vector,256,16> > s;
uint64_t min_handle_rank = std::numeric_limits<uint64_t>::max();
uint64_t max_handle_rank = 0;
graph.for_each_handle(
[&](const handle_t &found) {
uint64_t handle_rank = number_bool_packing::unpack_number(found);
min_handle_rank = std::min(min_handle_rank, handle_rank);
max_handle_rank = std::max(max_handle_rank, handle_rank);
});
// Start with the heads of the graph.
// We could also just use the first node of the graph.
std::vector<handle_t> seeds;
bool use_heads = true;
bool use_tails = false;
if (use_heads) {
seeds = head_nodes(&graph);
} else if (use_tails) {
seeds = tail_nodes(&graph);
} else {
handle_t min_handle = number_bool_packing::pack(min_handle_rank, false);
seeds = {min_handle};
}
// We need to keep track of the nodes we haven't visited to seed subsequent runs of the BFS
dyn::succinct_bitvector<dyn::spsi<dyn::packed_vector, 256, 16> > unvisited, flipped;
for (uint64_t i = 0; i <= max_handle_rank; ++i) {
unvisited.push_back(1);
flipped.push_back(0);
}
uint64_t prev_max_root = 0;
uint64_t prev_max_length = 0;
std::unique_ptr<progress_meter::ProgressMeter> bfs_progress;
if (progress_reporting) {
std::string banner = "[odgi::groom] grooming:";
bfs_progress = std::make_unique<progress_meter::ProgressMeter>(graph.get_node_count(), banner);
}
uint64_t edge_count = 0;
while (unvisited.rank1(unvisited.size()) != 0) {
if (use_bfs) {
bfs(graph,
[&graph, &unvisited, &flipped, &progress_reporting, &bfs_progress]
(const handle_t &h, const uint64_t &r, const uint64_t &l, const uint64_t &d) {
if (progress_reporting) {
bfs_progress->increment(1);
}
uint64_t i = number_bool_packing::unpack_number(h);
unvisited.set(i, 0);
flipped.set(i, graph.get_is_reverse(h));
},
[&unvisited](const handle_t &h) {
uint64_t i = number_bool_packing::unpack_number(h);
return unvisited.at(i) == 0;
},
[&edge_count](const handle_t &l, const handle_t &h) {
++edge_count;
return false;
},
[](void) { return false; },
seeds,
{},
false); // don't use bidirectional search
// get another seed
if (unvisited.rank1(unvisited.size()) != 0) {
uint64_t i = unvisited.select1(0);
handle_t h = number_bool_packing::pack(i, false);
seeds = {h};
}
} else {
dfs(graph,
[&graph, &unvisited, &flipped, &progress_reporting, &bfs_progress]
(const handle_t &h) {
if (progress_reporting) {
bfs_progress->increment(1);
}
uint64_t i = number_bool_packing::unpack_number(h);
unvisited.set(i, 0);
flipped.set(i, graph.get_is_reverse(h));
},
[&unvisited](const handle_t &h) {
uint64_t i = number_bool_packing::unpack_number(h);
return unvisited.at(i) == 0;
},
[](const handle_t& h) { return false; },
[](void) { return false; },
seeds);
//{},
//false); // don't use bidirectional search
// get another seed
if (unvisited.rank1(unvisited.size()) != 0) {
uint64_t i = unvisited.select1(0);
handle_t h = number_bool_packing::pack(i, false);
seeds = {h};
}
}
}
if (progress_reporting) {
bfs_progress->finish();
}
std::unique_ptr<progress_meter::ProgressMeter> handle_progress;
if (progress_reporting) {
std::string banner = "[odgi::groom] organizing handles:";
handle_progress = std::make_unique<progress_meter::ProgressMeter>(graph.get_node_count(), banner);
}
std::vector<handle_t> order;
uint64_t num_flipped_handles = 0;
graph.for_each_handle(
[&graph, &order, &flipped, &num_flipped_handles, &progress_reporting, &handle_progress](
const handle_t &h) {
bool to_flip = flipped[number_bool_packing::unpack_number(h)];
if (!to_flip) {
order.push_back(h);
} else {
order.push_back(graph.flip(h));
++num_flipped_handles;
}
if (progress_reporting) {
handle_progress->increment(1);
}
});
if (progress_reporting) {
handle_progress->finish();
std::cerr << "[odgi::groom] flipped " << num_flipped_handles << " handles" << std::endl;
}
return order;
}
}
}
|
/*!
* This is a subset and simplified version of Adafruit's
* "LED Backpack library for Arduino" adapted for the
* Raspberry Pi Pico.
*
* Author: Bernhard Bablok
*
* https://github.com/bablokb/pico-24bargraph
*
* Original source: https://github.com/adafruit/Adafruit_LED_Backpack
*
* @file Adafruit_LEDBackpack.cpp
*
* @mainpage Adafruit LED Backpack library for Arduino.
*
* @section intro_sec Introduction
*
* This is an Arduino library for our I2C LED Backpacks:
* ----> http://www.adafruit.com/products/
* ----> http://www.adafruit.com/products/
*
* These displays use I2C to communicate, 2 pins are required to
* interface. There are multiple selectable I2C addresses. For backpacks
* with 2 Address Select pins: 0x70, 0x71, 0x72 or 0x73. For backpacks
* with 3 Address Select pins: 0x70 thru 0x77
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section author Author
*
* Written by Limor Fried/Ladyada for Adafruit Industries.
*
* @section license License
*
* MIT license, all text above must be included in any redistribution
*
*/
#include "Pico_24bargraph.h"
#include "I2CDevice.h"
#ifndef _BV
#define _BV(bit) (1 << (bit)) ///< Bit-value if not defined by Arduino
#endif
void Pico_LEDBackpack::setBrightness(uint8_t b) {
if (b > 15)
b = 15; // limit to max brightness
uint8_t buffer = HT16K33_CMD_BRIGHTNESS | b;
_i2c_dev->write(&buffer, 1);
}
void Pico_LEDBackpack::blinkRate(uint8_t b) {
if (b > 3)
b = 0; // turn off if not sure
uint8_t buffer = HT16K33_BLINK_CMD | HT16K33_BLINK_DISPLAYON | (b << 1);
_i2c_dev->write(&buffer, 1);
}
Pico_LEDBackpack::Pico_LEDBackpack(I2CDevice* device) {
_i2c_dev = device;
// turn on oscillator
uint8_t buffer[1] = {0x21};
_i2c_dev->write(buffer, 1);
// internal RAM powers up with garbage/random values.
// ensure internal RAM is cleared before turning on display
// this ensures that no garbage pixels show up on the display
// when it is turned on.
clear();
writeDisplay();
blinkRate(HT16K33_BLINK_OFF);
setBrightness(15); // max brightness
}
void Pico_LEDBackpack::writeDisplay(void) {
uint8_t buffer[17];
buffer[0] = 0x00; // start at address $00
for (uint8_t i = 0; i < 8; i++) {
buffer[1 + 2 * i] = displaybuffer[i] & 0xFF;
buffer[2 + 2 * i] = displaybuffer[i] >> 8;
}
_i2c_dev->write(buffer, 17);
}
void Pico_LEDBackpack::clear(void) {
for (uint8_t i = 0; i < 8; i++) {
displaybuffer[i] = 0;
}
}
/******************************* 24 BARGRAPH OBJECT */
Pico_24bargraph::Pico_24bargraph(I2CDevice* i2cdev): Pico_LEDBackpack(i2cdev) {}
void Pico_24bargraph::setBar(uint8_t bar, uint8_t color) {
uint16_t a, c;
if (bar < 12)
c = bar / 4;
else
c = (bar - 12) / 4;
a = bar % 4;
if (bar >= 12)
a += 4;
if (color == LED_RED) {
// Turn on red LED.
displaybuffer[c] |= _BV(a);
// Turn off green LED.
displaybuffer[c] &= ~_BV(a + 8);
} else if (color == LED_YELLOW) {
// Turn on red and green LED.
displaybuffer[c] |= _BV(a) | _BV(a + 8);
} else if (color == LED_OFF) {
// Turn off red and green LED.
displaybuffer[c] &= ~_BV(a) & ~_BV(a + 8);
} else if (color == LED_GREEN) {
// Turn on green LED.
displaybuffer[c] |= _BV(a + 8);
// Turn off red LED.
displaybuffer[c] &= ~_BV(a);
}
}
|
/*
* TS Elements
* Copyright 2015-2018 M. Newhouse
* Released under the MIT license.
*/
#pragma once
#include "server_message_dispatcher.hpp"
#include "client_message.hpp"
#include "stage/stage_regulator.hpp"
#include "world/world_message_fwd.hpp"
#include "client/client_message_fwd.hpp"
namespace ts
{
namespace server
{
class Cup;
// This class wraps the essential components that we need
// for the server-sided part of a stage.
class Stage
{
public:
explicit Stage(std::unique_ptr<stage::Stage> stage_ptr, Cup* cup_obj = nullptr);
void update(std::uint32_t frame_duration);
const stage::StageDescription& stage_description() const;
const stage::Stage* stage() const;
template <typename MessageType>
void handle_message(const MessageType&) {} // Generic catch-all overload
void handle_message(const ClientMessage<client::messages::Update>& update_request);
void handle_message(const ClientMessage<stage::messages::ControlUpdate>& update_message);
void handle_message(const ClientMessage<client::messages::LocalConnection>& connect_message);
void handle_message(const ClientMessage<world::messages::CarPropertiesUpdate>& car_update);
// Internal message (server <-> server)
void handle_message(const world::messages::ControlPointHit& cp_hit);
// Car editor message
private:
stage::StageRegulator stage_regulator_;
MessageDispatcher message_dispatcher_;
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.