<commit_before>#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

// system
#include <sstream>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/model/thermalblock.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/finitevolume/dune-pdelab.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.fv.dp";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
    file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
    file << "numElements = 4" << std::endl;
    file << "filename = " << id << ".grid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.thermalblock]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.lowerLeft = [0.0; 0.0; 0.0]" << std::endl; // should coincide with the grid
    file << "diffusion.upperRight = [1.0; 1.0; 1.0]" << std::endl; // should coincide with the grid
    file << "diffusion.numElements = [2; 2; 2]"  << std::endl;
    file << "diffusion.components = [1.0; 10.0; 3.0; 2.1]"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.finitevolume.dune-pdelab]" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
Dune::shared_ptr< Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > >
  createModel(const Dune::Stuff::Common::ExtendedParameterTree& paramTree)
{
  // prepare
  paramTree.assertKey(id + ".model");
  const std::string modelId = paramTree.sub(id).get("model", "default_value");
  typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelInterfaceType;
  // choose model
  if (modelId == "detailed.solvers.stationary.linear.elliptic.model.default") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else if (modelId == "detailed.solvers.stationary.linear.elliptic.model.thermalblock") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else {
    std::stringstream msg;
    msg << std::endl << "Error in " << id << ": unknown model ('" << modelId << "') given in the following Dune::Parametertree" << std::endl;
    paramTree.report(msg);
    DUNE_THROW(Dune::InvalidStateException, msg.str());
  } // choose model
} // ... createModel(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::Stuff::Grid::Provider::Cube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id(), id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id()));
    typedef GridProviderType::GridType GridType;
    const GridType& grid = gridProvider.grid();
    typedef GridType::LeafGridView GridViewType;
    const Dune::shared_ptr< const GridViewType > gridView(new GridViewType(grid.leafView()));
    info << "  done (took " << timer.elapsed()
         << " sec, has " << grid.size(0) << " element";
    if (grid.size(0) > 1)
      info << "s";
    info << ")" << std::endl;
    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider.visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    // model
    info << "setting up model... " << std::flush;
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    paramTree.assertSub(id, id);
    typedef Dune::Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::Model::Interface<  DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    const Dune::shared_ptr< const ModelType >
        model = createModel< DomainFieldType, dimDomain, RangeFieldType, dimRange >(paramTree);
    typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // solver
    info << "initializing solver:" << std::endl;
    typedef Dune::Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::FiniteVolume::DunePdelab< ModelType, GridViewType, BoundaryInfoType, polOrder > SolverType;
    paramTree.assertSub(SolverType::id(), id);
    SolverType solver(model, gridView, boundaryInfo);
    solver.init("  ", debug);

    info << "solving:" << std::endl;
    typedef SolverType::TrialVectorType SolutionType;
    typedef Dune::shared_ptr<SolutionType> solution_ptr;
    solution_ptr solution = solution_ptr(new SolutionType(*(solver.gridFunctionSpace()),0.0));
//    evtl. dieses Anlegen des Vektors in eine Methode createVector() auslagern (die in DunePdelab liegt)?!
//    solution_ptr solution = solver.createVector();
    solver.solve(*solution, paramTree.sub(SolverType::id()).sub("solve"), "  ", debug);

    info << "postprocessing:" << std::endl;
    solver.visualize(*solution,
                     paramTree.sub(SolverType::id()).sub("visualize").get("filename", id + "_solution"),
                     paramTree.sub(SolverType::id()).sub("visualize").get("name", "solution"),
                     "  ",
                     debug);

    // if we came that far we can as well be happy about it
    return 0;
  } catch (Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch ( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<commit_msg>added mixed boundary types (should be cleaned up)<commit_after>#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

// system
#include <sstream>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/model/thermalblock.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/finitevolume/dune-pdelab.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.fv.dp";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
    file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
    file << "numElements = 4" << std::endl;
    file << "filename = " << id << ".grid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.thermalblock]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.lowerLeft = [0.0; 0.0; 0.0]" << std::endl; // should coincide with the grid
    file << "diffusion.upperRight = [1.0; 1.0; 1.0]" << std::endl; // should coincide with the grid
    file << "diffusion.numElements = [2; 2; 2]"  << std::endl;
    file << "diffusion.components = [1.0; 10.0; 3.0; 2.1]"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.finitevolume.dune-pdelab]" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
Dune::shared_ptr< Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > >
  createModel(const Dune::Stuff::Common::ExtendedParameterTree& paramTree)
{
  // prepare
  paramTree.assertKey(id + ".model");
  const std::string modelId = paramTree.sub(id).get("model", "default_value");
  typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelInterfaceType;
  // choose model
  if (modelId == "detailed.solvers.stationary.linear.elliptic.model.default") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else if (modelId == "detailed.solvers.stationary.linear.elliptic.model.thermalblock") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else {
    std::stringstream msg;
    msg << std::endl << "Error in " << id << ": unknown model ('" << modelId << "') given in the following Dune::Parametertree" << std::endl;
    paramTree.report(msg);
    DUNE_THROW(Dune::InvalidStateException, msg.str());
  } // choose model
} // ... createModel(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::Stuff::Grid::Provider::Cube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id(), id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id()));
    typedef GridProviderType::GridType GridType;
    const GridType& grid = gridProvider.grid();
    typedef GridType::LeafGridView GridViewType;
    const Dune::shared_ptr< const GridViewType > gridView(new GridViewType(grid.leafView()));
    info << "  done (took " << timer.elapsed()
         << " sec, has " << grid.size(0) << " element";
    if (grid.size(0) > 1)
      info << "s";
    info << ")" << std::endl;
    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider.visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    // model
    info << "setting up model... " << std::flush;
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    paramTree.assertSub(id, id);
    typedef Dune::Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::Model::Interface<  DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    const Dune::shared_ptr< const ModelType >
        model = createModel< DomainFieldType, dimDomain, RangeFieldType, dimRange >(paramTree);
    typedef Dune::Stuff::Grid::BoundaryInfo::IdBased BoundaryInfoType;
    typedef typename BoundaryInfoType::IdSetType IdSetType;
    typedef typename BoundaryInfoType::IdSetMapType IdSetMapType;
    Dune::shared_ptr< IdSetMapType > boundaryIdSetMap(new IdSetMapType());
    IdSetType dirichletSet;
    dirichletSet.insert(1);
    IdSetType neumannSet;
    neumannSet.insert(2);
    neumannSet.insert(3);
    neumannSet.insert(4);
    boundaryIdSetMap->insert(std::pair< std::string, IdSetType >("dirichlet", dirichletSet));
    boundaryIdSetMap->insert(std::pair< std::string, IdSetType >("neumann", neumannSet));
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType(boundaryIdSetMap));
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // solver
    info << "initializing solver:" << std::endl;
    typedef Dune::Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::FiniteVolume::DunePdelab< ModelType, GridViewType, BoundaryInfoType, polOrder > SolverType;
    paramTree.assertSub(SolverType::id(), id);
    SolverType solver(model, gridView, boundaryInfo);
    solver.init("  ", debug);

    info << "solving:" << std::endl;
    typedef SolverType::TrialVectorType SolutionType;
    typedef Dune::shared_ptr<SolutionType> solution_ptr;
    solution_ptr solution = solution_ptr(new SolutionType(*(solver.gridFunctionSpace()),0.0));
//    evtl. dieses Anlegen des Vektors in eine Methode createVector() auslagern (die in DunePdelab liegt)?!
//    solution_ptr solution = solver.createVector();
    solver.solve(*solution, paramTree.sub(SolverType::id()).sub("solve"), "  ", debug);

    info << "postprocessing:" << std::endl;
    solver.visualize(*solution,
                     paramTree.sub(SolverType::id()).sub("visualize").get("filename", id + "_solution"),
                     paramTree.sub(SolverType::id()).sub("visualize").get("name", "solution"),
                     "  ",
                     debug);

    // if we came that far we can as well be happy about it
    return 0;
  } catch (Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch ( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<|endoftext|>


<commit_before>/* Copyright (c) 2020 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/ir/mkldnn/scale_matmul_fuse_pass.h"

#include <string>
#include <vector>

#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/string/pretty_log.h"

namespace paddle {
namespace framework {
namespace ir {

class Graph;

using string::PrettyLogDetail;
ScaleMatmulFusePass::ScaleMatmulFusePass() {
  AddOpCompat(OpCompat("matmul"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("alpha")
      .IsNumGT(0.0f)
      .End()
      .AddAttr("transpose_X")
      .IsType<bool>()
      .End()
      .AddAttr("transpose_Y")
      .IsType<bool>()
      .End();

  AddOpCompat(OpCompat("scale"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("scale")
      .IsNumGT(0.0f)
      .End()
      .AddAttr("bias")
      .IsNumEQ(0.0f)
      .End()
      .AddAttr("bias_after_scale")
      .IsOptional()
      .IsType<bool>()
      .End();
}

void ScaleMatmulFusePass::ApplyImpl(ir::Graph* graph) const {
  PADDLE_ENFORCE_NOT_NULL(graph,
                          platform::errors::InvalidArgument(
                              "Pointer to graph argument should not be NULL."));

  FusePassBase::Init("scale_matmul_fuse_pass", graph);
  GraphPatternDetector gpd;
  patterns::ScaleMatmul scale_matmul_pattern{gpd.mutable_pattern(),
                                             "scale_matmul"};
  scale_matmul_pattern();

  int found_scale_matmul_fuse_count = 0;
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
    if (!IsCompat(subgraph, g)) {
      LOG(WARNING) << "Pass in op compat failed.";
      return;
    }
    GET_IR_NODE_FROM_SUBGRAPH(scale_in, scale_in, scale_matmul_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(scale_op, scale_op, scale_matmul_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(scale_out, scale_out, scale_matmul_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(matmul_op, matmul_op, scale_matmul_pattern);

    if (scale_op->Op()->GetAttrIfExists<float>("bias") == 0.0) {
      auto matmul_alpha = matmul_op->Op()->GetAttrIfExists<float>("alpha");
      auto scale_scale = scale_op->Op()->GetAttrIfExists<float>("scale");
      PADDLE_ENFORCE_GT(
          matmul_alpha, 0.0f,
          platform::errors::InvalidArgument(
              "Alpha(%f) of matmul op should have positive value.",
              matmul_alpha));
      PADDLE_ENFORCE_GT(scale_scale, 0.0f,
                        platform::errors::InvalidArgument(
                            "Scale(%f) of scale op should have positive value.",
                            scale_scale));

      std::string matmul_op_input_name;
      for (auto name : matmul_op->Op()->InputNames())
        for (auto input_name : matmul_op->Op()->Input(name))
          if (input_name == scale_out->Name()) matmul_op_input_name = name;

      PADDLE_ENFORCE_NE(
          matmul_op_input_name.empty(), true,
          platform::errors::NotFound("Operator after scale operator(%s) "
                                     "should have scale output as input.",
                                     scale_out->Name()));
      matmul_op->Op()->SetAttr("alpha", matmul_alpha * scale_scale);
      matmul_op->Op()->SetInput(matmul_op_input_name,
                                std::vector<std::string>({scale_in->Name()}));
      IR_NODE_LINK_TO(scale_in, matmul_op);

      if (!IsCompat(*matmul_op->Op())) {
        LOG(WARNING) << "scale_matmul_fuse_pass in out fc op compat failed.";
        return;
      }
      GraphSafeRemoveNodes(graph, {scale_op, scale_out});
      found_scale_matmul_fuse_count++;
    }
  };
  gpd(graph, handler);
  AddStatis(found_scale_matmul_fuse_count);
  if (!Has("disable_logs") || !Get<bool>("disable_logs"))
    PrettyLogDetail("---    fused %d scale with matmul",
                    found_scale_matmul_fuse_count);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(scale_matmul_fuse_pass,
              paddle::framework::ir::ScaleMatmulFusePass);

REGISTER_PASS_CAPABILITY(scale_matmul_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("scale", 0)
            .LE("matmul", 1));
<commit_msg>fix scale_matmul fuse pass (#43089)<commit_after>/* Copyright (c) 2020 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/ir/mkldnn/scale_matmul_fuse_pass.h"

#include <string>
#include <vector>

#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/string/pretty_log.h"

namespace paddle {
namespace framework {
namespace ir {

class Graph;

using string::PrettyLogDetail;
ScaleMatmulFusePass::ScaleMatmulFusePass() {
  AddOpCompat(OpCompat("matmul"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddInput("Y")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("alpha")
      .IsNumGT(0.0f)
      .End()
      .AddAttr("transpose_X")
      .IsType<bool>()
      .End()
      .AddAttr("transpose_Y")
      .IsType<bool>()
      .End();

  AddOpCompat(OpCompat("scale"))
      .AddInput("X")
      .IsTensor()
      .End()
      .AddOutput("Out")
      .IsTensor()
      .End()
      .AddAttr("scale")
      .IsNumGT(0.0f)
      .End()
      .AddAttr("bias")
      .IsNumEQ(0.0f)
      .End()
      .AddAttr("bias_after_scale")
      .IsOptional()
      .IsType<bool>()
      .End();
}

void ScaleMatmulFusePass::ApplyImpl(ir::Graph* graph) const {
  PADDLE_ENFORCE_NOT_NULL(graph,
                          platform::errors::InvalidArgument(
                              "Pointer to graph argument should not be NULL."));

  FusePassBase::Init("scale_matmul_fuse_pass", graph);
  GraphPatternDetector gpd;
  patterns::ScaleMatmul scale_matmul_pattern{gpd.mutable_pattern(),
                                             "scale_matmul"};
  scale_matmul_pattern();

  int found_scale_matmul_fuse_count = 0;
  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
    if (!IsCompat(subgraph, g)) {
      LOG(WARNING) << "Pass in op compat failed.";
      return;
    }
    GET_IR_NODE_FROM_SUBGRAPH(scale_in, scale_in, scale_matmul_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(scale_op, scale_op, scale_matmul_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(scale_out, scale_out, scale_matmul_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(matmul_op, matmul_op, scale_matmul_pattern);

    if ((scale_out->outputs).size() != 1) {
      return;
    }

    if (scale_op->Op()->GetAttrIfExists<float>("bias") == 0.0) {
      auto matmul_alpha = matmul_op->Op()->GetAttrIfExists<float>("alpha");
      auto scale_scale = scale_op->Op()->GetAttrIfExists<float>("scale");
      PADDLE_ENFORCE_GT(
          matmul_alpha, 0.0f,
          platform::errors::InvalidArgument(
              "Alpha(%f) of matmul op should have positive value.",
              matmul_alpha));
      PADDLE_ENFORCE_GT(scale_scale, 0.0f,
                        platform::errors::InvalidArgument(
                            "Scale(%f) of scale op should have positive value.",
                            scale_scale));

      std::string matmul_op_input_name;
      for (auto name : matmul_op->Op()->InputNames())
        for (auto input_name : matmul_op->Op()->Input(name))
          if (input_name == scale_out->Name()) matmul_op_input_name = name;

      PADDLE_ENFORCE_NE(
          matmul_op_input_name.empty(), true,
          platform::errors::NotFound("Operator after scale operator(%s) "
                                     "should have scale output as input.",
                                     scale_out->Name()));
      matmul_op->Op()->SetAttr("alpha", matmul_alpha * scale_scale);
      matmul_op->Op()->SetInput(matmul_op_input_name,
                                std::vector<std::string>({scale_in->Name()}));
      IR_NODE_LINK_TO(scale_in, matmul_op);

      if (!IsCompat(*matmul_op->Op())) {
        LOG(WARNING) << "scale_matmul_fuse_pass in out fc op compat failed.";
        return;
      }
      GraphSafeRemoveNodes(graph, {scale_op, scale_out});
      found_scale_matmul_fuse_count++;
    }
  };
  gpd(graph, handler);
  AddStatis(found_scale_matmul_fuse_count);
  if (!Has("disable_logs") || !Get<bool>("disable_logs"))
    PrettyLogDetail("---    fused %d scale with matmul",
                    found_scale_matmul_fuse_count);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(scale_matmul_fuse_pass,
              paddle::framework::ir::ScaleMatmulFusePass);

REGISTER_PASS_CAPABILITY(scale_matmul_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("scale", 0)
            .LE("matmul", 1));
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qtlocalpeer.h"

#include <QCoreApplication>
#include <QTime>

#if defined(Q_OS_WIN)
#include <QLibrary>
#include <qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif

#if defined(Q_OS_UNIX)
#include <time.h>
#include <unistd.h>
#endif

namespace SharedTools {

static const char ack[] = "ack";

QString QtLocalPeer::appSessionId(const QString &appId)
{
    QByteArray idc = appId.toUtf8();
    quint16 idNum = qChecksum(idc.constData(), idc.size());
    //### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqeness probability. Every-other-char split would be best.

    QString res = QLatin1String("qtsingleapplication-")
                 + QString::number(idNum, 16);
#if defined(Q_OS_WIN)
    if (!pProcessIdToSessionId) {
        QLibrary lib(QLatin1String("kernel32"));
        pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
    }
    if (pProcessIdToSessionId) {
        DWORD sessionId = 0;
        pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
        res += QLatin1Char('-') + QString::number(sessionId, 16);
    }
#else
    res += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
    return res;
}

QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
    : QObject(parent), id(appId)
{
    if (id.isEmpty())
        id = QCoreApplication::applicationFilePath();  //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win

    socketName = appSessionId(id);
    server = new QLocalServer(this);
    QString lockName = QDir(QDir::tempPath()).absolutePath()
                       + QLatin1Char('/') + socketName
                       + QLatin1String("-lockfile");
    lockFile.setFileName(lockName);
    lockFile.open(QIODevice::ReadWrite);
}

bool QtLocalPeer::isClient()
{
    if (lockFile.isLocked())
        return false;

    if (!lockFile.lock(QtLockedFile::WriteLock, false))
        return true;

    if (!QLocalServer::removeServer(socketName))
        qWarning("QtSingleCoreApplication: could not cleanup socket");
    bool res = server->listen(socketName);
    if (!res)
        qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
    QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
    return false;
}

bool QtLocalPeer::sendMessage(const QString &message, int timeout, bool block)
{
    if (!isClient())
        return false;

    QLocalSocket socket;
    bool connOk = false;
    for (int i = 0; i < 2; i++) {
        // Try twice, in case the other instance is just starting up
        socket.connectToServer(socketName);
        connOk = socket.waitForConnected(timeout/2);
        if (connOk || i)
            break;
        int ms = 250;
#if defined(Q_OS_WIN)
        Sleep(DWORD(ms));
#else
        struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
        nanosleep(&ts, NULL);
#endif
    }
    if (!connOk)
        return false;

    QByteArray uMsg(message.toUtf8());
    QDataStream ds(&socket);
    ds.writeBytes(uMsg.constData(), uMsg.size());
    bool res = socket.waitForBytesWritten(timeout);
    res &= socket.waitForReadyRead(timeout); // wait for ack
    res &= (socket.read(qstrlen(ack)) == ack);
    if (block) // block until peer disconnects
        socket.waitForDisconnected(-1);
    return res;
}

void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    // Why doesn't Qt have a blocking stream that takes care of this shait???
    while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {
        if (!socket->isValid()) // stale request
            return;
        socket->waitForReadyRead(1000);
    }
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    //qDebug() << "RCV: remaining" << remaining;
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
        //qDebug() << "RCV: got" << got << "remaining" << remaining;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    //### error check: got<0
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    // ### async this
    QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    emit messageReceived(message, socket); // ##(might take a long time to return)
}

} // namespace SharedTools
<commit_msg>bugfix for compiler error on ubuntu 16.04. - QDataStream<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qtlocalpeer.h"

#include <QCoreApplication>
#include <QTime>

#if defined(Q_OS_WIN)
#include <QLibrary>
#include <qt_windows.h>
typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif

#if defined(Q_OS_UNIX)
#include <time.h>
#include <unistd.h>
#endif

// @FIXME: bugfix for strange new compiler error on ubuntu 16.04 = ‘QDataStream ds’ has initializer but incomplete type
// not sure if that collides on other systems:
#include <QDataStream>

namespace SharedTools {

static const char ack[] = "ack";

QString QtLocalPeer::appSessionId(const QString &appId)
{
    QByteArray idc = appId.toUtf8();
    quint16 idNum = qChecksum(idc.constData(), idc.size());
    //### could do: two 16bit checksums over separate halves of id, for a 32bit result - improved uniqeness probability. Every-other-char split would be best.

    QString res = QLatin1String("qtsingleapplication-")
                 + QString::number(idNum, 16);
#if defined(Q_OS_WIN)
    if (!pProcessIdToSessionId) {
        QLibrary lib(QLatin1String("kernel32"));
        pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
    }
    if (pProcessIdToSessionId) {
        DWORD sessionId = 0;
        pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
        res += QLatin1Char('-') + QString::number(sessionId, 16);
    }
#else
    res += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
    return res;
}

QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
    : QObject(parent), id(appId)
{
    if (id.isEmpty())
        id = QCoreApplication::applicationFilePath();  //### On win, check if this returns .../argv[0] without casefolding; .\MYAPP == .\myapp on Win

    socketName = appSessionId(id);
    server = new QLocalServer(this);
    QString lockName = QDir(QDir::tempPath()).absolutePath()
                       + QLatin1Char('/') + socketName
                       + QLatin1String("-lockfile");
    lockFile.setFileName(lockName);
    lockFile.open(QIODevice::ReadWrite);
}

bool QtLocalPeer::isClient()
{
    if (lockFile.isLocked())
        return false;

    if (!lockFile.lock(QtLockedFile::WriteLock, false))
        return true;

    if (!QLocalServer::removeServer(socketName))
        qWarning("QtSingleCoreApplication: could not cleanup socket");
    bool res = server->listen(socketName);
    if (!res)
        qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
    QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
    return false;
}

bool QtLocalPeer::sendMessage(const QString &message, int timeout, bool block)
{
    if (!isClient())
        return false;

    QLocalSocket socket;
    bool connOk = false;
    for (int i = 0; i < 2; i++) {
        // Try twice, in case the other instance is just starting up
        socket.connectToServer(socketName);
        connOk = socket.waitForConnected(timeout/2);
        if (connOk || i)
            break;
        int ms = 250;
#if defined(Q_OS_WIN)
        Sleep(DWORD(ms));
#else
        struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
        nanosleep(&ts, NULL);
#endif
    }
    if (!connOk)
        return false;

    QByteArray uMsg(message.toUtf8());
    QDataStream ds(&socket);
    ds.writeBytes(uMsg.constData(), uMsg.size());
    bool res = socket.waitForBytesWritten(timeout);
    res &= socket.waitForReadyRead(timeout); // wait for ack
    res &= (socket.read(qstrlen(ack)) == ack);
    if (block) // block until peer disconnects
        socket.waitForDisconnected(-1);
    return res;
}

void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    // Why doesn't Qt have a blocking stream that takes care of this shait???
    while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {
        if (!socket->isValid()) // stale request
            return;
        socket->waitForReadyRead(1000);
    }
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    //qDebug() << "RCV: remaining" << remaining;
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
        //qDebug() << "RCV: got" << got << "remaining" << remaining;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    //### error check: got<0
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    // ### async this
    QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    emit messageReceived(message, socket); // ##(might take a long time to return)
}

} // namespace SharedTools
<|endoftext|>


<commit_before>#include <sstream>
#include <string>
#include <tuple>
#include <optional>
#include <functional>
#include <unordered_map>

#include "tuple_iterate.h"
#include "dataconsts.h"
#include "entity_system.h"
#include "chat/whisper_chat.h"
#include "components/client.h"

namespace {
template <typename... Args>
class Parser {
    public:
        Parser(std::stringstream&& ss) {
            size_t index = 0;
            Core::for_each(args, [&ss, &index, this](auto& data) {
                is_arg_ok[index++] = parse(ss, data);
            });
        }

        bool is_good() const {
            return std::all_of(is_arg_ok.cbegin(), is_arg_ok.cend(), [](bool i) {
                return i;
            });
        }

        bool is_arg_good(size_t index) const {
            return is_arg_ok[index];
        }

        template <size_t N>
        decltype(auto) get_arg() {
            return std::get<N>(args);
        }

    private:
        std::array<bool, sizeof...(Args)> is_arg_ok;
        std::tuple<Args...> args;

        template <typename T>
        static bool parse(std::stringstream& ss, T& h) {
            return static_cast<bool>(ss >> h);
        }

        template <typename T>
        static bool parse(std::stringstream& ss, std::optional<T>& h) {
            T tmp;
            const bool has_data = static_cast<bool>(ss >> tmp);
            if (has_data) {
                h = tmp;
            }
            return true;
        }
};

template <>
class Parser<> {
    public:
        Parser(std::stringstream&&) {}

        bool is_good() const {
            return true;
        }
};

void item(EntitySystem&, RoseCommon::Entity, Parser<int, int>) {
}

void teleport(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<int, int, int, std::optional<uint16_t>> parser) {
    if (!parser.is_good()) {
        Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage /tp <map_id> <x> <y> [client_id]");
        return;
    }
    entitySystem.teleport_entity(entity, parser.get_arg<1>() * 100, parser.get_arg<2>() * 100, parser.get_arg<0>());
}

void zuly(EntitySystem&, RoseCommon::Entity, Parser<int>) {
}
}

#define REGISTER_FUNCTION(f) [](EntitySystem& en, RoseCommon::Entity e, std::stringstream&& ss) { f(en, e, {std::move(ss)}); }

void help(EntitySystem&, RoseCommon::Entity, Parser<std::optional<std::string>>);

static const std::unordered_map<std::string, std::tuple<uint16_t, std::function<void(EntitySystem&, RoseCommon::Entity, std::stringstream&&)>, std::string>> commands = {
    {"/help", {1, REGISTER_FUNCTION(help), "Prints this help. Usage: /help [command]"}},
    //{"/item", {100, REGISTER_FUNCTION(item), "Creates an item. Usage: /item <type> <id>"}},
    //{"/zuly", {100, REGISTER_FUNCTION(zuly), "Adds zulies to your inventory (you can add a negative amount). Usage: /zuly <amount>"}},
    {"/tp", {200, REGISTER_FUNCTION(teleport), "Teleports a player or self. usage: /tp <map_id> <x> <y> [client_id]"}}
};

static const std::unordered_map<std::string, std::string> aliases = {
    {"/halp", "/help"},
    {"/teleport", "/tp"}
};

void help(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<std::optional<std::string>> parser) {
    if (!parser.is_good()) {
        Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage: /help [command]");
        return;
    }
    Chat::send_whisper(entitySystem, entity, "help (<required args> [optional args]):");
    if (!parser.get_arg<0>()) {
        for (const auto& command : commands) {
            Chat::send_whisper(entitySystem, entity, std::get<2>(command.second));
        }
    } else {
        if (const auto it = commands.find(parser.get_arg<0>().value()); it != commands.end()) {
            Chat::send_whisper(entitySystem, entity, std::get<2>(it->second));
        } else {
            Chat::send_whisper(entitySystem, entity, fmt::format("Error, no command {} found.", parser.get_arg<0>().value()));
        }
    }
}

void execute_gm(EntitySystem& entitySystem, RoseCommon::Entity entity, const std::string& message) {
    const uint16_t access_level = entitySystem.get_component<Component::Client>(entity).access_level;
    std::stringstream ss(message);
    std::string command;
    ss >> command;
    if (const auto it = aliases.find(command); it != aliases.cend()) {
        command = it->second;
    }
    if (const auto it = commands.find(command); it != commands.end() && access_level >= std::get<0>(it->second)) {
        std::get<1>(it->second)(entitySystem, entity, std::move(ss));
    } else {
        Chat::send_whisper(entitySystem, entity, "Error, no known command/not enough permissions");
    }
}
<commit_msg>Update gm_commands.cpp<commit_after>#include <sstream>
#include <string>
#include <tuple>
#include <optional>
#include <functional>
#include <unordered_map>

#include "tuple_iterate.h"
#include "dataconsts.h"
#include "entity_system.h"
#include "chat/whisper_chat.h"
#include "components/client.h"

namespace {
template <typename... Args>
class Parser {
    public:
        Parser(std::stringstream&& ss) {
            size_t index = 0;
            Core::for_each(args, [&ss, &index, this](auto& data) {
                is_arg_ok[index++] = parse(ss, data);
            });
        }

        bool is_good() const {
            return std::all_of(is_arg_ok.cbegin(), is_arg_ok.cend(), [](bool i) {
                return i;
            });
        }

        bool is_arg_good(size_t index) const {
            return is_arg_ok[index];
        }

        template <size_t N>
        decltype(auto) get_arg() {
            return std::get<N>(args);
        }

    private:
        std::array<bool, sizeof...(Args)> is_arg_ok;
        std::tuple<Args...> args;

        template <typename T>
        static bool parse(std::stringstream& ss, T& h) {
            return static_cast<bool>(ss >> h);
        }

        template <typename T>
        static bool parse(std::stringstream& ss, std::optional<T>& h) {
            T tmp;
            const bool has_data = static_cast<bool>(ss >> tmp);
            if (has_data) {
                h = tmp;
            }
            return true;
        }
};

template <>
class Parser<> {
    public:
        Parser(std::stringstream&&) {}

        bool is_good() const {
            return true;
        }
};

[[maybe_unused]] void item(EntitySystem&, RoseCommon::Entity, Parser<int, int>) {
}

void teleport(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<int, int, int, std::optional<uint16_t>> parser) {
    if (!parser.is_good()) {
        Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage /tp <map_id> <x> <y> [client_id]");
        return;
    }
    entitySystem.teleport_entity(entity, parser.get_arg<1>() * 100, parser.get_arg<2>() * 100, parser.get_arg<0>());
}

[[maybe_unused]] void zuly(EntitySystem&, RoseCommon::Entity, Parser<int>) {
}
}

#define REGISTER_FUNCTION(f) [](EntitySystem& en, RoseCommon::Entity e, std::stringstream&& ss) { f(en, e, {std::move(ss)}); }

void help(EntitySystem&, RoseCommon::Entity, Parser<std::optional<std::string>>);

static const std::unordered_map<std::string, std::tuple<uint16_t, std::function<void(EntitySystem&, RoseCommon::Entity, std::stringstream&&)>, std::string>> commands = {
    {"/help", {1, REGISTER_FUNCTION(help), "Prints this help. Usage: /help [command]"}},
    //{"/item", {100, REGISTER_FUNCTION(item), "Creates an item. Usage: /item <type> <id>"}},
    //{"/zuly", {100, REGISTER_FUNCTION(zuly), "Adds zulies to your inventory (you can add a negative amount). Usage: /zuly <amount>"}},
    {"/tp", {200, REGISTER_FUNCTION(teleport), "Teleports a player or self. usage: /tp <map_id> <x> <y> [client_id]"}}
};

static const std::unordered_map<std::string, std::string> aliases = {
    {"/halp", "/help"},
    {"/teleport", "/tp"}
};

void help(EntitySystem& entitySystem, RoseCommon::Entity entity, Parser<std::optional<std::string>> parser) {
    if (!parser.is_good()) {
        Chat::send_whisper(entitySystem, entity, "Error while parsing the command. Usage: /help [command]");
        return;
    }
    Chat::send_whisper(entitySystem, entity, "help (<required args> [optional args]):");
    if (!parser.get_arg<0>()) {
        for (const auto& command : commands) {
            Chat::send_whisper(entitySystem, entity, std::get<2>(command.second));
        }
    } else {
        if (const auto it = commands.find(parser.get_arg<0>().value()); it != commands.end()) {
            Chat::send_whisper(entitySystem, entity, std::get<2>(it->second));
        } else {
            Chat::send_whisper(entitySystem, entity, fmt::format("Error, no command {} found.", parser.get_arg<0>().value()));
        }
    }
}

void execute_gm(EntitySystem& entitySystem, RoseCommon::Entity entity, const std::string& message) {
    const uint16_t access_level = entitySystem.get_component<Component::Client>(entity).access_level;
    std::stringstream ss(message);
    std::string command;
    ss >> command;
    if (const auto it = aliases.find(command); it != aliases.cend()) {
        command = it->second;
    }
    if (const auto it = commands.find(command); it != commands.end() && access_level >= std::get<0>(it->second)) {
        std::get<1>(it->second)(entitySystem, entity, std::move(ss));
    } else {
        Chat::send_whisper(entitySystem, entity, "Error, no known command/not enough permissions");
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 1999-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "XalanDiagnosticMemoryManager.hpp"

#if !defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream>
#endif

#include <ctype.h>

#include "xercesc/util/PlatformUtils.hpp"

XALAN_CPP_NAMESPACE_BEGIN

XalanDiagnosticMemoryManager::XalanDiagnosticMemoryManager(
            MemoryManager&  theMemoryManager,
            bool            fAssertErrors,
            StreamType*     theStream) :
    m_memoryManager(theMemoryManager),
    m_assertErrors(fAssertErrors),
    m_locked(false),
    m_sequence(0),
    m_highWaterMark(0),
    m_currentAllocated(0),
    m_allocations(theMemoryManager),
    m_stream(theStream)
{
}

XalanDiagnosticMemoryManager::~XalanDiagnosticMemoryManager()
{
    if (m_allocations.size() > 0 && m_stream != 0)
    {
        *m_stream << "Detected memory leaks. "
                  << m_allocations.size()
                  << " blocks are still allocated.\n";
    }
}

void*
XalanDiagnosticMemoryManager::allocate(size_type  size)
{
    void*   theResult = 0;

    if (m_locked == true)
    {
        if (m_stream != 0)
        {
            *m_stream << "Attempt to allocate "
                      << size
                      << " bytes from locked instance "
                      << this
                      << ".\n";

            dumpStatistics(m_stream);
        }

        throw LockException();
    }
    else
    {
        theResult =
            m_memoryManager.allocate(size);
        assert(theResult != 0);

        assert(m_allocations.find(theResult) == m_allocations.end());

        m_currentAllocated += size;

        if (m_currentAllocated > m_highWaterMark)
        {
            m_highWaterMark = m_currentAllocated;
        }

        m_allocations.insert(MapType::value_type(theResult, Data(size, m_sequence++)));
    }

    return theResult;
}

void
XalanDiagnosticMemoryManager::deallocate(void*    pointer)
{
    if (m_locked == true)
    {
        if (m_stream != 0)
        {
            *m_stream << "Attempt to deallocate address "
                      << pointer
                      << " with locked instance "
                      << this
                      << ".\n";
        }

        throw LockException();
    }
    else
    {
        if (pointer != 0)
        {
            MapType::iterator   i =
                m_allocations.find(pointer);

            if (i != m_allocations.end())
            {
                m_memoryManager.deallocate(pointer);

                assert(m_currentAllocated >= i->second.m_size);

                m_currentAllocated -= i->second.m_size;

                m_allocations.erase(i);
            }
            else
            {
                if (m_stream != 0)
                {
                    *m_stream << "Attempt to free unallocated address "
                              << pointer
                              << " with instance "
                              << this
                              << ".\n";
                }

                assert(!m_assertErrors);
            }
        }
    }
}

void
XalanDiagnosticMemoryManager::dumpStatistics(
            StreamType*     theStream,
            size_type       theBytesToDump)
{
    StreamType* const   diagStream = theStream != 0 ? theStream : m_stream;

    if (diagStream != 0)
    {
        *diagStream << "Total number of allocations: "
                    << m_sequence
                    << ".\n"
                    << "Total current allocations: "
                    << m_allocations.size()
                    << ".\n"
                    << "Total bytes currently allocated: "
                    << m_currentAllocated
                    << ".\n"
                    << "Peak bytes allocated: "
                    << m_highWaterMark
                    << ".\n";

        for(const_iterator i = m_allocations.begin();
                i != m_allocations.end();
                    ++i)
        {
            const void* const   thePointer = i->first;
            const Data&         theData = i->second;

            XALAN_USING_STD(dec);

            *diagStream << "Block at address "
                        << thePointer
                        << " with sequence "
                        << dec
                        << theData.m_sequence
                        << " is "
                        << theData.m_size
                        << " bytes long.\n";

            XALAN_USING_XERCES(XMLPlatformUtils);

	        const size_type     theHeaderSize =
                XMLPlatformUtils::alignPointerForNewBlockAllocation(sizeof(MemoryManager*));

            const char* const   theChars =
                reinterpret_cast<const char*>(thePointer) +
                    theHeaderSize;

            const unsigned char* const  theUChars =
                reinterpret_cast<const unsigned char*>(theChars);

            if (theBytesToDump != 0)
            {
                XALAN_USING_STD(hex);

                const size_type     theCount =
                    theBytesToDump > theData.m_size ?
                        theData.m_size :
                        theBytesToDump;

                {
                    *diagStream << "(";

                    for (size_t j = 0; j < theCount; ++j)
                    {
                        const char  ch = isprint(theChars[j]) ?
                                            theChars[j] :
                                            ' ';

                        *diagStream << ch;
                    }

                    *diagStream << ")  ";
                }

                if (theCount < theBytesToDump)
                {
                    for (size_t j = theCount; j < theBytesToDump; ++j)
                    {
                        *diagStream << ' ';
                    }
                }

                {
                    *diagStream << hex;

                    for (size_t j = 0; j < theCount; ++j)
                    {
                        *diagStream << unsigned(theUChars[j])
                                    << " ";
                    }
                }

                *diagStream << "\n";
            }
        }
    }
}

XALAN_CPP_NAMESPACE_END
<commit_msg>Don't dump statistics when reporting an allocation error with a locked instance.<commit_after>/*
 * Copyright 1999-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "XalanDiagnosticMemoryManager.hpp"

#if !defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream>
#endif

#include <ctype.h>

#include "xercesc/util/PlatformUtils.hpp"

XALAN_CPP_NAMESPACE_BEGIN

XalanDiagnosticMemoryManager::XalanDiagnosticMemoryManager(
            MemoryManager&  theMemoryManager,
            bool            fAssertErrors,
            StreamType*     theStream) :
    m_memoryManager(theMemoryManager),
    m_assertErrors(fAssertErrors),
    m_locked(false),
    m_sequence(0),
    m_highWaterMark(0),
    m_currentAllocated(0),
    m_allocations(theMemoryManager),
    m_stream(theStream)
{
}

XalanDiagnosticMemoryManager::~XalanDiagnosticMemoryManager()
{
    if (m_allocations.size() > 0 && m_stream != 0)
    {
        *m_stream << "Detected memory leaks. "
                  << m_allocations.size()
                  << " blocks are still allocated.\n";
    }
}

void*
XalanDiagnosticMemoryManager::allocate(size_type  size)
{
    void*   theResult = 0;

    if (m_locked == true)
    {
        if (m_stream != 0)
        {
            *m_stream << "Attempt to allocate "
                      << size
                      << " bytes from locked instance "
                      << this
                      << ".\n";
        }

        throw LockException();
    }
    else
    {
        theResult =
            m_memoryManager.allocate(size);
        assert(theResult != 0);

        assert(m_allocations.find(theResult) == m_allocations.end());

        m_currentAllocated += size;

        if (m_currentAllocated > m_highWaterMark)
        {
            m_highWaterMark = m_currentAllocated;
        }

        m_allocations.insert(MapType::value_type(theResult, Data(size, m_sequence++)));
    }

    return theResult;
}

void
XalanDiagnosticMemoryManager::deallocate(void*    pointer)
{
    if (m_locked == true)
    {
        if (m_stream != 0)
        {
            *m_stream << "Attempt to deallocate address "
                      << pointer
                      << " with locked instance "
                      << this
                      << ".\n";
        }

        throw LockException();
    }
    else
    {
        if (pointer != 0)
        {
            MapType::iterator   i =
                m_allocations.find(pointer);

            if (i != m_allocations.end())
            {
                m_memoryManager.deallocate(pointer);

                assert(m_currentAllocated >= i->second.m_size);

                m_currentAllocated -= i->second.m_size;

                m_allocations.erase(i);
            }
            else
            {
                if (m_stream != 0)
                {
                    *m_stream << "Attempt to free unallocated address "
                              << pointer
                              << " with instance "
                              << this
                              << ".\n";
                }

                assert(!m_assertErrors);
            }
        }
    }
}

void
XalanDiagnosticMemoryManager::dumpStatistics(
            StreamType*     theStream,
            size_type       theBytesToDump)
{
    StreamType* const   diagStream = theStream != 0 ? theStream : m_stream;

    if (diagStream != 0)
    {
        *diagStream << "Total number of allocations: "
                    << m_sequence
                    << ".\n"
                    << "Total current allocations: "
                    << m_allocations.size()
                    << ".\n"
                    << "Total bytes currently allocated: "
                    << m_currentAllocated
                    << ".\n"
                    << "Peak bytes allocated: "
                    << m_highWaterMark
                    << ".\n";

        for(const_iterator i = m_allocations.begin();
                i != m_allocations.end();
                    ++i)
        {
            const void* const   thePointer = i->first;
            const Data&         theData = i->second;

            XALAN_USING_STD(dec);

            *diagStream << "Block at address "
                        << thePointer
                        << " with sequence "
                        << dec
                        << theData.m_sequence
                        << " is "
                        << theData.m_size
                        << " bytes long.\n";

            XALAN_USING_XERCES(XMLPlatformUtils);

            const size_type     theHeaderSize =
                XMLPlatformUtils::alignPointerForNewBlockAllocation(sizeof(MemoryManager*));

            const char* const   theChars =
                reinterpret_cast<const char*>(thePointer) +
                    theHeaderSize;

            const unsigned char* const  theUChars =
                reinterpret_cast<const unsigned char*>(theChars);

            if (theBytesToDump != 0)
            {
                XALAN_USING_STD(hex);

                const size_type     theCount =
                    theBytesToDump > theData.m_size ?
                        theData.m_size :
                        theBytesToDump;

                {
                    *diagStream << "(";

                    for (size_t j = 0; j < theCount; ++j)
                    {
                        const char  ch = isprint(theChars[j]) ?
                                            theChars[j] :
                                            ' ';

                        *diagStream << ch;
                    }

                    *diagStream << ")  ";
                }

                if (theCount < theBytesToDump)
                {
                    for (size_t j = theCount; j < theBytesToDump; ++j)
                    {
                        *diagStream << ' ';
                    }
                }

                {
                    *diagStream << hex;

                    for (size_t j = 0; j < theCount; ++j)
                    {
                        *diagStream << unsigned(theUChars[j])
                                    << " ";
                    }
                }

                *diagStream << "\n";
            }
        }
    }
}

XALAN_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include <QAudioOutput>
#include <QAudioDeviceInfo>
#include <QAudioInput>

class Window2 : public QWidget
{
    Q_OBJECT

public slots:
//![0]
    void stateChanged(QAudio::State newState)
    {
        switch(newState) {
            case QAudio::StopState:
            if (input->error() != QAudio::NoError) {
                // Error handling
            } else {

            }
            break;
//![0]
        default:
            ;
        }
    }

private:
    QAudioInput *input;

};

class Window : public QWidget
{
    Q_OBJECT

public:
    Window()
    {
        output = new QAudioOutput;
        connect(output, SIGNAL(stateChanged(QAudio::State)),
            this, SLOT(stateChanged(QAudio::State)));
    }

private:
    void setupFormat()
    {
//![1]
        QAudioFormat format;
        format.setFrequency(44100);
//![1]
        format.setChannels(2);
        format.setSampleSize(16);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat::LittleEndian);
//![2]
        format.setSampleType(QAudioFormat::SignedInt);

        QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());

        if (!info.isFormatSupported(format))
            format = info.nearestFormat(format);
//![2]
    }

public slots:
//![3]
    void stateChanged(QAudio::State newState)
    {
        switch (newState) {
            case QAudio::StopState:
                if (output->error() != QAudio::NoError) {
                    // Do your error handlin
                } else {
                    // Normal stop
                }
                break;
//![3]

            // Handle
            case QAudio::ActiveState:
                // Handle active state...
                break;
            break;
        default:
            ;
        }
    }

private:
    QAudioOutput *output;
};

int main(int argv, char **args)
{
    QApplication app(argv, args);

    Window window;
    window.show();

    return app.exec();
}

#include "main.moc"

<commit_msg>Doc: Fixed comments in a code snippet.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include <QAudioOutput>
#include <QAudioDeviceInfo>
#include <QAudioInput>

class Window2 : public QWidget
{
    Q_OBJECT

public slots:
//![0]
    void stateChanged(QAudio::State newState)
    {
        switch(newState) {
            case QAudio::StopState:
            if (input->error() != QAudio::NoError) {
                // Error handling
            } else {

            }
            break;
//![0]
        default:
            ;
        }
    }

private:
    QAudioInput *input;

};

class Window : public QWidget
{
    Q_OBJECT

public:
    Window()
    {
        output = new QAudioOutput;
        connect(output, SIGNAL(stateChanged(QAudio::State)),
            this, SLOT(stateChanged(QAudio::State)));
    }

private:
    void setupFormat()
    {
//![1]
        QAudioFormat format;
        format.setFrequency(44100);
//![1]
        format.setChannels(2);
        format.setSampleSize(16);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat::LittleEndian);
//![2]
        format.setSampleType(QAudioFormat::SignedInt);

        QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());

        if (!info.isFormatSupported(format))
            format = info.nearestFormat(format);
//![2]
    }

public slots:
//![3]
    void stateChanged(QAudio::State newState)
    {
        switch (newState) {
            case QAudio::StopState:
                if (output->error() != QAudio::NoError) {
                    // Perform error handling
                } else {
                    // Normal stop
                }
                break;
//![3]

            // Handle
            case QAudio::ActiveState:
                // Handle active state...
                break;
            break;
        default:
            ;
        }
    }

private:
    QAudioOutput *output;
};

int main(int argv, char **args)
{
    QApplication app(argv, args);

    Window window;
    window.show();

    return app.exec();
}

#include "main.moc"

<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP

#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/mat/prob/bernoulli_logit_glm_lpmf.hpp>

namespace stan {
namespace math {

/**
 * @deprecated use bernoulli_logit_glm_lpmf
 */
template <bool propto, typename T_n, typename T_x, typename T_alpha,
          typename T_beta>
typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
    const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
  return bernoulli_logit_glm_lpmf<propto, T_n, T_x, T_alpha, T_beta>(n, x, alpha,
                                                                    beta);
}

/**
 * @deprecated use bernoulli_logit_glm_lpmf
 */
template <typename T_n, typename T_x, typename T_alpha, typename T_beta>
inline typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
    const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
  return bernoulli_logit_glm_lpmf<false>(n, x, alpha, beta);
}
}  // namespace math
}  // namespace stan
#endif
<commit_msg>satisfied cpplint again<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_BERNOULLI_LOGIT_GLM_LOG_HPP

#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/mat/prob/bernoulli_logit_glm_lpmf.hpp>

namespace stan {
namespace math {

/**
 * @deprecated use bernoulli_logit_glm_lpmf
 */
template <bool propto, typename T_n, typename T_x, typename T_alpha,
          typename T_beta>
typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
    const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
  return bernoulli_logit_glm_lpmf<propto, T_n, T_x, T_alpha, T_beta>(n, x,
                                                                     alpha,
                                                                     beta);
}

/**
 * @deprecated use bernoulli_logit_glm_lpmf
 */
template <typename T_n, typename T_x, typename T_alpha, typename T_beta>
inline typename return_type<T_x, T_alpha, T_beta>::type bernoulli_logit_glm_log(
    const T_n &n, const T_x &x, const T_alpha &alpha, const T_beta &beta) {
  return bernoulli_logit_glm_lpmf<false>(n, x, alpha, beta);
}
}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: overlayanimatedbitmapex.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 13:06:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
#define _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX

#ifndef _SDR_OVERLAY_OVERLAYOBJECT_HXX
#include <svx/sdr/overlay/overlayobject.hxx>
#endif

#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace overlay
    {
        class OverlayAnimatedBitmapEx : public OverlayObjectWithBasePosition
        {
        protected:
            // the Bitmaps
            BitmapEx                                maBitmapEx1;
            BitmapEx                                maBitmapEx2;

            // position of the basePosition inside the Bitmaps, in pixels
            sal_uInt16                              mnCenterX1;
            sal_uInt16                              mnCenterY1;
            sal_uInt16                              mnCenterX2;
            sal_uInt16                              mnCenterY2;

            // bitfield
            // Flag to remember which state to draw. Inited with sal_False (0)
            unsigned                                mbOverlayState : 1;

            // Draw geometry
            virtual void drawGeometry(OutputDevice& rOutputDevice);

            // Create the BaseRange. This method needs to calculate maBaseRange.
            virtual void createBaseRange(OutputDevice& rOutputDevice);

        public:
            OverlayAnimatedBitmapEx(
                const basegfx::B2DPoint& rBasePos,
                const BitmapEx& rBitmapEx1, const BitmapEx& rBitmapEx2,
                sal_uInt16 nCenX1 = 0, sal_uInt16 nCenY1 = 0,
                sal_uInt16 nCenX2 = 0, sal_uInt16 nCenY2 = 0);
            virtual ~OverlayAnimatedBitmapEx();

            const BitmapEx& getBitmapEx1() const { return maBitmapEx1; }
            const BitmapEx& getBitmapEx2() const { return maBitmapEx2; }
            void setBitmapEx1(const BitmapEx& rNew);
            void setBitmapEx2(const BitmapEx& rNew);

            sal_uInt16 getCenterX1() const { return mnCenterX1; }
            sal_uInt16 getCenterY1() const { return mnCenterY1; }
            sal_uInt16 getCenterX2() const { return mnCenterX2; }
            sal_uInt16 getCenterY2() const { return mnCenterY2; }
            void setCenterXY1(sal_uInt16 nNewX, sal_uInt16 nNewY);
            void setCenterXY2(sal_uInt16 nNewX, sal_uInt16 nNewY);

            // execute event from base class ::sdr::animation::Event. Default
            // implementation does nothing and does not create a new event.
            virtual void Trigger(sal_uInt32 nTime);

            // Zoom has changed. If the objects logical size
            // depends on the MapMode of the used OutputDevice, use this call
            // to invalidate the range in logical coordinates.
            virtual void zoomHasChanged();
        };
    } // end of namespace overlay
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX

// eof
<commit_msg>INTEGRATION: CWS aw051 (1.2.222); FILE MERGED 2007/05/03 14:16:50 aw 1.2.222.1: #i53286# using GetCursorBlinkRate now<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: overlayanimatedbitmapex.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-18 10:51:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX
#define _SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX

#ifndef _SDR_OVERLAY_OVERLAYOBJECT_HXX
#include <svx/sdr/overlay/overlayobject.hxx>
#endif

#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////

namespace sdr
{
    namespace overlay
    {
        class OverlayAnimatedBitmapEx : public OverlayObjectWithBasePosition
        {
        protected:
            // the Bitmaps
            BitmapEx                                maBitmapEx1;
            BitmapEx                                maBitmapEx2;

            // position of the basePosition inside the Bitmaps, in pixels
            sal_uInt16                              mnCenterX1;
            sal_uInt16                              mnCenterY1;
            sal_uInt16                              mnCenterX2;
            sal_uInt16                              mnCenterY2;

            // #i53216# added CursorBlinkTime (in ms)
            sal_uInt32                              mnBlinkTime;

            // bitfield
            // Flag to remember which state to draw. Inited with sal_False (0)
            unsigned                                mbOverlayState : 1;

            // Draw geometry
            virtual void drawGeometry(OutputDevice& rOutputDevice);

            // Create the BaseRange. This method needs to calculate maBaseRange.
            virtual void createBaseRange(OutputDevice& rOutputDevice);

            // #i53216# check blink time value range (currently 25 < mnBlinkTime < 10000)
            void impCheckBlinkTimeValueRange();

        public:
            OverlayAnimatedBitmapEx(
                const basegfx::B2DPoint& rBasePos,
                const BitmapEx& rBitmapEx1,
                const BitmapEx& rBitmapEx2,
                sal_uInt32 nBlinkTime = 500,
                sal_uInt16 nCenX1 = 0,
                sal_uInt16 nCenY1 = 0,
                sal_uInt16 nCenX2 = 0,
                sal_uInt16 nCenY2 = 0);
            virtual ~OverlayAnimatedBitmapEx();

            const BitmapEx& getBitmapEx1() const { return maBitmapEx1; }
            const BitmapEx& getBitmapEx2() const { return maBitmapEx2; }
            void setBitmapEx1(const BitmapEx& rNew);
            void setBitmapEx2(const BitmapEx& rNew);

            sal_uInt16 getCenterX1() const { return mnCenterX1; }
            sal_uInt16 getCenterY1() const { return mnCenterY1; }
            sal_uInt16 getCenterX2() const { return mnCenterX2; }
            sal_uInt16 getCenterY2() const { return mnCenterY2; }
            void setCenterXY1(sal_uInt16 nNewX, sal_uInt16 nNewY);
            void setCenterXY2(sal_uInt16 nNewX, sal_uInt16 nNewY);

            // #i53216# added CursorBlinkTime (in ms)
            sal_uInt32 getBlinkTime() const { return mnBlinkTime; }
            void setBlinkTime(sal_uInt32 nNew);

            // execute event from base class ::sdr::animation::Event. Default
            // implementation does nothing and does not create a new event.
            virtual void Trigger(sal_uInt32 nTime);

            // Zoom has changed. If the objects logical size
            // depends on the MapMode of the used OutputDevice, use this call
            // to invalidate the range in logical coordinates.
            virtual void zoomHasChanged();
        };
    } // end of namespace overlay
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////

#endif //_SDR_OVERLAY_OVERLAYANIMATEDBITMAPEX_HXX

// eof
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: viewcontactofsdrmediaobj.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-22 15:14:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx>
#include "svdomedia.hxx"

#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx>
#endif

namespace sdr { namespace contact {

// ----------------------------
// - ViewContactOfSdrMediaObj -
// ----------------------------

ViewContactOfSdrMediaObj::ViewContactOfSdrMediaObj( SdrMediaObj& rMediaObj ) :
    ViewContactOfSdrObj( rMediaObj )
{
}

// ------------------------------------------------------------------------------

ViewContactOfSdrMediaObj::~ViewContactOfSdrMediaObj()
{
}

// ------------------------------------------------------------------------------

sal_Bool ViewContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC)
{
    return ViewContactOfSdrObj::PaintObject( rDisplayInfo, rPaintRectangle, rAssociatedVOC );
}

// ------------------------------------------------------------------------------

ViewObjectContact& ViewContactOfSdrMediaObj::CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact)
{
    return *( new ViewObjectContactOfSdrMediaObj( rObjectContact, *this, static_cast< SdrMediaObj& >( GetSdrObject() ).getMediaProperties() ) );
}

// ------------------------------------------------------------------------------

bool ViewContactOfSdrMediaObj::hasPreferredSize() const
{
    // #i71805# Since we may have a whole bunch of VOCs here, make a loop
    // return true if all have their preferred size
    bool bRetval(true);

    for(sal_uInt32 a(0L); bRetval && a < maVOCList.Count(); a++)
    {
        if(!static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->hasPreferredSize())
        {
            bRetval = false;
        }
    }

    return bRetval;
}

// ------------------------------------------------------------------------------

Size ViewContactOfSdrMediaObj::getPreferredSize() const
{
    // #i71805# Since we may have a whole bunch of VOCs here, make a loop
    // return first useful size -> the size from the first which is visualized as a window
    for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
    {
        Size aSize(static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->getPreferredSize());

        if(0 != aSize.getWidth() || 0 != aSize.getHeight())
        {
            return aSize;
        }
    }

    return Size();
}

// ------------------------------------------------------------------------------

void ViewContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const
{
    // #i71805# Since we may have a whole bunch of VOCs here, make a loop
    for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
    {
        static_cast< ViewObjectContactOfSdrMediaObj* >(maVOCList.GetObject(a))->updateMediaItem(rItem);
    }
}

// ------------------------------------------------------------------------------

void ViewContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )
{
    for( sal_uInt32 n(0L); n < maVOCList.Count(); n++ )
    {
        static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( n ) )->executeMediaItem( rItem );
    }
}

// ------------------------------------------------------------------------------

void ViewContactOfSdrMediaObj::mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState )
{
    static_cast< SdrMediaObj& >( GetSdrObject() ).mediaPropertiesChanged( rNewState );
}

// ------------------------------------------------------------------------------
// #i72701#
sal_Bool ViewContactOfSdrMediaObj::ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC)
{
    // set pos/size of associated media window
    const ViewObjectContactOfSdrMediaObj& rVOC(dynamic_cast< const ViewObjectContactOfSdrMediaObj& >(rAssociatedVOC));
    rVOC.checkMediaWindowPosition(rDisplayInfo);

    // call parent
    return ViewContactOfSdrObj::ShouldPaintObject(rDisplayInfo, rAssociatedVOC);
}

// ------------------------------------------------------------------------------

}} // end of namespace sdr::contact

// eof
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.130); FILE MERGED 2007/06/04 13:27:16 vg 1.9.130.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: viewcontactofsdrmediaobj.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 18:45:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx>
#include <svx/svdomedia.hxx>

#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTOFSDRMEDIAOBJ_HXX
#include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx>
#endif

namespace sdr { namespace contact {

// ----------------------------
// - ViewContactOfSdrMediaObj -
// ----------------------------

ViewContactOfSdrMediaObj::ViewContactOfSdrMediaObj( SdrMediaObj& rMediaObj ) :
    ViewContactOfSdrObj( rMediaObj )
{
}

// ------------------------------------------------------------------------------

ViewContactOfSdrMediaObj::~ViewContactOfSdrMediaObj()
{
}

// ------------------------------------------------------------------------------

sal_Bool ViewContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC)
{
    return ViewContactOfSdrObj::PaintObject( rDisplayInfo, rPaintRectangle, rAssociatedVOC );
}

// ------------------------------------------------------------------------------

ViewObjectContact& ViewContactOfSdrMediaObj::CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact)
{
    return *( new ViewObjectContactOfSdrMediaObj( rObjectContact, *this, static_cast< SdrMediaObj& >( GetSdrObject() ).getMediaProperties() ) );
}

// ------------------------------------------------------------------------------

bool ViewContactOfSdrMediaObj::hasPreferredSize() const
{
    // #i71805# Since we may have a whole bunch of VOCs here, make a loop
    // return true if all have their preferred size
    bool bRetval(true);

    for(sal_uInt32 a(0L); bRetval && a < maVOCList.Count(); a++)
    {
        if(!static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->hasPreferredSize())
        {
            bRetval = false;
        }
    }

    return bRetval;
}

// ------------------------------------------------------------------------------

Size ViewContactOfSdrMediaObj::getPreferredSize() const
{
    // #i71805# Since we may have a whole bunch of VOCs here, make a loop
    // return first useful size -> the size from the first which is visualized as a window
    for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
    {
        Size aSize(static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( 0 ) )->getPreferredSize());

        if(0 != aSize.getWidth() || 0 != aSize.getHeight())
        {
            return aSize;
        }
    }

    return Size();
}

// ------------------------------------------------------------------------------

void ViewContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const
{
    // #i71805# Since we may have a whole bunch of VOCs here, make a loop
    for(sal_uInt32 a(0L); a < maVOCList.Count(); a++)
    {
        static_cast< ViewObjectContactOfSdrMediaObj* >(maVOCList.GetObject(a))->updateMediaItem(rItem);
    }
}

// ------------------------------------------------------------------------------

void ViewContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )
{
    for( sal_uInt32 n(0L); n < maVOCList.Count(); n++ )
    {
        static_cast< ViewObjectContactOfSdrMediaObj* >( maVOCList.GetObject( n ) )->executeMediaItem( rItem );
    }
}

// ------------------------------------------------------------------------------

void ViewContactOfSdrMediaObj::mediaPropertiesChanged( const ::avmedia::MediaItem& rNewState )
{
    static_cast< SdrMediaObj& >( GetSdrObject() ).mediaPropertiesChanged( rNewState );
}

// ------------------------------------------------------------------------------
// #i72701#
sal_Bool ViewContactOfSdrMediaObj::ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC)
{
    // set pos/size of associated media window
    const ViewObjectContactOfSdrMediaObj& rVOC(dynamic_cast< const ViewObjectContactOfSdrMediaObj& >(rAssociatedVOC));
    rVOC.checkMediaWindowPosition(rDisplayInfo);

    // call parent
    return ViewContactOfSdrObj::ShouldPaintObject(rDisplayInfo, rAssociatedVOC);
}

// ------------------------------------------------------------------------------

}} // end of namespace sdr::contact

// eof
<|endoftext|>