<commit_before>/*
 *            Copyright 2016 The MUSCET Development Team
 *
 *      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 <votca/xtp/gyration.h>
#include <boost/format.hpp>
#include <votca/tools/elements.h>

using namespace votca::tools;

namespace votca { namespace xtp {

void Density2Gyration::Initialize( tools::Property& options) {
    string key = Identify();

    std::string statestring=options.ifExistsReturnElseThrowRuntimeError<string>(key + ".state");
    _state.FromString(statestring);
    _dostateonly = options.ifExistsReturnElseReturnDefault<bool>(key + ".difference_to_groundstate",false);
    _gridsize = options.ifExistsReturnElseReturnDefault<string>(key+".gridsize","medium");
    _openmp_threads = options.ifExistsReturnElseReturnDefault<int>(key + ".openmp",1);

    // get the path to the shared folders with xml files
    char *votca_share = getenv("VOTCASHARE");
    if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files.");
    }

    void Density2Gyration::AnalyzeDensity(const Orbitals & orbitals) {
      int threads = 1;
#ifdef _OPENMP
      if (_openmp_threads > 0) omp_set_num_threads(_openmp_threads);
      threads = omp_get_max_threads();
#endif
      XTP_LOG(logDEBUG, *_log) << "===== Running on " << threads << " threads ===== " << flush;

     const QMMolecule& Atomlist = orbitals.QMAtoms();
      Eigen::MatrixXd DMAT_tot;
      BasisSet bs;
      bs.LoadBasisSet(orbitals.getDFTbasis());
      AOBasis basis;
      basis.AOBasisFill(bs, Atomlist);
      AnalyzeGeometry(Atomlist);
      std::vector<Eigen::MatrixXd > DMAT;

      // setup numerical integration grid
      NumericalIntegration numway;
      numway.GridSetup(_gridsize, Atomlist, basis);

      if (!_dostateonly) {
        Eigen::MatrixXd DMATGS = orbitals.DensityMatrixFull(_state);
        Gyrationtensor gyro = numway.IntegrateGyrationTensor(DMAT_tot);
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;
        es.computeDirect(gyro.gyration);
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Converting to Eigenframe " << flush;
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Reporting " << flush;
        ReportAnalysis(_state.ToLongString(), gyro,es);

      } else{
        // hole density first
        std::vector<Eigen::MatrixXd > DMAT=orbitals.DensityMatrixExcitedState(_state);
        Gyrationtensor gyro_hole = numway.IntegrateGyrationTensor(DMAT[0]);
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_h;
        es_h.computeDirect(gyro_hole.gyration);
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Converting to Eigenframe " << flush;
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Reporting " << flush;
        ReportAnalysis("hole", gyro_hole,es_h);

        // electron density
        Gyrationtensor gyro_electron = numway.IntegrateGyrationTensor(DMAT[1]);
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_e;
        es_e.computeDirect(gyro_electron.gyration);
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Converting to Eigenframe " << flush;
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Reporting " << flush;
        ReportAnalysis("electron", gyro_electron,es_e);
      }
      return;
    }

    void Density2Gyration::AnalyzeGeometry(const QMMolecule& atoms){

        tools::Elements elements;
        double mass=0.0;
        Eigen::Vector3d centroid = Eigen::Vector3d::Zero();
        Eigen::Matrix3d gyration = Eigen::Matrix3d::Zero();
        for (const QMAtom& atom:atoms){
            double m = elements.getMass(atom.getElement());
            const Eigen::Vector3d  & pos =atom.getPos();
            mass+= m;
            centroid+=m*pos;
            gyration+=m*pos*pos.transpose();
        }
        centroid/=mass;
        gyration/=mass;
        gyration-=centroid*centroid.transpose();
        Gyrationtensor gyro;
        gyro.mass=mass;
        gyro.centroid=centroid;
        gyro.gyration=gyration;
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;
        es.computeDirect(gyro.gyration);
        ReportAnalysis( "geometry", gyro,es );
    }

    void Density2Gyration::ReportAnalysis(string label,const Gyrationtensor& gyro, const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>& es){

            XTP_LOG(logINFO, *_log) << "---------------- " << label << " ----------------" << flush;
            XTP_LOG(logINFO, *_log) << (boost::format("  Norm               = %1$9.4f ") % (gyro.mass) ) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Centroid x         = %1$9.4f Ang") % (gyro.centroid.x()*tools::conv::bohr2ang) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Centroid y         = %1$9.4f Ang") % (gyro.centroid.y()*tools::conv::bohr2ang) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Centroid y         = %1$9.4f Ang") % (gyro.centroid.z()*tools::conv::bohr2ang) ) << flush;

            double RA2 = tools::conv::bohr2ang  *tools::conv::bohr2ang;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor xx = %1$9.4f Ang^2") % (gyro.gyration(0,0)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor xy = %1$9.4f Ang^2") % (gyro.gyration(0,1)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor xz = %1$9.4f Ang^2") % (gyro.gyration(0,2)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor yy = %1$9.4f Ang^2") % (gyro.gyration(1,1)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor yz = %1$9.4f Ang^2") % (gyro.gyration(1,2)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor zz = %1$9.4f Ang^2") % (gyro.gyration(2,2)*RA2) ) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor D1 = %1$9.4f Ang^2") % (es.eigenvalues()[0]*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor D2 = %1$9.4f Ang^2") % (es.eigenvalues()[1]*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor D3 = %1$9.4f Ang^2") % (es.eigenvalues()[2]*RA2) ) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Radius of Gyration = %1$9.4f Ang") % (std::sqrt(es.eigenvalues().sum())*tools::conv::bohr2ang )) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 1 1 = %1$9.4f ") % es.eigenvectors().col(0).x() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 1 2 = %1$9.4f ") % es.eigenvectors().col(0).y() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 1 3 = %1$9.4f ") % es.eigenvectors().col(0).z() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 2 1 = %1$9.4f ") % es.eigenvectors().col(1).x() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 2 2 = %1$9.4f ") % es.eigenvectors().col(1).y() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 2 3 = %1$9.4f ") % es.eigenvectors().col(1).z() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 3 1 = %1$9.4f ") % es.eigenvectors().col(2).x() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 3 2 = %1$9.4f ") % es.eigenvectors().col(2).y() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 3 3 = %1$9.4f ") % es.eigenvectors().col(2).z() ) << flush;
            return;
    }

}}

<commit_msg>Added using namespace std to gyration.cc<commit_after>/*
 *            Copyright 2016 The MUSCET Development Team
 *
 *      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 <votca/xtp/gyration.h>
#include <boost/format.hpp>
#include <votca/tools/elements.h>

using namespace std;
using namespace votca::tools;

namespace votca { namespace xtp {

void Density2Gyration::Initialize( tools::Property& options) {
    string key = Identify();

    std::string statestring=options.ifExistsReturnElseThrowRuntimeError<string>(key + ".state");
    _state.FromString(statestring);
    _dostateonly = options.ifExistsReturnElseReturnDefault<bool>(key + ".difference_to_groundstate",false);
    _gridsize = options.ifExistsReturnElseReturnDefault<string>(key+".gridsize","medium");
    _openmp_threads = options.ifExistsReturnElseReturnDefault<int>(key + ".openmp",1);

    // get the path to the shared folders with xml files
    char *votca_share = getenv("VOTCASHARE");
    if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files.");
    }

    void Density2Gyration::AnalyzeDensity(const Orbitals & orbitals) {
      int threads = 1;
#ifdef _OPENMP
      if (_openmp_threads > 0) omp_set_num_threads(_openmp_threads);
      threads = omp_get_max_threads();
#endif
      XTP_LOG(logDEBUG, *_log) << "===== Running on " << threads << " threads ===== " << flush;

     const QMMolecule& Atomlist = orbitals.QMAtoms();
      Eigen::MatrixXd DMAT_tot;
      BasisSet bs;
      bs.LoadBasisSet(orbitals.getDFTbasis());
      AOBasis basis;
      basis.AOBasisFill(bs, Atomlist);
      AnalyzeGeometry(Atomlist);
      std::vector<Eigen::MatrixXd > DMAT;

      // setup numerical integration grid
      NumericalIntegration numway;
      numway.GridSetup(_gridsize, Atomlist, basis);

      if (!_dostateonly) {
        Eigen::MatrixXd DMATGS = orbitals.DensityMatrixFull(_state);
        Gyrationtensor gyro = numway.IntegrateGyrationTensor(DMAT_tot);
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;
        es.computeDirect(gyro.gyration);
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Converting to Eigenframe " << flush;
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Reporting " << flush;
        ReportAnalysis(_state.ToLongString(), gyro,es);

      } else{
        // hole density first
        std::vector<Eigen::MatrixXd > DMAT=orbitals.DensityMatrixExcitedState(_state);
        Gyrationtensor gyro_hole = numway.IntegrateGyrationTensor(DMAT[0]);
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_h;
        es_h.computeDirect(gyro_hole.gyration);
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Converting to Eigenframe " << flush;
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Reporting " << flush;
        ReportAnalysis("hole", gyro_hole,es_h);

        // electron density
        Gyrationtensor gyro_electron = numway.IntegrateGyrationTensor(DMAT[1]);
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_e;
        es_e.computeDirect(gyro_electron.gyration);
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Converting to Eigenframe " << flush;
        XTP_LOG(logDEBUG, *_log) << TimeStamp() << " Reporting " << flush;
        ReportAnalysis("electron", gyro_electron,es_e);
      }
      return;
    }

    void Density2Gyration::AnalyzeGeometry(const QMMolecule& atoms){

        tools::Elements elements;
        double mass=0.0;
        Eigen::Vector3d centroid = Eigen::Vector3d::Zero();
        Eigen::Matrix3d gyration = Eigen::Matrix3d::Zero();
        for (const QMAtom& atom:atoms){
            double m = elements.getMass(atom.getElement());
            const Eigen::Vector3d  & pos =atom.getPos();
            mass+= m;
            centroid+=m*pos;
            gyration+=m*pos*pos.transpose();
        }
        centroid/=mass;
        gyration/=mass;
        gyration-=centroid*centroid.transpose();
        Gyrationtensor gyro;
        gyro.mass=mass;
        gyro.centroid=centroid;
        gyro.gyration=gyration;
        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;
        es.computeDirect(gyro.gyration);
        ReportAnalysis( "geometry", gyro,es );
    }

    void Density2Gyration::ReportAnalysis(string label,const Gyrationtensor& gyro, const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>& es){

            XTP_LOG(logINFO, *_log) << "---------------- " << label << " ----------------" << flush;
            XTP_LOG(logINFO, *_log) << (boost::format("  Norm               = %1$9.4f ") % (gyro.mass) ) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Centroid x         = %1$9.4f Ang") % (gyro.centroid.x()*tools::conv::bohr2ang) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Centroid y         = %1$9.4f Ang") % (gyro.centroid.y()*tools::conv::bohr2ang) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Centroid y         = %1$9.4f Ang") % (gyro.centroid.z()*tools::conv::bohr2ang) ) << flush;

            double RA2 = tools::conv::bohr2ang  *tools::conv::bohr2ang;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor xx = %1$9.4f Ang^2") % (gyro.gyration(0,0)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor xy = %1$9.4f Ang^2") % (gyro.gyration(0,1)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor xz = %1$9.4f Ang^2") % (gyro.gyration(0,2)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor yy = %1$9.4f Ang^2") % (gyro.gyration(1,1)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor yz = %1$9.4f Ang^2") % (gyro.gyration(1,2)*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor zz = %1$9.4f Ang^2") % (gyro.gyration(2,2)*RA2) ) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor D1 = %1$9.4f Ang^2") % (es.eigenvalues()[0]*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor D2 = %1$9.4f Ang^2") % (es.eigenvalues()[1]*RA2) ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Gyration Tensor D3 = %1$9.4f Ang^2") % (es.eigenvalues()[2]*RA2) ) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Radius of Gyration = %1$9.4f Ang") % (std::sqrt(es.eigenvalues().sum())*tools::conv::bohr2ang )) << flush;

            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 1 1 = %1$9.4f ") % es.eigenvectors().col(0).x() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 1 2 = %1$9.4f ") % es.eigenvectors().col(0).y() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 1 3 = %1$9.4f ") % es.eigenvectors().col(0).z() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 2 1 = %1$9.4f ") % es.eigenvectors().col(1).x() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 2 2 = %1$9.4f ") % es.eigenvectors().col(1).y() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 2 3 = %1$9.4f ") % es.eigenvectors().col(1).z() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 3 1 = %1$9.4f ") % es.eigenvectors().col(2).x() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 3 2 = %1$9.4f ") % es.eigenvectors().col(2).y() ) << flush;
            XTP_LOG(logINFO,*_log) << (boost::format("  Tensor EF Axis 3 3 = %1$9.4f ") % es.eigenvectors().col(2).z() ) << flush;
            return;
    }

}}

<|endoftext|>


<commit_before>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include <gst/gst.h>

#include "logging.hpp"

#include <boost/format.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/sources/channel_feature.hpp>
#include <boost/log/sources/channel_logger.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/manipulators/add_value.hpp>

namespace logging = boost::log;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;

typedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;

namespace kurento
{

/* kurento logging sinks */
boost::shared_ptr< sink_t > system_sink;

static std::string
debug_object (GObject *object)
{
  if (object == NULL) {
    return "";
  }

  if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {
    boost::format fmt ("<%s:%s> ");
    fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT (
             object) ) : "''") % GST_OBJECT_NAME (object);
    return fmt.str();
  }

  if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {
    boost::format fmt ("<%s> ");
    fmt % GST_OBJECT_NAME (object);
    return fmt.str();
  }

  if (G_IS_OBJECT (object) ) {
    boost::format fmt ("<%s@%p> ");
    fmt %  G_OBJECT_TYPE_NAME (object) % object;
    return fmt.str();
  }

  boost::format fmt ("<%p> ");
  fmt % object;
  return fmt.str();
}

static std::string
expand_string (std::string str, int len)
{
  std::string ret = str;
  int sp = len - str.size ();

  for (int i = sp; i > 0; i--) {
    str.append (" ");
  }

  return str;
}

static severity_level
gst_debug_level_to_severity_level (GstDebugLevel level)
{
  switch (level) {
  case GST_LEVEL_ERROR:
    return error;

  case GST_LEVEL_WARNING:
    return warning;

  case GST_LEVEL_FIXME:
    return fixme;

  case GST_LEVEL_INFO:
    return info;

  case GST_LEVEL_DEBUG:
    return debug;

  case GST_LEVEL_LOG:
    return log;

  case GST_LEVEL_TRACE:
    return trace;

  default:
    return undefined;
  }
}

static void
kms_log_function (GstDebugCategory *category, GstDebugLevel level,
                  const gchar *file,
                  const gchar *function, gint line, GObject *object,
                  GstDebugMessage *message, gpointer user_data)
{
  if (level > gst_debug_category_get_threshold (category) ) {
    return;
  }

  severity_level severity = gst_debug_level_to_severity_level (level);

  if (severity == undefined) {
    return;
  }

  BOOST_LOG_SEV (system_logger::get(), severity) <<
      logging::add_value ("Category", expand_string (category->name, 25) ) <<
      logging::add_value ("FileName",
                          boost::filesystem::path (file).filename().string() ) <<
      logging::add_value ("Line", line) <<
      logging::add_value ("Function", function) <<
      logging::add_value ("GObject", debug_object (object) ) <<
      gst_debug_message_get (message);
}

void init_file_collecting (boost::shared_ptr< sink_t > sink,
                           const std::string &path,
                           int fileSize,
                           int fileNumber)
{
  sink->locked_backend()->set_file_collector (sinks::file::make_collector (
        keywords::target = path,
        keywords::max_size = (fileSize * fileNumber) * 1024 * 1024,
        keywords::min_free_space = fileSize * 1024 * 1024
      ) );
}

/* The formatting logic for the severity level */
template< typename CharT, typename TraitsT >
inline std::basic_ostream< CharT, TraitsT > &operator<< (
  std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)
{
  static const char *const str[] = {
    "  error",
    "warning",
    "  fixme",
    "   info",
    "  debug",
    "    log",
    "  trace",
    "unknown"
  };

  if (static_cast< std::size_t > (lvl) < (sizeof (str) / sizeof (*str) ) ) {
    strm << str[lvl];
  } else {
    strm << static_cast< int > (lvl);
  }

  return strm;
}

static void
system_formatter (logging::record_view const &rec,
                  logging::formatting_ostream &strm)
{
  auto date_time_formatter = expr::stream
                             << expr::format_date_time< boost::posix_time::ptime > ("TimeStamp",
                                 "%Y-%m-%d %H:%M:%S,%f");
  date_time_formatter (rec, strm) << " ";
  strm << logging::extract< attrs::current_process_id::value_type > ("ProcessID",
       rec) << " ";
  strm << "[" <<
       logging::extract< attrs::current_thread_id::value_type > ("ThreadID",
           rec) << "] ";
  strm << logging::extract< severity_level > ("Severity", rec) << " ";
  strm << logging::extract< std::string > ("Category", rec) << " ";
  strm << logging::extract< std::string > ("FileName", rec) << ":";
  strm << logging::extract< int > ("Line", rec) << " ";
  strm << logging::extract< std::string > ("Function", rec) << "() ";
  strm << logging::extract< std::string > ("GObject", rec) << " ";
  strm << rec[expr::smessage];
}

bool
kms_init_logging (const std::string &path, int fileSize, int fileNumber)
{
  gst_debug_remove_log_function_by_data (NULL);
  gst_debug_add_log_function (kms_log_function, NULL, NULL);

  boost::shared_ptr< logging::core > core = logging::core::get();

  boost::shared_ptr< sinks::text_file_backend > backend =
    boost::make_shared< sinks::text_file_backend > (
      keywords::file_name = path + "/" + "media-server_%Y-%m-%d_%H-%M-%S.%5N.pid" +
                            std::to_string (getpid() ) + ".log",
      keywords::rotation_size = fileSize * 1024 * 1024,
      keywords::time_based_rotation = sinks::file::rotation_at_time_point (0, 0, 0)
    );

  /* Enable auto-flushing after each log record written */
  backend->auto_flush (true);

  /* Wrap it into the frontend and register in the core.   */
  /* The backend requires synchronization in the frontend. */
  system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );

  /*Set up filter to pass only records that have the necessary attributes */
  system_sink->set_filter (
    expr::has_attr< std::string > ("Channel") &&
    expr::attr< std::string > ("Channel") == "system"
  );

  /* Set up where the rotated files will be stored */
  init_file_collecting (system_sink, path + "/logs", fileSize, fileNumber);

  /* Upon restart, scan the directory for files matching the file_name pattern */
  system_sink->locked_backend()->scan_for_files();

  core->add_sink (system_sink);

  system_sink->set_formatter (&system_formatter);

  return true;
}

}  /* kurento */
<commit_msg>logging: Do not print gstreamer logs when boost file log is active<commit_after>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include <gst/gst.h>

#include "logging.hpp"

#include <boost/format.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/sources/channel_feature.hpp>
#include <boost/log/sources/channel_logger.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/manipulators/add_value.hpp>

namespace logging = boost::log;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;

typedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;

namespace kurento
{

/* kurento logging sinks */
boost::shared_ptr< sink_t > system_sink;

static std::string
debug_object (GObject *object)
{
  if (object == NULL) {
    return "";
  }

  if (GST_IS_PAD (object) && GST_OBJECT_NAME (object) ) {
    boost::format fmt ("<%s:%s> ");
    fmt % (GST_OBJECT_PARENT (object) != NULL ? GST_OBJECT_NAME (GST_OBJECT_PARENT (
             object) ) : "''") % GST_OBJECT_NAME (object);
    return fmt.str();
  }

  if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object) ) {
    boost::format fmt ("<%s> ");
    fmt % GST_OBJECT_NAME (object);
    return fmt.str();
  }

  if (G_IS_OBJECT (object) ) {
    boost::format fmt ("<%s@%p> ");
    fmt %  G_OBJECT_TYPE_NAME (object) % object;
    return fmt.str();
  }

  boost::format fmt ("<%p> ");
  fmt % object;
  return fmt.str();
}

static std::string
expand_string (std::string str, int len)
{
  std::string ret = str;
  int sp = len - str.size ();

  for (int i = sp; i > 0; i--) {
    str.append (" ");
  }

  return str;
}

static severity_level
gst_debug_level_to_severity_level (GstDebugLevel level)
{
  switch (level) {
  case GST_LEVEL_ERROR:
    return error;

  case GST_LEVEL_WARNING:
    return warning;

  case GST_LEVEL_FIXME:
    return fixme;

  case GST_LEVEL_INFO:
    return info;

  case GST_LEVEL_DEBUG:
    return debug;

  case GST_LEVEL_LOG:
    return log;

  case GST_LEVEL_TRACE:
    return trace;

  default:
    return undefined;
  }
}

static void
kms_log_function (GstDebugCategory *category, GstDebugLevel level,
                  const gchar *file,
                  const gchar *function, gint line, GObject *object,
                  GstDebugMessage *message, gpointer user_data)
{
  if (level > gst_debug_category_get_threshold (category) ) {
    return;
  }

  severity_level severity = gst_debug_level_to_severity_level (level);

  if (severity == undefined) {
    return;
  }

  BOOST_LOG_SEV (system_logger::get(), severity) <<
      logging::add_value ("Category", expand_string (category->name, 25) ) <<
      logging::add_value ("FileName",
                          boost::filesystem::path (file).filename().string() ) <<
      logging::add_value ("Line", line) <<
      logging::add_value ("Function", function) <<
      logging::add_value ("GObject", debug_object (object) ) <<
      gst_debug_message_get (message);
}

void init_file_collecting (boost::shared_ptr< sink_t > sink,
                           const std::string &path,
                           int fileSize,
                           int fileNumber)
{
  sink->locked_backend()->set_file_collector (sinks::file::make_collector (
        keywords::target = path,
        keywords::max_size = (fileSize * fileNumber) * 1024 * 1024,
        keywords::min_free_space = fileSize * 1024 * 1024
      ) );
}

/* The formatting logic for the severity level */
template< typename CharT, typename TraitsT >
inline std::basic_ostream< CharT, TraitsT > &operator<< (
  std::basic_ostream< CharT, TraitsT > &strm, severity_level lvl)
{
  static const char *const str[] = {
    "  error",
    "warning",
    "  fixme",
    "   info",
    "  debug",
    "    log",
    "  trace",
    "unknown"
  };

  if (static_cast< std::size_t > (lvl) < (sizeof (str) / sizeof (*str) ) ) {
    strm << str[lvl];
  } else {
    strm << static_cast< int > (lvl);
  }

  return strm;
}

static void
system_formatter (logging::record_view const &rec,
                  logging::formatting_ostream &strm)
{
  auto date_time_formatter = expr::stream
                             << expr::format_date_time< boost::posix_time::ptime > ("TimeStamp",
                                 "%Y-%m-%d %H:%M:%S,%f");
  date_time_formatter (rec, strm) << " ";
  strm << logging::extract< attrs::current_process_id::value_type > ("ProcessID",
       rec) << " ";
  strm << "[" <<
       logging::extract< attrs::current_thread_id::value_type > ("ThreadID",
           rec) << "] ";
  strm << logging::extract< severity_level > ("Severity", rec) << " ";
  strm << logging::extract< std::string > ("Category", rec) << " ";
  strm << logging::extract< std::string > ("FileName", rec) << ":";
  strm << logging::extract< int > ("Line", rec) << " ";
  strm << logging::extract< std::string > ("Function", rec) << "() ";
  strm << logging::extract< std::string > ("GObject", rec) << " ";
  strm << rec[expr::smessage];
}

bool
kms_init_logging (const std::string &path, int fileSize, int fileNumber)
{
  gst_debug_remove_log_function (gst_debug_log_default);
  gst_debug_add_log_function (kms_log_function, NULL, NULL);

  boost::shared_ptr< logging::core > core = logging::core::get();

  boost::shared_ptr< sinks::text_file_backend > backend =
    boost::make_shared< sinks::text_file_backend > (
      keywords::file_name = path + "/" + "media-server_%Y-%m-%d_%H-%M-%S.%5N.pid" +
                            std::to_string (getpid() ) + ".log",
      keywords::rotation_size = fileSize * 1024 * 1024,
      keywords::time_based_rotation = sinks::file::rotation_at_time_point (0, 0, 0)
    );

  /* Enable auto-flushing after each log record written */
  backend->auto_flush (true);

  /* Wrap it into the frontend and register in the core.   */
  /* The backend requires synchronization in the frontend. */
  system_sink = boost::shared_ptr< sink_t > (new sink_t (backend) );

  /*Set up filter to pass only records that have the necessary attributes */
  system_sink->set_filter (
    expr::has_attr< std::string > ("Channel") &&
    expr::attr< std::string > ("Channel") == "system"
  );

  /* Set up where the rotated files will be stored */
  init_file_collecting (system_sink, path + "/logs", fileSize, fileNumber);

  /* Upon restart, scan the directory for files matching the file_name pattern */
  system_sink->locked_backend()->scan_for_files();

  core->add_sink (system_sink);

  system_sink->set_formatter (&system_formatter);

  return true;
}

}  /* kurento */
<|endoftext|>


<commit_before>/*
  This file is part of libkdepim.

  Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
  Copyright (c) 2002 David Jarvie <software@astrojar.org.uk>
  Copyright (c) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
  Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

//krazy:excludeall=qclasses as we want to subclass from QComboBox, not KComboBox

#include "kdateedit.h"

#include <KCalendarSystem>
#include <KDebug>
#include <KGlobal>
#include <KGlobalSettings>
#include <KLocale>

#include <QAbstractItemView>
#include <QApplication>
#include <QEvent>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMouseEvent>
#include <QValidator>

using namespace KPIM;

class DateValidator : public QValidator
{
  public:
    DateValidator( const QStringList &keywords, QWidget *parent )
      : QValidator( parent ), mKeywords( keywords )
    {}

    virtual State validate( QString &str, int & ) const
    {
      int length = str.length();

      // empty string is intermediate so one can clear the edit line and start from scratch
      if ( length <= 0 ) {
        return Intermediate;
      }

      if ( mKeywords.contains( str.toLower() ) ) {
        return Acceptable;
      }

      bool ok = false;
      KGlobal::locale()->readDate( str, &ok );
      if ( ok ) {
        return Acceptable;
      } else {
        return Intermediate;
      }
    }

  private:
    QStringList mKeywords;
};

KDateEdit::KDateEdit( QWidget *parent, const char *name )
  : QComboBox( parent ), mReadOnly( false ), mDiscardNextMousePress( false )
{
  setObjectName( name );
  // need at least one entry for popup to work
  setMaxCount( 1 );
  setEditable( true );

  mDate = QDate::currentDate();
  QString today = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );

  addItem( today );
  setCurrentIndex( 0 );
  setSizeAdjustPolicy( AdjustToContents );

  connect( lineEdit(), SIGNAL( returnPressed() ),
           this, SLOT( lineEnterPressed() ) );
  connect( this, SIGNAL( textChanged( const QString& ) ),
           SLOT( slotTextChanged( const QString& ) ) );

  mPopup = new KDatePickerPopup( KDatePickerPopup::DatePicker | KDatePickerPopup::Words,
                                 QDate::currentDate(), this );
  mPopup->hide();
  mPopup->installEventFilter( this );

  connect( mPopup, SIGNAL( dateChanged( const QDate& ) ),
           SLOT( dateSelected( const QDate& ) ) );

  // handle keyword entry
  setupKeywords();
  lineEdit()->installEventFilter( this );

  setValidator( new DateValidator( mKeywordMap.keys(), this ) );

  mTextChanged = false;
}

KDateEdit::~KDateEdit()
{
}

void KDateEdit::setDate( const QDate &date )
{
  assignDate( date );
  updateView();
}

QDate KDateEdit::date() const
{
  return mDate;
}

void KDateEdit::setReadOnly( bool readOnly )
{
  mReadOnly = readOnly;
  lineEdit()->setReadOnly( readOnly );
}

bool KDateEdit::isReadOnly() const
{
  return mReadOnly;
}

void KDateEdit::showPopup()
{
  if ( mReadOnly ) {
    return;
  }

  QRect desk = KGlobalSettings::desktopGeometry( this );

  QPoint popupPoint = mapToGlobal( QPoint( 0, 0 ) );

  int dateFrameHeight = mPopup->sizeHint().height();
  if ( popupPoint.y() + height() + dateFrameHeight > desk.bottom() ) {
    popupPoint.setY( popupPoint.y() - dateFrameHeight );
  } else {
    popupPoint.setY( popupPoint.y() + height() );
  }

  int dateFrameWidth = mPopup->sizeHint().width();
  if ( popupPoint.x() + dateFrameWidth > desk.right() ) {
    popupPoint.setX( desk.right() - dateFrameWidth );
  }

  if ( popupPoint.x() < desk.left() ) {
    popupPoint.setX( desk.left() );
  }

  if ( popupPoint.y() < desk.top() ) {
    popupPoint.setY( desk.top() );
  }

  if ( mDate.isValid() ) {
    mPopup->setDate( mDate );
  } else {
    mPopup->setDate( QDate::currentDate() );
  }

  mPopup->popup( popupPoint );

  // The combo box is now shown pressed. Make it show not pressed again
  // by causing its (invisible) list box to emit a 'selected' signal.
  // First, ensure that the list box contains the date currently displayed.
  QDate date = parseDate();
  assignDate( date );
  updateView();

  // Now, simulate an Enter to unpress it
  QAbstractItemView *lb = view();
  if ( lb ) {
    lb->setCurrentIndex( lb->model()->index( 0, 0 ) );
    QKeyEvent *keyEvent =
      new QKeyEvent( QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier );
    QApplication::postEvent( lb, keyEvent );
  }
}

void KDateEdit::dateSelected( const QDate &date )
{
  if ( assignDate( date ) ) {
    updateView();
    emit dateChanged( date );
    emit dateEntered( date );

    if ( date.isValid() ) {
      mPopup->hide();
    }
  }
}

void KDateEdit::lineEnterPressed()
{
  bool replaced = false;

  QDate date = parseDate( &replaced );

  if ( assignDate( date ) ) {
    if ( replaced ) {
      updateView();
    }

    emit dateChanged( date );
    emit dateEntered( date );
  }
}

QDate KDateEdit::parseDate( bool *replaced ) const
{
  QString text = currentText();
  QDate result;

  if ( replaced ) {
    (*replaced) = false;
  }

  if ( text.isEmpty() ) {
    result = QDate();
  } else if ( mKeywordMap.contains( text.toLower() ) ) {
    QDate today = QDate::currentDate();
    int i = mKeywordMap[ text.toLower() ];
    if ( i >= 100 ) {
      /* A day name has been entered. Convert to offset from today.
       * This uses some math tricks to figure out the offset in days
       * to the next date the given day of the week occurs. There
       * are two cases, that the new day is >= the current day, which means
       * the new day has not occurred yet or that the new day < the current day,
       * which means the new day is already passed (so we need to find the
       * day in the next week).
       */
      i -= 100;
      int currentDay = today.dayOfWeek();
      if ( i >= currentDay ) {
        i -= currentDay;
      } else {
        i += 7 - currentDay;
      }
    }

    result = today.addDays( i );
    if ( replaced ) {
      (*replaced) = true;
    }
  } else {
    result = KGlobal::locale()->readDate( text );
  }

  return result;
}

void KDateEdit::focusOutEvent( QFocusEvent *e )
{
  if ( mTextChanged ) {
    lineEnterPressed();
    mTextChanged = false;
  }
  QComboBox::focusOutEvent( e );
}

void KDateEdit::keyPressEvent(QKeyEvent* e)
{
      int step = 0;
      if ( e->key() == Qt::Key_Up ) {
        step = 1;
      } else if ( e->key() == Qt::Key_Down ) {
        step = -1;
      }
      if ( step && !mReadOnly ) {
        QDate date = parseDate();
        if ( date.isValid() ) {
          date = date.addDays( step );
          if ( assignDate( date ) ) {
            updateView();
            emit dateChanged( date );
            emit dateEntered( date );
          }
        }
      }
}

bool KDateEdit::eventFilter( QObject *object, QEvent *event )
{
  if ( object == lineEdit() ) {
    // We only process the focus out event if the text has changed
    // since we got focus
    if ( ( event->type() == QEvent::FocusOut ) && mTextChanged ) {
      lineEnterPressed();
      mTextChanged = false;
    } else if ( event->type() == QEvent::KeyPress ) {
      // Up and down arrow keys step the date
      QKeyEvent *keyEvent = (QKeyEvent *)event;

      if ( keyEvent->key() == Qt::Key_Return ) {
        lineEnterPressed();
        return true;
      }
    }
  } else {
    // It's a date picker event
    switch ( event->type() ) {
    case QEvent::MouseButtonDblClick:
    case QEvent::MouseButtonPress:
    {
      QMouseEvent *mouseEvent = (QMouseEvent*)event;
      if ( !mPopup->rect().contains( mouseEvent->pos() ) ) {
        QPoint globalPos = mPopup->mapToGlobal( mouseEvent->pos() );
        if ( QApplication::widgetAt( globalPos ) == this ) {
          // The date picker is being closed by a click on the
          // KDateEdit widget. Avoid popping it up again immediately.
          mDiscardNextMousePress = true;
        }
      }

      break;
    }
    default:
      break;
    }
  }

  return false;
}

void KDateEdit::mousePressEvent( QMouseEvent *event )
{
  if ( event->button() == Qt::LeftButton && mDiscardNextMousePress ) {
    mDiscardNextMousePress = false;
    return;
  }

  QComboBox::mousePressEvent( event );
}

void KDateEdit::slotTextChanged( const QString & )
{
  QDate date = parseDate();

  if ( assignDate( date ) ) {
    emit dateChanged( date );
  }

  mTextChanged = true;
}

void KDateEdit::setupKeywords()
{
  // Create the keyword list. This will be used to match against when the user
  // enters information.
  mKeywordMap.insert( i18nc( "the day after today", "tomorrow" ), 1 );
  mKeywordMap.insert( i18nc( "this day", "today" ), 0 );
  mKeywordMap.insert( i18nc( "the day before today", "yesterday" ), -1 );

  QString dayName;
  for ( int i = 1; i <= 7; ++i ) {
    dayName = KGlobal::locale()->calendar()->weekDayName( i ).toLower();
    mKeywordMap.insert( dayName, i + 100 );
  }
}

bool KDateEdit::assignDate( const QDate &date )
{
  mDate = date;
  mTextChanged = false;
  return true;
}

void KDateEdit::updateView()
{
  QString dateString;
  if ( mDate.isValid() ) {
    dateString = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );
  }

  // We do not want to generate a signal here,
  // since we explicitly setting the date
  bool blocked = signalsBlocked();
  blockSignals( true );
  removeItem( 0 );
  insertItem( 0, dateString );
  blockSignals( blocked );
}

#include "kdateedit.moc"
<commit_msg>Let's allow people to type in the KDateEdit. Okay? :-)<commit_after>/*
  This file is part of libkdepim.

  Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
  Copyright (c) 2002 David Jarvie <software@astrojar.org.uk>
  Copyright (c) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
  Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

//krazy:excludeall=qclasses as we want to subclass from QComboBox, not KComboBox

#include "kdateedit.h"

#include <KCalendarSystem>
#include <KDebug>
#include <KGlobal>
#include <KGlobalSettings>
#include <KLocale>

#include <QAbstractItemView>
#include <QApplication>
#include <QEvent>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMouseEvent>
#include <QValidator>

using namespace KPIM;

class DateValidator : public QValidator
{
  public:
    DateValidator( const QStringList &keywords, QWidget *parent )
      : QValidator( parent ), mKeywords( keywords )
    {}

    virtual State validate( QString &str, int & ) const
    {
      int length = str.length();

      // empty string is intermediate so one can clear the edit line and start from scratch
      if ( length <= 0 ) {
        return Intermediate;
      }

      if ( mKeywords.contains( str.toLower() ) ) {
        return Acceptable;
      }

      bool ok = false;
      KGlobal::locale()->readDate( str, &ok );
      if ( ok ) {
        return Acceptable;
      } else {
        return Intermediate;
      }
    }

  private:
    QStringList mKeywords;
};

KDateEdit::KDateEdit( QWidget *parent, const char *name )
  : QComboBox( parent ), mReadOnly( false ), mDiscardNextMousePress( false )
{
  setObjectName( name );
  // need at least one entry for popup to work
  setMaxCount( 1 );
  setEditable( true );

  mDate = QDate::currentDate();
  QString today = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );

  addItem( today );
  setCurrentIndex( 0 );
  setSizeAdjustPolicy( AdjustToContents );

  connect( lineEdit(), SIGNAL( returnPressed() ),
           this, SLOT( lineEnterPressed() ) );
  connect( this, SIGNAL( textChanged( const QString& ) ),
           SLOT( slotTextChanged( const QString& ) ) );

  mPopup = new KDatePickerPopup( KDatePickerPopup::DatePicker | KDatePickerPopup::Words,
                                 QDate::currentDate(), this );
  mPopup->hide();
  mPopup->installEventFilter( this );

  connect( mPopup, SIGNAL( dateChanged( const QDate& ) ),
           SLOT( dateSelected( const QDate& ) ) );

  // handle keyword entry
  setupKeywords();
  lineEdit()->installEventFilter( this );

  setValidator( new DateValidator( mKeywordMap.keys(), this ) );

  mTextChanged = false;
}

KDateEdit::~KDateEdit()
{
}

void KDateEdit::setDate( const QDate &date )
{
  assignDate( date );
  updateView();
}

QDate KDateEdit::date() const
{
  return mDate;
}

void KDateEdit::setReadOnly( bool readOnly )
{
  mReadOnly = readOnly;
  lineEdit()->setReadOnly( readOnly );
}

bool KDateEdit::isReadOnly() const
{
  return mReadOnly;
}

void KDateEdit::showPopup()
{
  if ( mReadOnly ) {
    return;
  }

  QRect desk = KGlobalSettings::desktopGeometry( this );

  QPoint popupPoint = mapToGlobal( QPoint( 0, 0 ) );

  int dateFrameHeight = mPopup->sizeHint().height();
  if ( popupPoint.y() + height() + dateFrameHeight > desk.bottom() ) {
    popupPoint.setY( popupPoint.y() - dateFrameHeight );
  } else {
    popupPoint.setY( popupPoint.y() + height() );
  }

  int dateFrameWidth = mPopup->sizeHint().width();
  if ( popupPoint.x() + dateFrameWidth > desk.right() ) {
    popupPoint.setX( desk.right() - dateFrameWidth );
  }

  if ( popupPoint.x() < desk.left() ) {
    popupPoint.setX( desk.left() );
  }

  if ( popupPoint.y() < desk.top() ) {
    popupPoint.setY( desk.top() );
  }

  if ( mDate.isValid() ) {
    mPopup->setDate( mDate );
  } else {
    mPopup->setDate( QDate::currentDate() );
  }

  mPopup->popup( popupPoint );

  // The combo box is now shown pressed. Make it show not pressed again
  // by causing its (invisible) list box to emit a 'selected' signal.
  // First, ensure that the list box contains the date currently displayed.
  QDate date = parseDate();
  assignDate( date );
  updateView();

  // Now, simulate an Enter to unpress it
  QAbstractItemView *lb = view();
  if ( lb ) {
    lb->setCurrentIndex( lb->model()->index( 0, 0 ) );
    QKeyEvent *keyEvent =
      new QKeyEvent( QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier );
    QApplication::postEvent( lb, keyEvent );
  }
}

void KDateEdit::dateSelected( const QDate &date )
{
  if ( assignDate( date ) ) {
    updateView();
    emit dateChanged( date );
    emit dateEntered( date );

    if ( date.isValid() ) {
      mPopup->hide();
    }
  }
}

void KDateEdit::lineEnterPressed()
{
  bool replaced = false;

  QDate date = parseDate( &replaced );

  if ( assignDate( date ) ) {
    if ( replaced ) {
      updateView();
    }

    emit dateChanged( date );
    emit dateEntered( date );
  }
}

QDate KDateEdit::parseDate( bool *replaced ) const
{
  QString text = currentText();
  QDate result;

  if ( replaced ) {
    (*replaced) = false;
  }

  if ( text.isEmpty() ) {
    result = QDate();
  } else if ( mKeywordMap.contains( text.toLower() ) ) {
    QDate today = QDate::currentDate();
    int i = mKeywordMap[ text.toLower() ];
    if ( i >= 100 ) {
      /* A day name has been entered. Convert to offset from today.
       * This uses some math tricks to figure out the offset in days
       * to the next date the given day of the week occurs. There
       * are two cases, that the new day is >= the current day, which means
       * the new day has not occurred yet or that the new day < the current day,
       * which means the new day is already passed (so we need to find the
       * day in the next week).
       */
      i -= 100;
      int currentDay = today.dayOfWeek();
      if ( i >= currentDay ) {
        i -= currentDay;
      } else {
        i += 7 - currentDay;
      }
    }

    result = today.addDays( i );
    if ( replaced ) {
      (*replaced) = true;
    }
  } else {
    result = KGlobal::locale()->readDate( text );
  }

  return result;
}

void KDateEdit::focusOutEvent( QFocusEvent *e )
{
  if ( mTextChanged ) {
    lineEnterPressed();
    mTextChanged = false;
  }
  QComboBox::focusOutEvent( e );
}

void KDateEdit::keyPressEvent(QKeyEvent* e)
{
      int step = 0;
      if ( e->key() == Qt::Key_Up ) {
        step = 1;
      } else if ( e->key() == Qt::Key_Down ) {
        step = -1;
      }
      if ( step && !mReadOnly ) {
        QDate date = parseDate();
        if ( date.isValid() ) {
          date = date.addDays( step );
          if ( assignDate( date ) ) {
            updateView();
            emit dateChanged( date );
            emit dateEntered( date );
          }
        }
      }
      QComboBox::keyPressEvent( e );
}

bool KDateEdit::eventFilter( QObject *object, QEvent *event )
{
  if ( object == lineEdit() ) {
    // We only process the focus out event if the text has changed
    // since we got focus
    if ( ( event->type() == QEvent::FocusOut ) && mTextChanged ) {
      lineEnterPressed();
      mTextChanged = false;
    } else if ( event->type() == QEvent::KeyPress ) {
      // Up and down arrow keys step the date
      QKeyEvent *keyEvent = (QKeyEvent *)event;

      if ( keyEvent->key() == Qt::Key_Return ) {
        lineEnterPressed();
        return true;
      }
    }
  } else {
    // It's a date picker event
    switch ( event->type() ) {
    case QEvent::MouseButtonDblClick:
    case QEvent::MouseButtonPress:
    {
      QMouseEvent *mouseEvent = (QMouseEvent*)event;
      if ( !mPopup->rect().contains( mouseEvent->pos() ) ) {
        QPoint globalPos = mPopup->mapToGlobal( mouseEvent->pos() );
        if ( QApplication::widgetAt( globalPos ) == this ) {
          // The date picker is being closed by a click on the
          // KDateEdit widget. Avoid popping it up again immediately.
          mDiscardNextMousePress = true;
        }
      }

      break;
    }
    default:
      break;
    }
  }

  return false;
}

void KDateEdit::mousePressEvent( QMouseEvent *event )
{
  if ( event->button() == Qt::LeftButton && mDiscardNextMousePress ) {
    mDiscardNextMousePress = false;
    return;
  }

  QComboBox::mousePressEvent( event );
}

void KDateEdit::slotTextChanged( const QString & )
{
  QDate date = parseDate();

  if ( assignDate( date ) ) {
    emit dateChanged( date );
  }

  mTextChanged = true;
}

void KDateEdit::setupKeywords()
{
  // Create the keyword list. This will be used to match against when the user
  // enters information.
  mKeywordMap.insert( i18nc( "the day after today", "tomorrow" ), 1 );
  mKeywordMap.insert( i18nc( "this day", "today" ), 0 );
  mKeywordMap.insert( i18nc( "the day before today", "yesterday" ), -1 );

  QString dayName;
  for ( int i = 1; i <= 7; ++i ) {
    dayName = KGlobal::locale()->calendar()->weekDayName( i ).toLower();
    mKeywordMap.insert( dayName, i + 100 );
  }
}

bool KDateEdit::assignDate( const QDate &date )
{
  mDate = date;
  mTextChanged = false;
  return true;
}

void KDateEdit::updateView()
{
  QString dateString;
  if ( mDate.isValid() ) {
    dateString = KGlobal::locale()->formatDate( mDate, KLocale::ShortDate );
  }

  // We do not want to generate a signal here,
  // since we explicitly setting the date
  bool blocked = signalsBlocked();
  blockSignals( true );
  removeItem( 0 );
  insertItem( 0, dateString );
  blockSignals( blocked );
}

#include "kdateedit.moc"
<|endoftext|>


<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Actions/Draw.hpp>
#include <hspp/Actions/Generic.hpp>
#include <hspp/Cards/Cards.hpp>
#include <hspp/Games/Game.hpp>
#include <hspp/Games/GameManager.hpp>

#include <effolkronium/random.hpp>

#include <algorithm>

using Random = effolkronium::random_static;

namespace Hearthstonepp
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
    // Add hero and hero power
    GetPlayer1().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
    GetPlayer2().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));

    // Set opponent player
    GetPlayer1().SetOpponent(&GetPlayer2());
    GetPlayer2().SetOpponent(&GetPlayer1());
}

Player& Game::GetPlayer1()
{
    return m_players[0];
}

Player& Game::GetPlayer2()
{
    return m_players[1];
}

Player& Game::GetCurrentPlayer()
{
    return *m_currentPlayer;
}

Player& Game::GetOpponentPlayer()
{
    return m_currentPlayer->GetOpponent();
}

void Game::BeginFirst()
{
    // Set next step
    nextStep = Step::BEGIN_SHUFFLE;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::BeginShuffle()
{
    // Shuffle cards in deck
    if (m_gameConfig.doShuffle)
    {
        GetPlayer1().GetDeck().Shuffle();
        GetPlayer2().GetDeck().Shuffle();
    }

    // Set next step
    nextStep = Step::BEGIN_DRAW;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::BeginDraw()
{
    for (auto& p : m_players)
    {
        // Draw 3 cards
        Generic::Draw(p);
        Generic::Draw(p);
        Generic::Draw(p);

        if (&p != m_firstPlayer)
        {
            // Draw 4th card for second player
            Generic::Draw(p);

            // Give "The Coin" card to second player
            Card coin = Cards::GetInstance().FindCardByID("GAME_005");
            p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));
        }
    }

    // Set next step
    nextStep =
        m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::BeginMulligan()
{
    // Do nothing
}

void Game::MainBegin()
{
    // Set next step
    nextStep = Step::MAIN_READY;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainReady()
{
    // Reset the number of attacked
    for (auto& p : m_players)
    {
        // Hero
        p.GetHero()->numAttacked = 0;
        // Field
        for (auto& m : p.GetField().GetAllMinions())
        {
            m->numAttacked = 0;
        }
    }

    // Reset exhaust for current player
    auto& curPlayer = GetCurrentPlayer();
    // Hero
    curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);
    // Weapon
    if (curPlayer.GetHero()->weapon != nullptr)
    {
        curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);
    }
    // Hero power
    curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        m->SetGameTag(GameTag::EXHAUSTED, 0);
    }

    // Set next step
    nextStep = Step::MAIN_START_TRIGGERS;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainStartTriggers()
{
    // Set next step
    nextStep = Step::MAIN_RESOURCE;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainResource()
{
    auto& curPlayer = GetCurrentPlayer();

    // Add mana crystal to current player
    Generic::ChangeManaCrystal(curPlayer, 1, false);

    // Reset current mana
    curPlayer.currentMana = curPlayer.maximumMana;

    // Set next step
    nextStep = Step::MAIN_DRAW;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainDraw()
{
    // Draw a card for current player
    Generic::Draw(GetCurrentPlayer());

    // Set next step
    nextStep = Step::MAIN_START;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainStart()
{
    // Set next step
    nextStep = Step::MAIN_ACTION;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainEnd()
{
    // Set next step
    nextStep = Step::MAIN_CLEANUP;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainCleanUp()
{
    auto& curPlayer = GetCurrentPlayer();

    // Unfreeze all characters they control that are Frozen, don't have
    // summoning sickness (or do have Charge) and have not attacked that turn
    // Hero
    if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&
        curPlayer.GetHero()->numAttacked == 0)
    {
        curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);
    }
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&
            m->GetGameTag(GameTag::EXHAUSTED) == 0)
        {
            m->SetGameTag(GameTag::FROZEN, 0);
        }
    }

    // Set next step
    nextStep = Step::MAIN_NEXT;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainNext()
{
    // Set player for next turn
    m_currentPlayer = &m_currentPlayer->GetOpponent();

    // Count next turn
    m_turn++;

    // Set next step
    nextStep = Step::MAIN_READY;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::FinalWrapUp()
{
    // Do nothing
}

void Game::FinalGameOver()
{
    // Do nothing
}

void Game::StartGame()
{
    // Reverse card order in deck
    if (!m_gameConfig.doShuffle)
    {
        std::reverse(m_gameConfig.player1Deck.begin(),
                     m_gameConfig.player1Deck.end());
        std::reverse(m_gameConfig.player2Deck.begin(),
                     m_gameConfig.player2Deck.end());
    }

    // Set up decks
    for (auto& card : m_gameConfig.player1Deck)
    {
        Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
        GetPlayer1().GetDeck().AddCard(*entity);
    }
    for (auto& card : m_gameConfig.player2Deck)
    {
        Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
        GetPlayer2().GetDeck().AddCard(*entity);
    }

    // Determine first player
    switch (m_gameConfig.startPlayer)
    {
        case PlayerType::RANDOM:
        {
            auto val = Random::get(0, 1);
            m_firstPlayer = &m_players[val];
            break;
        }
        case PlayerType::PLAYER1:
            m_firstPlayer = &m_players[0];
            break;
        case PlayerType::PLAYER2:
            m_firstPlayer = &m_players[1];
            break;
    }
    m_currentPlayer = m_firstPlayer;

    // Set first turn
    m_turn = 1;

    // Set next step
    nextStep = Step::BEGIN_FIRST;
    GameManager::ProcessNextStep(*this, nextStep);
}
}  // namespace Hearthstonepp<commit_msg>[ci skip] feat(game-state): Add code to set game states<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Actions/Draw.hpp>
#include <hspp/Actions/Generic.hpp>
#include <hspp/Cards/Cards.hpp>
#include <hspp/Games/Game.hpp>
#include <hspp/Games/GameManager.hpp>

#include <effolkronium/random.hpp>

#include <algorithm>

using Random = effolkronium::random_static;

namespace Hearthstonepp
{
Game::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)
{
    // Add hero and hero power
    GetPlayer1().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player1Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));
    GetPlayer2().AddHeroAndPower(
        Cards::GetInstance().GetHeroCard(gameConfig.player2Class),
        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));

    // Set opponent player
    GetPlayer1().SetOpponent(&GetPlayer2());
    GetPlayer2().SetOpponent(&GetPlayer1());
}

Player& Game::GetPlayer1()
{
    return m_players[0];
}

Player& Game::GetPlayer2()
{
    return m_players[1];
}

Player& Game::GetCurrentPlayer()
{
    return *m_currentPlayer;
}

Player& Game::GetOpponentPlayer()
{
    return m_currentPlayer->GetOpponent();
}

void Game::BeginFirst()
{
    // Set next step
    nextStep = Step::BEGIN_SHUFFLE;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::BeginShuffle()
{
    // Shuffle cards in deck
    if (m_gameConfig.doShuffle)
    {
        GetPlayer1().GetDeck().Shuffle();
        GetPlayer2().GetDeck().Shuffle();
    }

    // Set next step
    nextStep = Step::BEGIN_DRAW;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::BeginDraw()
{
    for (auto& p : m_players)
    {
        // Draw 3 cards
        Generic::Draw(p);
        Generic::Draw(p);
        Generic::Draw(p);

        if (&p != m_firstPlayer)
        {
            // Draw 4th card for second player
            Generic::Draw(p);

            // Give "The Coin" card to second player
            Card coin = Cards::GetInstance().FindCardByID("GAME_005");
            p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));
        }
    }

    // Set next step
    nextStep =
        m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::BeginMulligan()
{
    // Do nothing
}

void Game::MainBegin()
{
    // Set next step
    nextStep = Step::MAIN_READY;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainReady()
{
    // Reset the number of attacked
    for (auto& p : m_players)
    {
        // Hero
        p.GetHero()->numAttacked = 0;
        // Field
        for (auto& m : p.GetField().GetAllMinions())
        {
            m->numAttacked = 0;
        }
    }

    // Reset exhaust for current player
    auto& curPlayer = GetCurrentPlayer();
    // Hero
    curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);
    // Weapon
    if (curPlayer.GetHero()->weapon != nullptr)
    {
        curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);
    }
    // Hero power
    curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        m->SetGameTag(GameTag::EXHAUSTED, 0);
    }

    // Set next step
    nextStep = Step::MAIN_START_TRIGGERS;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainStartTriggers()
{
    // Set next step
    nextStep = Step::MAIN_RESOURCE;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainResource()
{
    auto& curPlayer = GetCurrentPlayer();

    // Add mana crystal to current player
    Generic::ChangeManaCrystal(curPlayer, 1, false);

    // Reset current mana
    curPlayer.currentMana = curPlayer.maximumMana;

    // Set next step
    nextStep = Step::MAIN_DRAW;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainDraw()
{
    // Draw a card for current player
    Generic::Draw(GetCurrentPlayer());

    // Set next step
    nextStep = Step::MAIN_START;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainStart()
{
    // Set next step
    nextStep = Step::MAIN_ACTION;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainEnd()
{
    // Set next step
    nextStep = Step::MAIN_CLEANUP;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainCleanUp()
{
    auto& curPlayer = GetCurrentPlayer();

    // Unfreeze all characters they control that are Frozen, don't have
    // summoning sickness (or do have Charge) and have not attacked that turn
    // Hero
    if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&
        curPlayer.GetHero()->numAttacked == 0)
    {
        curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);
    }
    // Field
    for (auto& m : curPlayer.GetField().GetAllMinions())
    {
        if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&
            m->GetGameTag(GameTag::EXHAUSTED) == 0)
        {
            m->SetGameTag(GameTag::FROZEN, 0);
        }
    }

    // Set next step
    nextStep = Step::MAIN_NEXT;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::MainNext()
{
    // Set player for next turn
    m_currentPlayer = &m_currentPlayer->GetOpponent();

    // Count next turn
    m_turn++;

    // Set next step
    nextStep = Step::MAIN_READY;
    GameManager::ProcessNextStep(*this, nextStep);
}

void Game::FinalWrapUp()
{
    // Do nothing
}

void Game::FinalGameOver()
{
    // Do nothing
}

void Game::StartGame()
{
    // Reverse card order in deck
    if (!m_gameConfig.doShuffle)
    {
        std::reverse(m_gameConfig.player1Deck.begin(),
                     m_gameConfig.player1Deck.end());
        std::reverse(m_gameConfig.player2Deck.begin(),
                     m_gameConfig.player2Deck.end());
    }

    // Set up decks
    for (auto& card : m_gameConfig.player1Deck)
    {
        Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));
        GetPlayer1().GetDeck().AddCard(*entity);
    }
    for (auto& card : m_gameConfig.player2Deck)
    {
        Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));
        GetPlayer2().GetDeck().AddCard(*entity);
    }

    // Set game states
    state = State::RUNNING;
    for (auto& p : m_players)
    {
        p.playState = PlayState::PLAYING;
    }

    // Determine first player
    switch (m_gameConfig.startPlayer)
    {
        case PlayerType::RANDOM:
        {
            auto val = Random::get(0, 1);
            m_firstPlayer = &m_players[val];
            break;
        }
        case PlayerType::PLAYER1:
            m_firstPlayer = &m_players[0];
            break;
        case PlayerType::PLAYER2:
            m_firstPlayer = &m_players[1];
            break;
    }
    m_currentPlayer = m_firstPlayer;

    // Set first turn
    m_turn = 1;

    // Set next step
    nextStep = Step::BEGIN_FIRST;
    GameManager::ProcessNextStep(*this, nextStep);
}
}  // namespace Hearthstonepp<|endoftext|>


<commit_before>/*
    This file is part of libkdepim.

    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <time.h>
#include <unistd.h>

#include <qstring.h>

#include <kstandarddirs.h>
#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>

#include "kpimprefs.h"

KPimPrefs::KPimPrefs( const QString &name )
  : KConfigSkeleton( name )
{
}

KPimPrefs::~KPimPrefs()
{
}

void KPimPrefs::usrSetDefaults()
{
  setCategoryDefaults();
}

void KPimPrefs::usrReadConfig()
{
  kdDebug(5300) << "KPimPrefs::usrReadConfig()" << endl;

  config()->setGroup("General");
  mCustomCategories = config()->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();
}

const QString KPimPrefs::timezone()
{
  QString zone = "";

  // Read TimeZoneId from korganizerrc.
  KConfig korgcfg( locate( "config", QString::fromLatin1("korganizerrc") ) );
  korgcfg.setGroup( "Time & Date" );
  QString tz(korgcfg.readEntry( "TimeZoneId" ) );
  if ( ! tz.isEmpty() )
  {
    zone = tz;
    kdDebug(5300) << "timezone from korganizerrc is " << zone << endl;
  }

  // If timezone not found in KOrg, use the system's default timezone.
  if ( zone.isEmpty() )
  {
    char zonefilebuf[PATH_MAX];

    // readlink does not return a null-terminated string.
    memset(zonefilebuf, '\0', PATH_MAX);
    int len = readlink("/etc/localtime", zonefilebuf, PATH_MAX);
    if ( len > 0 && len < PATH_MAX )
    {
        zone = QString::fromLocal8Bit(zonefilebuf);
        zone = zone.mid(zone.find("zoneinfo/") + 9);
        kdDebug(5300) << "system timezone from /etc/localtime is " << zone << endl;
    }
    else
    {
        tzset();
        zone = tzname[0];
        kdDebug(5300)  << "system timezone from tzset() is " << zone << endl;
    }
  }

  return( zone );

}

void KPimPrefs::usrWriteConfig()
{
  config()->setGroup("General");
  config()->writeEntry("Custom Categories",mCustomCategories);
}
<commit_msg>No QT_NO_CAST_ASCII in libkdepim, so don't need fromLatin1.<commit_after>/*
    This file is part of libkdepim.

    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <time.h>
#include <unistd.h>

#include <qstring.h>

#include <kstandarddirs.h>
#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>

#include "kpimprefs.h"

KPimPrefs::KPimPrefs( const QString &name )
  : KConfigSkeleton( name )
{
}

KPimPrefs::~KPimPrefs()
{
}

void KPimPrefs::usrSetDefaults()
{
  setCategoryDefaults();
}

void KPimPrefs::usrReadConfig()
{
  kdDebug(5300) << "KPimPrefs::usrReadConfig()" << endl;

  config()->setGroup("General");
  mCustomCategories = config()->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();
}

const QString KPimPrefs::timezone()
{
  QString zone = "";

  // Read TimeZoneId from korganizerrc.
  KConfig korgcfg( locate( "config", "korganizerrc" ) );
  korgcfg.setGroup( "Time & Date" );
  QString tz(korgcfg.readEntry( "TimeZoneId" ) );
  if ( ! tz.isEmpty() )
  {
    zone = tz;
    kdDebug(5300) << "timezone from korganizerrc is " << zone << endl;
  }

  // If timezone not found in KOrg, use the system's default timezone.
  if ( zone.isEmpty() )
  {
    char zonefilebuf[PATH_MAX];

    int len = readlink("/etc/localtime", zonefilebuf, PATH_MAX);
    if ( len > 0 && len < PATH_MAX )
    {
        zone = QString::fromLocal8Bit(zonefilebuf, len);
        zone = zone.mid(zone.find("zoneinfo/") + 9);
        kdDebug(5300) << "system timezone from /etc/localtime is " << zone << endl;
    }
    else
    {
        tzset();
        zone = tzname[0];
        kdDebug(5300)  << "system timezone from tzset() is " << zone << endl;
    }
  }

  return( zone );

}

void KPimPrefs::usrWriteConfig()
{
  config()->setGroup("General");
  config()->writeEntry("Custom Categories",mCustomCategories);
}
<|endoftext|>


<commit_before>#include <zombye/core/game.hpp>
#include <zombye/ecs/entity.hpp>
#include <zombye/gameplay/gameplay_system.hpp>
#include <zombye/gameplay/state_component.hpp>
#include <zombye/scripting/scripting_system.hpp>

namespace zombye {
    state_component::state_component(game& game, entity& owner)
    : reflective{game, owner}, scripting_system_{game_.scripting_system()}, current_state_{nullptr} {
        game_.gameplay()->register_component(this);
    }

    state_component::~state_component() {
        game_.gameplay()->unregister_component(this);
    }

    void state_component::emplace(const std::string& state_name, const std::string& file_name) {
        auto it = states_.find(state_name);
        if (it != states_.end()) {
            throw std::runtime_error("state " + state_name + " already exists in " + std::to_string(owner_.id()));
        }

        static auto state_prefix = std::to_string(owner_.id()) + "_";
        auto module_name = state_prefix + state_name;

        scripting_system_.begin_module(module_name);
        scripting_system_.load_script(file_name);
        scripting_system_.end_module();

        auto module = scripting_system_.script_engine().GetModule(module_name.c_str());
        if (!module) {
            throw std::runtime_error("no module named " + module_name);
        }

        auto enter_ptr = module->GetFunctionByName("enter");
        if (!enter_ptr) {
            throw std::runtime_error("no function callback for enter state in " + file_name);
        }

        auto update_ptr = module->GetFunctionByName("update");
        if (!update_ptr) {
            throw std::runtime_error("no function callback for update state in " + file_name);
        }

        auto leave_ptr = module->GetFunctionByName("leave");
        if (!leave_ptr) {
            throw std::runtime_error("no function callback for leave state in " + file_name);
        }

        states_.insert(std::make_pair(state_name, character_state{enter_ptr, update_ptr, leave_ptr}));
    }

    void state_component::change_state(const std::string& state_name) {
        auto it = states_.find(state_name);
        if (it == states_.end()) {
            throw std::runtime_error("entity " + std::to_string(owner_.id()) + " has no state " + state_name);
        }

        if (current_state_) {
            scripting_system_.prepare(*current_state_->leave);
            scripting_system_.argument(0, &owner_);
            scripting_system_.exec();
        }

        current_state_ = &(it->second);
        scripting_system_.prepare(*current_state_->enter);
        scripting_system_.argument(0, &owner_);
        scripting_system_.exec();
    }

    void state_component::update(float delta_time) {
        if (current_state_) {
            scripting_system_.prepare(*current_state_->update);
            scripting_system_.argument(0, delta_time);
            scripting_system_.argument(1, &owner_);
            scripting_system_.exec();
        }
    }

    void state_component::register_at_script_engine(game& game) {
        auto& scripting_system = game.scripting_system();

        scripting_system.register_type<state_component>("state_component");

        scripting_system.register_member_function("state_component", "void emplace(const string& in, const string& in)",
            +[](state_component& component, const std::string& state_name, const std::string& file_name) {
                component.emplace(state_name, file_name);
            });
        scripting_system.register_member_function("state_component", "void change_state(const string& in)",
            +[](state_component& component, const std::string& state_name) { component.change_state(state_name); });

        scripting_system.register_member_function("entity_impl",
            "state_component& add_state_component()",
            +[](entity& owner) -> state_component& {
                return owner.emplace<state_component>();
            });
        scripting_system.register_member_function("entity_impl", "state_component@ get_state_component()",
            +[](entity& owner) { return owner.component<state_component>(); });
    }
}
<commit_msg>fix wrong argument pass to scripting_system::argument<commit_after>#include <zombye/core/game.hpp>
#include <zombye/ecs/entity.hpp>
#include <zombye/gameplay/gameplay_system.hpp>
#include <zombye/gameplay/state_component.hpp>
#include <zombye/scripting/scripting_system.hpp>

namespace zombye {
    state_component::state_component(game& game, entity& owner)
    : reflective{game, owner}, scripting_system_{game_.scripting_system()}, current_state_{nullptr} {
        game_.gameplay()->register_component(this);
    }

    state_component::~state_component() {
        game_.gameplay()->unregister_component(this);
    }

    void state_component::emplace(const std::string& state_name, const std::string& file_name) {
        auto it = states_.find(state_name);
        if (it != states_.end()) {
            throw std::runtime_error("state " + state_name + " already exists in " + std::to_string(owner_.id()));
        }

        static auto state_prefix = std::to_string(owner_.id()) + "_";
        auto module_name = state_prefix + state_name;

        scripting_system_.begin_module(module_name);
        scripting_system_.load_script(file_name);
        scripting_system_.end_module();

        auto module = scripting_system_.script_engine().GetModule(module_name.c_str());
        if (!module) {
            throw std::runtime_error("no module named " + module_name);
        }

        auto enter_ptr = module->GetFunctionByName("enter");
        if (!enter_ptr) {
            throw std::runtime_error("no function callback for enter state in " + file_name);
        }

        auto update_ptr = module->GetFunctionByName("update");
        if (!update_ptr) {
            throw std::runtime_error("no function callback for update state in " + file_name);
        }

        auto leave_ptr = module->GetFunctionByName("leave");
        if (!leave_ptr) {
            throw std::runtime_error("no function callback for leave state in " + file_name);
        }

        states_.insert(std::make_pair(state_name, character_state{enter_ptr, update_ptr, leave_ptr}));
    }

    void state_component::change_state(const std::string& state_name) {
        auto it = states_.find(state_name);
        if (it == states_.end()) {
            throw std::runtime_error("entity " + std::to_string(owner_.id()) + " has no state " + state_name);
        }

        if (current_state_) {
            scripting_system_.prepare(*current_state_->leave);
            scripting_system_.argument(0, owner_);
            scripting_system_.exec();
        }

        current_state_ = &(it->second);
        scripting_system_.prepare(*current_state_->enter);
        scripting_system_.argument(0, owner_);
        scripting_system_.exec();
    }

    void state_component::update(float delta_time) {
        if (current_state_) {
            scripting_system_.prepare(*current_state_->update);
            scripting_system_.argument(0, delta_time);
            scripting_system_.argument(1, owner_);
            scripting_system_.exec();
        }
    }

    void state_component::register_at_script_engine(game& game) {
        auto& scripting_system = game.scripting_system();

        scripting_system.register_type<state_component>("state_component");

        scripting_system.register_member_function("state_component", "void emplace(const string& in, const string& in)",
            +[](state_component& component, const std::string& state_name, const std::string& file_name) {
                component.emplace(state_name, file_name);
            });
        scripting_system.register_member_function("state_component", "void change_state(const string& in)",
            +[](state_component& component, const std::string& state_name) { component.change_state(state_name); });

        scripting_system.register_member_function("entity_impl",
            "state_component& add_state_component()",
            +[](entity& owner) -> state_component& {
                return owner.emplace<state_component>();
            });
        scripting_system.register_member_function("entity_impl", "state_component@ get_state_component()",
            +[](entity& owner) { return owner.component<state_component>(); });
    }
}
<|endoftext|>


<commit_before>#ifndef STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP
#define STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP

#include <vector>
#include <boost/math/tools/promotion.hpp>

#include <stan/math/prim/mat/fun/Eigen.hpp>

#include <stan/math/prim/scal/err/check_equal.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>

namespace stan {

  namespace math {

    /** Return the multiplication of the sparse matrix spefcified by
     * by values and indexing by the specified dense vector.
     *
     * The sparse matrix X of dimension m by n is represented by the
     * vector w (of values), the integer array v (containing one-based
     * row index of each value), the integer array u (containing
     * one-based indexes of where each column starts in w), and the
     * integer array z (containing the number of non-zero entries in
     * each column of w).
     *
     * @tparam T1 Type of sparse matrix entries.
     * @tparam T2 Type of dense vector entries.
     * @param m Rows in matrix.
     * @param n Columns in matrix.
     * @param v One-based row index of each value.
     * @param u one-based index of where each column starts in w.
     * @param z number of non-zer entries in each column of w.
     * @return dense vector for the product.
     * @throw ... explain error conditions briefly ...
     */
    /** Return the multiplication of the sparse matrix (specified by
     * by values and indexing) by the specified dense vector.
     *
     * The sparse matrix X of dimension m by n is represented by the
     * vector w (of values), the integer array v (containing one-based
     * row index of each value), the integer array u (containing
     * one-based indexes of where each column starts in w), and the
     * integer array z (containing the number of non-zero entries in
     * each column of w).
     *
     * @tparam T1 Type of sparse matrix entries.
     * @tparam T2 Type of dense vector entries.
     * @param m Number of rows in matrix.
     * @param n Number of columns in matrix.
		 * @param w Vector of non-zero values in matrix.
     * @param v One-based row index of each non-zero value, same
		 *          length as w.
     * @param u one-based index of where each column starts in w, equal to
		 *          the number of columns plus one.
     * @param z number of non-zero entries in each column of w, equal to
		 *          the number of columns..
     * @return dense vector for the product.
     * @throw std::domain_error if m and n are not positive or are nan.
		 * @throw std::domain_error if the implied sparse matrix and b are
		 *                          not multiplicable.
		 * @throw std::domain_error if m/n/w/v/u/z are not internally
		 * consistent, as defined by the indexing scheme.  Extractors are
		 * defined in Stan which guarantee a consistent set of m/n/w/v/u/z
		 * for a given sparse matrix.
     */
    template <typename T1, typename T2>
    inline
    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
    sparse_multiply_csc(const int& m,
                    const int& n,
                    const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
                    const std::vector<int>& v,
                    const std::vector<int>& u,
                    const std::vector<int>& z,
                    const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {

			stan::math::check_positive("sparse_multiply_csr","m",m);
			stan::math::check_positive("sparse_multiply_csr","n",n);
			stan::math::check_equal("sparse_multiply_csr","n/b", n, b.size());
			stan::math::check_equal("sparse_multiply_csr","n/u", n, u.size()-1);
			stan::math::check_equal("sparse_multiply_csr","n/z", n, z.size()  );
			stan::math::check_equal("sparse_multiply_csr","w/v", w.size(), v.size());
			stan::math::check_equal("sparse_multiply_csr","u/z/v", u[n-1]+z[n-1]-1, v.size());

      typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
      Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1>  y(m);
      for (int j = 0; j < n; ++j) {
        int end = u[j] + z[j] - 1;
        for (int q = u[j] - 1; q < end; ++q)
          y(v[q]-1) += w[q] * b(j);
      }
      return y;
    }

    /** Return the multiplication of the sparse matrix (specified by
     * by values and indexing) by the specified dense vector.
     *
     * The sparse matrix X of dimension m by n is represented by the
     * vector w (of values), the integer array v (containing one-based
     * column index of each value), the integer array u (containing
     * one-based indexes of where each row starts in w), and the
     * integer array z (containing the number of non-zero entries in
     * each row of w).
     *
     * @tparam T1 Type of sparse matrix entries.
     * @tparam T2 Type of dense vector entries.
     * @param m Number of rows in matrix.
     * @param n Number of columns in matrix.
		 * @param w Vector of non-zero values in matrix.
     * @param v One-based column index of each non-zero value, same
		 *          length as w.
     * @param u one-based index of where each row starts in w, equal to
		 *          the number of rows plus one.
     * @param z number of non-zero entries in each row of w, equal to
		 *          the number of rows..
     * @return dense vector for the product.
     * @throw std::domain_error if m and n are not positive or are nan.
		 * @throw std::domain_error if the implied sparse matrix and b are
		 *                          not multiplicable.
		 * @throw std::domain_error if m/n/w/v/u/z are not internally
		 * consistent, as defined by the indexing scheme.  Extractors are
		 * defined in Stan which guarantee a consistent set of m/n/w/v/u/z
		 * for a given sparse matrix.
     */
    template <typename T1, typename T2>
    inline
    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
    sparse_multiply_csr(const int& m,
                    const int& n,
                    const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
                    const std::vector<int>& v,
                    const std::vector<int>& u,
                    const std::vector<int>& z,
                    const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {

			stan::math::check_positive("sparse_multiply_csr","m",m);
			stan::math::check_positive("sparse_multiply_csr","n",n);
			stan::math::check_equal("sparse_multiply_csr","n/b", n, b.size());
			stan::math::check_equal("sparse_multiply_csr","m/u", m, u.size()-1);
			stan::math::check_equal("sparse_multiply_csr","m/z", m, z.size()  );
			stan::math::check_equal("sparse_multiply_csr","w/v", w.size(), v.size());
			stan::math::check_equal("sparse_multiply_csr","u/z/v", u[m-1]+z[m-1]-1, v.size());

      typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
      Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1>  y(m);
      for (int i = 0; i < m; ++i) {
        int end = u[i] + z[i] - 1;
        int p = 0;
        Eigen::Matrix<T2,Eigen::Dynamic,1> b_sub(z[i]);
        for (int q = u[i]-1; q < end; ++q) {
          b_sub(p) = b(v[q]-1);
          ++p;
        }
        Eigen::Matrix<T2,Eigen::Dynamic,1> w_sub = w.segment(u[i]-1,z[i]);
        y(i) = stan::math::dot_product(w_sub,b_sub);
      }
      return y;
    }

  }

}

#endif

<commit_msg>Fixed tabs.<commit_after>#ifndef STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP
#define STAN__MATH__MATRIX__SPARSE_MULTIPLY_HPP

#include <vector>
#include <boost/math/tools/promotion.hpp>

#include <stan/math/prim/mat/fun/Eigen.hpp>

#include <stan/math/prim/scal/err/check_equal.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>

namespace stan {

  namespace math {

    /** Return the multiplication of the sparse matrix spefcified by
     * by values and indexing by the specified dense vector.
     *
     * The sparse matrix X of dimension m by n is represented by the
     * vector w (of values), the integer array v (containing one-based
     * row index of each value), the integer array u (containing
     * one-based indexes of where each column starts in w), and the
     * integer array z (containing the number of non-zero entries in
     * each column of w).
     *
     * @tparam T1 Type of sparse matrix entries.
     * @tparam T2 Type of dense vector entries.
     * @param m Rows in matrix.
     * @param n Columns in matrix.
     * @param v One-based row index of each value.
     * @param u one-based index of where each column starts in w.
     * @param z number of non-zer entries in each column of w.
     * @return dense vector for the product.
     * @throw ... explain error conditions briefly ...
     */
    /** Return the multiplication of the sparse matrix (specified by
     * by values and indexing) by the specified dense vector.
     *
     * The sparse matrix X of dimension m by n is represented by the
     * vector w (of values), the integer array v (containing one-based
     * row index of each value), the integer array u (containing
     * one-based indexes of where each column starts in w), and the
     * integer array z (containing the number of non-zero entries in
     * each column of w).
     *
     * @tparam T1 Type of sparse matrix entries.
     * @tparam T2 Type of dense vector entries.
     * @param m Number of rows in matrix.
     * @param n Number of columns in matrix.
     * @param w Vector of non-zero values in matrix.
     * @param v One-based row index of each non-zero value, same
     *          length as w.
     * @param u one-based index of where each column starts in w, equal to
     *          the number of columns plus one.
     * @param z number of non-zero entries in each column of w, equal to
     *          the number of columns..
     * @return dense vector for the product.
     * @throw std::domain_error if m and n are not positive or are nan.
     * @throw std::domain_error if the implied sparse matrix and b are
     *                          not multiplicable.
     * @throw std::domain_error if m/n/w/v/u/z are not internally
     * consistent, as defined by the indexing scheme.  Extractors are
     * defined in Stan which guarantee a consistent set of m/n/w/v/u/z
     * for a given sparse matrix.
     */
    template <typename T1, typename T2>
    inline
    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
    sparse_multiply_csc(const int& m,
                    const int& n,
                    const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
                    const std::vector<int>& v,
                    const std::vector<int>& u,
                    const std::vector<int>& z,
                    const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {

      stan::math::check_positive("sparse_multiply_csr","m",m);
      stan::math::check_positive("sparse_multiply_csr","n",n);
      stan::math::check_equal("sparse_multiply_csr","n/b", n, b.size());
      stan::math::check_equal("sparse_multiply_csr","n/u", n, u.size()-1);
      stan::math::check_equal("sparse_multiply_csr","n/z", n, z.size()  );
      stan::math::check_equal("sparse_multiply_csr","w/v", w.size(), v.size());
      stan::math::check_equal("sparse_multiply_csr","u/z/v", u[n-1]+z[n-1]-1, v.size());

      typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
      Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1>  y(m);
      for (int j = 0; j < n; ++j) {
        int end = u[j] + z[j] - 1;
        for (int q = u[j] - 1; q < end; ++q)
          y(v[q]-1) += w[q] * b(j);
      }
      return y;
    }

    /** Return the multiplication of the sparse matrix (specified by
     * by values and indexing) by the specified dense vector.
     *
     * The sparse matrix X of dimension m by n is represented by the
     * vector w (of values), the integer array v (containing one-based
     * column index of each value), the integer array u (containing
     * one-based indexes of where each row starts in w), and the
     * integer array z (containing the number of non-zero entries in
     * each row of w).
     *
     * @tparam T1 Type of sparse matrix entries.
     * @tparam T2 Type of dense vector entries.
     * @param m Number of rows in matrix.
     * @param n Number of columns in matrix.
     * @param w Vector of non-zero values in matrix.
     * @param v One-based column index of each non-zero value, same
     *          length as w.
     * @param u one-based index of where each row starts in w, equal to
     *          the number of rows plus one.
     * @param z number of non-zero entries in each row of w, equal to
     *          the number of rows..
     * @return dense vector for the product.
     * @throw std::domain_error if m and n are not positive or are nan.
     * @throw std::domain_error if the implied sparse matrix and b are
     *                          not multiplicable.
     * @throw std::domain_error if m/n/w/v/u/z are not internally
     * consistent, as defined by the indexing scheme.  Extractors are
     * defined in Stan which guarantee a consistent set of m/n/w/v/u/z
     * for a given sparse matrix.
     */
    template <typename T1, typename T2>
    inline
    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type, Eigen::Dynamic, 1>
    sparse_multiply_csr(const int& m,
                    const int& n,
                    const Eigen::Matrix<T1, Eigen::Dynamic,1>& w,
                    const std::vector<int>& v,
                    const std::vector<int>& u,
                    const std::vector<int>& z,
                    const Eigen::Matrix<T2, Eigen::Dynamic,1>& b) {

      stan::math::check_positive("sparse_multiply_csr","m",m);
      stan::math::check_positive("sparse_multiply_csr","n",n);
      stan::math::check_equal("sparse_multiply_csr","n/b", n, b.size());
      stan::math::check_equal("sparse_multiply_csr","m/u", m, u.size()-1);
      stan::math::check_equal("sparse_multiply_csr","m/z", m, z.size()  );
      stan::math::check_equal("sparse_multiply_csr","w/v", w.size(), v.size());
      stan::math::check_equal("sparse_multiply_csr","u/z/v", u[m-1]+z[m-1]-1, v.size());

      typedef typename boost::math::tools::promote_args<T1, T2>::type fun_scalar_t;
      Eigen::Matrix<fun_scalar_t, Eigen::Dynamic, 1>  y(m);
      for (int i = 0; i < m; ++i) {
        int end = u[i] + z[i] - 1;
        int p = 0;
        Eigen::Matrix<T2,Eigen::Dynamic,1> b_sub(z[i]);
        for (int q = u[i]-1; q < end; ++q) {
          b_sub(p) = b(v[q]-1);
          ++p;
        }
        Eigen::Matrix<T2,Eigen::Dynamic,1> w_sub = w.segment(u[i]-1,z[i]);
        y(i) = stan::math::dot_product(w_sub,b_sub);
      }
      return y;
    }

  }

}

#endif

<|endoftext|>