<commit_before>#include "string_functions.h"
#include <sstream>
#include <regex>

StringListT fromRegistryString(const std::wstring &string, wchar_t separator)
{
	// tokenize using RegExp
	StringListT strList;
	std::wostringstream ss;
	ss << L"[^" << separator << L"]+";
	std::wregex reSeparator( ss.str());

	std::wsregex_token_iterator begin( string.begin(), string.end(), reSeparator);
	std::wsregex_token_iterator end;

	std::copy( begin, end, std::back_inserter( strList));
	strList.erase(std::remove_if(strList.begin(), strList.end(), [](const std::wstring str){
		return str.empty() || str[0] == 0; }), strList.end());
	return strList;
}

std::wstring toRegistryString(const StringListT &paths, wchar_t separator)
{
	std::wstring sSeparator( 1, separator);
	std::wostringstream ss;
	std::copy( paths.begin(), paths.end(), std::ostream_iterator<StringListT::value_type,
			   StringListT::value_type::value_type>( ss, sSeparator.c_str()));
	return ss.str();
}
<commit_msg>Cosmetics: avoid to use wostringstream<commit_after>#include "string_functions.h"
#include <sstream>
#include <regex>

StringListT fromRegistryString(const std::wstring &string, wchar_t separator)
{
	// tokenize using RegExp
	StringListT strList;

	std::wregex reSeparator(std::wstring(L"[^") + separator + std::wstring(L"]+"));
	std::wsregex_token_iterator begin( string.begin(), string.end(), reSeparator);
	std::wsregex_token_iterator end;

	std::copy( begin, end, std::back_inserter( strList));
	strList.erase(std::remove_if(strList.begin(), strList.end(), [](const std::wstring str){
		return str.empty() || str[0] == 0; }), strList.end());
	return strList;
}

std::wstring toRegistryString(const StringListT &paths, wchar_t separator)
{
	std::wstring sSeparator( 1, separator);
	std::wostringstream ss;
	std::copy( paths.begin(), paths.end(), std::ostream_iterator<StringListT::value_type,
			   StringListT::value_type::value_type>( ss, sSeparator.c_str()));
	return ss.str();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iterator>
#include <utility>
#include <deque>
#include <string>
#include <cstdlib>
#include "nfa.hxx"

extern int yyparse (void*);
extern FILE* yyin;
extern std::deque<std::string > qq;

/* Get set of input alphabet T from automaton's delta mapping. */
std::set<LetterT > input_alphabet (const NFA& nfa)
{
    std::set<LetterT> alphabet;
    for (DeltaMappingT::const_iterator i = nfa.delta.begin();
	 i != nfa.delta.end();
	 ++i) {
	for (StateDeltaT::const_iterator k = i->second.begin();
	     k != i->second.end();
	     ++k) {
	    alphabet.insert(k->first);
	}
    }
    return alphabet;
}

int main(int argc, char* argv[])
{
    /* Osetreni parametru vstupniho souboru */
    if (argc == 2) {
	if (!(yyin = fopen(argv[1],"r"))) {
	    perror("chyba fopen()");
	    exit(EXIT_FAILURE);
	}
    }
    else
	yyin = stdin;

    NFA nfa;
    NFA_conv nfa_conv;
    int ret = yyparse((void*)&nfa);
    if (ret == 1) {
	std::cerr << "chyba pri parsovani vstupu" << std::endl;
	std::copy(qq.begin(),qq.end(),
		  std::ostream_iterator<std::string >(std::cout," => "));
	exit(EXIT_FAILURE);
    }
    /* Testovaci vypis vstupniho automatu. */
    std::cout << "input:" << std::endl << printNFA(nfa) << std::endl;

    /* 1. The set Q' = {{q0}} will be defined, the state {q0} will be treated
       as unmarked. */
    std::set<LetterT > alphabet = input_alphabet(nfa);
    std::set<SetOfStatesT > Qnew, unmarked, marked;
    SetOfStatesT q0set;
    q0set.insert(nfa.initial);
    Qnew.insert(q0set);
    unmarked.insert(q0set);

    /* 2. If each state in Q' is marked, then continue with step (4). */
    while (! unmarked.empty()) {
	/* 3. An unmarked state q' will be chosen from Q' and th following
	   operations will be executed: */
	SetOfStatesT q_ = *unmarked.begin();
	/* (a) We will determine delta'(q',a) = union(delta(p,a)) for
	   p element q' and for all a element T. */
	StateDeltaT stdelta;
	int cnt = 0;
	for (std::set<LetterT >::const_iterator letter = alphabet.begin();
	     letter != alphabet.end();
	     ++letter) {
	    /* alokace promenne pro sjednoceni union(delta(p,a))
	       for p element q' */
	    SetOfStatesT* un = new SetOfStatesT;
	    int cnt2 = 0;
	    for (SetOfStatesT::const_iterator p = q_.begin();
		 p != q_.end();
		 ++p) {
		// najdi StateDeltaT pro stav
		DeltaMappingT::const_iterator dmi = nfa.delta.find(*p);
		// element nenalezen
		if (dmi == nfa.delta.end())
		    continue;
		const StateDeltaT& sd = dmi->second;
		/* najdi mnozinu cilovych stavu ze stavu *p pri
		   vstupnim pismenu *letter */
		StateDeltaT::const_iterator sdi = sd.find(*letter);
		// element nenalezen
		if (sdi == sd.end())
		    continue;
		un->insert(sdi->second.begin(), sdi->second.end());
	    }
	    stdelta.insert(make_pair(*letter,*un));
	    /* (b) Q' = Q' union delta'(q',a) for all a element T. */
	    Qnew.insert(*un);
	    /* pokud stav jeste neni oznaceny */
	    if (marked.find(*un) == marked.end())
		/* pridame ho k neoznacenym */
		unmarked.insert(*un);
	    /* (c) The state q' element Q' will be marked. */
	    unmarked.erase(q_);
	    marked.insert(q_);
	    /* (d) Continue with step (2). */
	}
	nfa_conv.delta.insert(make_pair(q_,stdelta));
    }

    nfa_conv.name = nfa.name;
    /* 4. q0' = {q0}. */
    nfa_conv.initial = q0set;
    /* 5. F' = {q' : q' element Q', q' intersection F != 0}. */
    for (std::set<SetOfStatesT >::const_iterator q_ = Qnew.begin();
	 q_ != Qnew.end();
	 ++q_) {
	// promenna pro prunik
	SetOfStatesT inter;
	set_intersection(q_->begin(), q_->end(),
			 nfa.final.begin(), nfa.final.end(),
			 std::insert_iterator<SetOfStatesT >(inter,
							     inter.begin()));
	if (! inter.empty())
	    nfa_conv.final.insert(*q_);
    }

    /* Testovaci vypis prevedeneho automatu */
    std::cout << "converted:" << std::endl << printNFA(nfa_conv) << std::endl;

    exit(EXIT_SUCCESS);
}
<commit_msg>Odstraneni prevodu z NFA do DFA a jeho presun do funkce nove Odstraneni prevodu z NFA do DFA a jeho presun do funkce nove nfa.cxx:convert_NFA2DFA(). Presun funkce input_alphabet() z nfa2dfa.cc do nfa.cxx. Odstraneni nepotrebne ladici promenne. Uprava komentaru.<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iterator>
#include <utility>
#include <deque>
#include <string>
#include <cstdlib>
#include "nfa.hxx"

extern int yyparse (void*);
extern FILE* yyin;

int main(int argc, char* argv[])
{
    /* Osetreni parametru vstupniho souboru */
    if (argc == 2) {
	if (!(yyin = fopen(argv[1],"r"))) {
	    perror("chyba fopen()");
	    exit(EXIT_FAILURE);
	}
    }
    else
	yyin = stdin;

    NFA nfa;
    int ret = yyparse((void*)&nfa);
    if (ret == 1) {
	std::cerr << "chyba pri parsovani vstupu" << std::endl;
	exit(EXIT_FAILURE);
    }
    /* Ladici vypis vstupniho automatu. */
    std::cout << "input:" << std::endl << printNFA(nfa) << std::endl;

    NFA_conv nfa_conv = convert_NFA2DFA(nfa);

    /* Ladici vypis prevedeneho automatu */
    std::cout << "converted:" << std::endl << printNFA(nfa_conv) << std::endl;

    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>/**
Software License Agreement (BSD)

\authors   Mike Purvis <mpurvis@clearpathrobotics.com>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the
   following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
   following disclaimer in the documentation and/or other materials provided with the distribution.
 * Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
   products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "geometry_msgs/Twist.h"
#include "ros/ros.h"
#include "sensor_msgs/Joy.h"
#include "teleop_twist_joy/teleop_twist_joy.h"

#include <map>
#include <string>

namespace teleop_twist_joy
{

/**
 * Internal members of class. This is the pimpl idiom, and allows more flexibility in adding
 * parameters later without breaking ABI compatibility, for robots which link TeleopTwistJoy
 * directly into base nodes.
 */
struct TeleopTwistJoy::Impl
{
  void joyCallback(const sensor_msgs::Joy::ConstPtr& joy);

  ros::Subscriber joy_sub;
  ros::Publisher cmd_vel_pub;

  int enable_button;
  int enable_turbo_button;

  std::map<std::string, int> axis_linear_map;
  std::map<std::string, double> scale_linear_map;
  std::map<std::string, double> scale_linear_turbo_map;

  std::map<std::string, int> axis_angular_map;
  std::map<std::string, double> scale_angular_map;
  std::map<std::string, double> scale_angular_turbo_map;

  bool sent_disable_msg;
};

/**
 * Constructs TeleopTwistJoy.
 * \param nh NodeHandle to use for setting up the publisher and subscriber.
 * \param nh_param NodeHandle to use for searching for configuration parameters.
 */
TeleopTwistJoy::TeleopTwistJoy(ros::NodeHandle* nh, ros::NodeHandle* nh_param)
{
  pimpl_ = new Impl;

  pimpl_->cmd_vel_pub = nh->advertise<geometry_msgs::Twist>("cmd_vel", 1, true);
  pimpl_->joy_sub = nh->subscribe<sensor_msgs::Joy>("joy", 1, &TeleopTwistJoy::Impl::joyCallback, pimpl_);

  nh_param->param<int>("enable_button", pimpl_->enable_button, 0);
  nh_param->param<int>("enable_turbo_button", pimpl_->enable_turbo_button, -1);

  if (nh_param->getParam("axis_linear", pimpl_->axis_linear_map))
  {
    nh_param->getParam("axis_linear", pimpl_->axis_linear_map);
    nh_param->getParam("scale_linear", pimpl_->scale_linear_map);
    nh_param->getParam("scale_linear_turbo", pimpl_->scale_linear_turbo_map);
  }
  else
  {
    nh_param->param<int>("axis_linear", pimpl_->axis_linear_map["x"], 1);
    nh_param->param<double>("scale_linear", pimpl_->scale_linear_map["x"], 0.5);
    nh_param->param<double>("scale_linear_turbo", pimpl_->scale_linear_turbo_map["x"], 1.0);
  }

  if (nh_param->getParam("axis_angular", pimpl_->axis_angular_map))
  {
    nh_param->getParam("axis_angular", pimpl_->axis_angular_map);
    nh_param->getParam("scale_angular", pimpl_->scale_angular_map);
  }
  else
  {
    nh_param->param<int>("axis_angular", pimpl_->axis_angular_map["yaw"], 0);
    nh_param->param<double>("scale_angular", pimpl_->scale_angular_map["yaw"], 0.5);
    nh_param->param<double>("scale_angular_turbo", pimpl_->scale_angular_turbo_map["yaw"], pimpl_->scale_angular_map["yaw"]);
  }

  ROS_INFO_NAMED("TeleopTwistJoy", "Teleop enable button %i.", pimpl_->enable_button);
  ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0, "TeleopTwistJoy",
      "Turbo on button %i.", pimpl_->enable_turbo_button);

  for (std::map<std::string, int>::iterator it = pimpl_->axis_linear_map.begin();
      it != pimpl_->axis_linear_map.end(); ++it)
  {
    ROS_INFO_NAMED("TeleopTwistJoy", "Linear axis %s on %i at scale %f.",
    it->first.c_str(), it->second, pimpl_->scale_linear_map[it->first]);
    ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0, "TeleopTwistJoy",
        "Turbo for linear axis %s is scale %f.", it->first.c_str(), pimpl_->scale_linear_turbo_map[it->first]);
  }

  for (std::map<std::string, int>::iterator it = pimpl_->axis_angular_map.begin();
      it != pimpl_->axis_angular_map.end(); ++it)
  {
    ROS_INFO_NAMED("TeleopTwistJoy", "Angular axis %s on %i at scale %f.",
    it->first.c_str(), it->second, pimpl_->scale_angular_map[it->first]);
  }

  pimpl_->sent_disable_msg = false;
}

void TeleopTwistJoy::Impl::joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg)
{
  // Initializes with zeros by default.
  geometry_msgs::Twist cmd_vel_msg;

  if (enable_turbo_button >= 0 && joy_msg->buttons[enable_turbo_button])
  {
    if (axis_linear_map.find("x") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.x = joy_msg->axes[axis_linear_map["x"]] * scale_linear_turbo_map["x"];
    }
    if (axis_linear_map.find("y") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.y = joy_msg->axes[axis_linear_map["y"]] * scale_linear_turbo_map["y"];
    }
    if  (axis_linear_map.find("z") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.z = joy_msg->axes[axis_linear_map["z"]] * scale_linear_turbo_map["z"];
    }
    if  (axis_angular_map.find("yaw") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.z = joy_msg->axes[axis_angular_map["yaw"]] * scale_angular_turbo_map["yaw"];
    }
    if  (axis_angular_map.find("pitch") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.y = joy_msg->axes[axis_angular_map["pitch"]] * scale_angular_turbo_map["pitch"];
    }
    if  (axis_angular_map.find("roll") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.x = joy_msg->axes[axis_angular_map["roll"]] * scale_angular_turbo_map["roll"];
    }

    cmd_vel_pub.publish(cmd_vel_msg);
    sent_disable_msg = false;
  }
  else if (joy_msg->buttons[enable_button])
  {
    if  (axis_linear_map.find("x") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.x = joy_msg->axes[axis_linear_map["x"]] * scale_linear_map["x"];
    }
    if  (axis_linear_map.find("x") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.y = joy_msg->axes[axis_linear_map["y"]] * scale_linear_map["y"];
    }
    if  (axis_linear_map.find("z") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.z = joy_msg->axes[axis_linear_map["z"]] * scale_linear_map["z"];
    }
    if  (axis_angular_map.find("yaw") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.z = joy_msg->axes[axis_angular_map["yaw"]] * scale_angular_map["yaw"];
    }
    if  (axis_angular_map.find("pitch") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.y = joy_msg->axes[axis_angular_map["pitch"]] * scale_angular_map["pitch"];
    }
    if  (axis_angular_map.find("roll") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.x = joy_msg->axes[axis_angular_map["roll"]] * scale_angular_map["roll"];
    }

    cmd_vel_pub.publish(cmd_vel_msg);
    sent_disable_msg = false;
  }
  else
  {
    // When enable button is released, immediately send a single no-motion command
    // in order to stop the robot.
    if (!sent_disable_msg)
    {
      cmd_vel_pub.publish(cmd_vel_msg);
      sent_disable_msg = true;
    }
  }
}

}  // namespace teleop_twist_joy
<commit_msg>Shorten long line that roslint didn't like.<commit_after>/**
Software License Agreement (BSD)

\authors   Mike Purvis <mpurvis@clearpathrobotics.com>
\copyright Copyright (c) 2014, Clearpath Robotics, Inc., All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the
   following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
   following disclaimer in the documentation and/or other materials provided with the distribution.
 * Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote
   products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "geometry_msgs/Twist.h"
#include "ros/ros.h"
#include "sensor_msgs/Joy.h"
#include "teleop_twist_joy/teleop_twist_joy.h"

#include <map>
#include <string>

namespace teleop_twist_joy
{

/**
 * Internal members of class. This is the pimpl idiom, and allows more flexibility in adding
 * parameters later without breaking ABI compatibility, for robots which link TeleopTwistJoy
 * directly into base nodes.
 */
struct TeleopTwistJoy::Impl
{
  void joyCallback(const sensor_msgs::Joy::ConstPtr& joy);

  ros::Subscriber joy_sub;
  ros::Publisher cmd_vel_pub;

  int enable_button;
  int enable_turbo_button;

  std::map<std::string, int> axis_linear_map;
  std::map<std::string, double> scale_linear_map;
  std::map<std::string, double> scale_linear_turbo_map;

  std::map<std::string, int> axis_angular_map;
  std::map<std::string, double> scale_angular_map;
  std::map<std::string, double> scale_angular_turbo_map;

  bool sent_disable_msg;
};

/**
 * Constructs TeleopTwistJoy.
 * \param nh NodeHandle to use for setting up the publisher and subscriber.
 * \param nh_param NodeHandle to use for searching for configuration parameters.
 */
TeleopTwistJoy::TeleopTwistJoy(ros::NodeHandle* nh, ros::NodeHandle* nh_param)
{
  pimpl_ = new Impl;

  pimpl_->cmd_vel_pub = nh->advertise<geometry_msgs::Twist>("cmd_vel", 1, true);
  pimpl_->joy_sub = nh->subscribe<sensor_msgs::Joy>("joy", 1, &TeleopTwistJoy::Impl::joyCallback, pimpl_);

  nh_param->param<int>("enable_button", pimpl_->enable_button, 0);
  nh_param->param<int>("enable_turbo_button", pimpl_->enable_turbo_button, -1);

  if (nh_param->getParam("axis_linear", pimpl_->axis_linear_map))
  {
    nh_param->getParam("axis_linear", pimpl_->axis_linear_map);
    nh_param->getParam("scale_linear", pimpl_->scale_linear_map);
    nh_param->getParam("scale_linear_turbo", pimpl_->scale_linear_turbo_map);
  }
  else
  {
    nh_param->param<int>("axis_linear", pimpl_->axis_linear_map["x"], 1);
    nh_param->param<double>("scale_linear", pimpl_->scale_linear_map["x"], 0.5);
    nh_param->param<double>("scale_linear_turbo", pimpl_->scale_linear_turbo_map["x"], 1.0);
  }

  if (nh_param->getParam("axis_angular", pimpl_->axis_angular_map))
  {
    nh_param->getParam("axis_angular", pimpl_->axis_angular_map);
    nh_param->getParam("scale_angular", pimpl_->scale_angular_map);
  }
  else
  {
    nh_param->param<int>("axis_angular", pimpl_->axis_angular_map["yaw"], 0);
    nh_param->param<double>("scale_angular", pimpl_->scale_angular_map["yaw"], 0.5);
    nh_param->param<double>("scale_angular_turbo",
        pimpl_->scale_angular_turbo_map["yaw"], pimpl_->scale_angular_map["yaw"]);
  }

  ROS_INFO_NAMED("TeleopTwistJoy", "Teleop enable button %i.", pimpl_->enable_button);
  ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0, "TeleopTwistJoy",
      "Turbo on button %i.", pimpl_->enable_turbo_button);

  for (std::map<std::string, int>::iterator it = pimpl_->axis_linear_map.begin();
      it != pimpl_->axis_linear_map.end(); ++it)
  {
    ROS_INFO_NAMED("TeleopTwistJoy", "Linear axis %s on %i at scale %f.",
    it->first.c_str(), it->second, pimpl_->scale_linear_map[it->first]);
    ROS_INFO_COND_NAMED(pimpl_->enable_turbo_button >= 0, "TeleopTwistJoy",
        "Turbo for linear axis %s is scale %f.", it->first.c_str(), pimpl_->scale_linear_turbo_map[it->first]);
  }

  for (std::map<std::string, int>::iterator it = pimpl_->axis_angular_map.begin();
      it != pimpl_->axis_angular_map.end(); ++it)
  {
    ROS_INFO_NAMED("TeleopTwistJoy", "Angular axis %s on %i at scale %f.",
    it->first.c_str(), it->second, pimpl_->scale_angular_map[it->first]);
  }

  pimpl_->sent_disable_msg = false;
}

void TeleopTwistJoy::Impl::joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg)
{
  // Initializes with zeros by default.
  geometry_msgs::Twist cmd_vel_msg;

  if (enable_turbo_button >= 0 && joy_msg->buttons[enable_turbo_button])
  {
    if (axis_linear_map.find("x") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.x = joy_msg->axes[axis_linear_map["x"]] * scale_linear_turbo_map["x"];
    }
    if (axis_linear_map.find("y") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.y = joy_msg->axes[axis_linear_map["y"]] * scale_linear_turbo_map["y"];
    }
    if  (axis_linear_map.find("z") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.z = joy_msg->axes[axis_linear_map["z"]] * scale_linear_turbo_map["z"];
    }
    if  (axis_angular_map.find("yaw") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.z = joy_msg->axes[axis_angular_map["yaw"]] * scale_angular_turbo_map["yaw"];
    }
    if  (axis_angular_map.find("pitch") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.y = joy_msg->axes[axis_angular_map["pitch"]] * scale_angular_turbo_map["pitch"];
    }
    if  (axis_angular_map.find("roll") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.x = joy_msg->axes[axis_angular_map["roll"]] * scale_angular_turbo_map["roll"];
    }

    cmd_vel_pub.publish(cmd_vel_msg);
    sent_disable_msg = false;
  }
  else if (joy_msg->buttons[enable_button])
  {
    if  (axis_linear_map.find("x") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.x = joy_msg->axes[axis_linear_map["x"]] * scale_linear_map["x"];
    }
    if  (axis_linear_map.find("x") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.y = joy_msg->axes[axis_linear_map["y"]] * scale_linear_map["y"];
    }
    if  (axis_linear_map.find("z") != axis_linear_map.end())
    {
      cmd_vel_msg.linear.z = joy_msg->axes[axis_linear_map["z"]] * scale_linear_map["z"];
    }
    if  (axis_angular_map.find("yaw") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.z = joy_msg->axes[axis_angular_map["yaw"]] * scale_angular_map["yaw"];
    }
    if  (axis_angular_map.find("pitch") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.y = joy_msg->axes[axis_angular_map["pitch"]] * scale_angular_map["pitch"];
    }
    if  (axis_angular_map.find("roll") != axis_angular_map.end())
    {
      cmd_vel_msg.angular.x = joy_msg->axes[axis_angular_map["roll"]] * scale_angular_map["roll"];
    }

    cmd_vel_pub.publish(cmd_vel_msg);
    sent_disable_msg = false;
  }
  else
  {
    // When enable button is released, immediately send a single no-motion command
    // in order to stop the robot.
    if (!sent_disable_msg)
    {
      cmd_vel_pub.publish(cmd_vel_msg);
      sent_disable_msg = true;
    }
  }
}

}  // namespace teleop_twist_joy
<|endoftext|>


<commit_before>#include <memory>
#include <llvm/ADT/STLExtras.h>
#include "parser.hpp"

namespace llscm {
	using namespace std;
	using namespace llvm;

	void Parser::match(const Token & tok, const Token && expected) {
		if (tok != expected) {
			stringstream ss;
			ss << "Expected token \"" << expected.name << "\".";
			throw ParserException(ss.str());
		}
	}

	/*
	 * prog = form { form }
	 */
	vector<P_ScmObj> Parser::NT_Prog() {
		const Token * tok;
		vector<P_ScmObj> prog;

		while (true) {
			tok = reader->nextToken();
			// TODO: if (!tok) REPORT ERROR
			P_ScmObj form = NT_Form();
			if (!form) break;
			prog.push_back(move(form));
		}

		return prog;
	}

	/*
	 * form = "(" def ")" | expr
	 * def = "define" sym expr ...
	 * expr = atom | ( "(" list ")" )
	 */
	P_ScmObj Parser::NT_Form() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			tok = reader->nextToken();
			// TODO: if (!tok) REPORT ERROR
			if (tok->t == KWRD && tok->kw == KW_DEFINE) {
				// Current token is "define"
				obj = NT_Def();
			}
			else {
				// Current token is the first token of list
				obj = NT_List();
			}
			match(*reader->currToken(), Token(KW_RPAR));
			return obj;
		}
		// Anything other than "(" must be an atom
		return NT_Atom();
	}

	/*
	 * def = "define" sym expr
	 *		 | "define" "(" symlist ")" body
	 *		 | "let" "(" bindlist ")" body
	 */
	P_ScmObj Parser::NT_Def() {
		return nullptr;
	}

	/*
	 * expr = atom | ( "(" list ")" )
	 */
	P_ScmObj Parser::NT_Expr() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			tok = reader->nextToken();
			obj = NT_List();
			match(*reader->currToken(), Token(KW_RPAR));
			return obj;
		}
		return NT_Atom();
	}

	/*
	 * atom = str | sym | int | float | true | false | null
	 */
	P_ScmObj Parser::NT_Atom() {
		const Token * tok = reader->currToken();

		switch (tok->t) {
		case STR:
			return make_unique<ScmStr>(tok->name);
		case SYM:
			return make_unique<ScmSym>(tok->name);
		case INT:
			return make_unique<ScmInt>(tok->int_val);
		case FLOAT:
			return make_unique<ScmFloat>(tok->float_val);
		default:;
		}

		// TODO: if (tok->t != KWRD) REPORT ERROR
		switch (tok->kw) {
		case KW_TRUE:
			return make_unique<ScmTrue>();
		case KW_FALSE:
			return make_unique<ScmFalse>();
		case KW_NULL:
			return make_unique<ScmNull>();
		default:
			return nullptr; // TODO: REPORT ERROR (this would look like EOF)
		}
	}

	/*
	 * list = { expr }
	 */
	P_ScmObj Parser::NT_List() {
		// TODO: special cases: lambda, quote, if
		return nullptr;
	}

	/*
	 * symlist = { sym }
	 */
	P_ScmObj Parser::NT_SymList() {
		return nullptr;
	}

	/*
	 * bindlist = { "(" sym expr ")" }
	 */
	P_ScmObj Parser::NT_BindList() {
		return nullptr;
	}

	/*
	 * body = { def } expr { expr }
	 */
	P_ScmObj Parser::NT_Body() {
		return nullptr;
	}
};
<commit_msg>Added basic error handling to parser.<commit_after>#include <memory>
#include <llvm/ADT/STLExtras.h>
#include "parser.hpp"

namespace llscm {
	using namespace std;
	using namespace llvm;

	void Parser::match(const Token & tok, const Token && expected) {
		if (tok != expected) {
			stringstream ss;
			ss << "Expected token \"" << expected.name << "\".";
			throw ParserException(ss.str());
		}
	}

	/*
	 * prog = form { form }
	 */
	vector<P_ScmObj> Parser::NT_Prog() {
		const Token * tok;
		vector<P_ScmObj> prog;
		bool first = true;

		while (true) {
			tok = reader->nextToken();
			if (!tok) {
				if (first) throw ParserException("Program is empty.");
				else break;
			}
			P_ScmObj form = NT_Form();
			prog.push_back(move(form));
			first = false;
		}

		return prog;
	}

	/*
	 * form = "(" def ")" | expr
	 * def = "define" sym expr ...
	 * expr = atom | ( "(" list ")" )
	 */
	P_ScmObj Parser::NT_Form() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			tok = reader->nextToken();
			if (!tok) {
				throw ParserException("Reached EOF while parsing a list.");
			}
			if (tok->t == KWRD && tok->kw == KW_DEFINE) {
				// Current token is "define"
				obj = NT_Def();
			}
			else {
				// Current token is the first token of list
				obj = NT_List();
			}
			match(*reader->currToken(), Token(KW_RPAR));
			return obj;
		}
		// Anything other than "(" must be an atom
		return NT_Atom();
	}

	/*
	 * def = "define" sym expr
	 *		 | "define" "(" symlist ")" body
	 *		 | "let" "(" bindlist ")" body
	 */
	P_ScmObj Parser::NT_Def() {
		return nullptr;
	}

	/*
	 * expr = atom | ( "(" list ")" )
	 */
	P_ScmObj Parser::NT_Expr() {
		const Token * tok = reader->currToken();
		P_ScmObj obj;

		if (tok->t == KWRD && tok->kw == KW_LPAR) {
			tok = reader->nextToken();
			obj = NT_List();
			match(*reader->currToken(), Token(KW_RPAR));
			return obj;
		}
		return NT_Atom();
	}

	/*
	 * atom = str | sym | int | float | true | false | null
	 */
	P_ScmObj Parser::NT_Atom() {
		const Token * tok = reader->currToken();

		switch (tok->t) {
		case STR:
			return make_unique<ScmStr>(tok->name);
		case SYM:
			return make_unique<ScmSym>(tok->name);
		case INT:
			return make_unique<ScmInt>(tok->int_val);
		case FLOAT:
			return make_unique<ScmFloat>(tok->float_val);
		default:;
		}

		if (tok->t != KWRD) throw ParserException("Invalid token for an atom.");
		switch (tok->kw) {
		case KW_TRUE:
			return make_unique<ScmTrue>();
		case KW_FALSE:
			return make_unique<ScmFalse>();
		case KW_NULL:
			return make_unique<ScmNull>();
		default:
			throw ParserException("Invalid token for an atom.");
		}
	}

	/*
	 * list = { expr }
	 */
	P_ScmObj Parser::NT_List() {
		// TODO: special cases: lambda, quote, if
		return nullptr;
	}

	/*
	 * symlist = { sym }
	 */
	P_ScmObj Parser::NT_SymList() {
		return nullptr;
	}

	/*
	 * bindlist = { "(" sym expr ")" }
	 */
	P_ScmObj Parser::NT_BindList() {
		return nullptr;
	}

	/*
	 * body = { def } expr { expr }
	 */
	P_ScmObj Parser::NT_Body() {
		return nullptr;
	}
};
<|endoftext|>


<commit_before>#ifndef BFC_PARSER_HPP
#define BFC_PARSER_HPP

#include "lexer.hpp"
#include "result.hpp"
#include "ast.hpp"

namespace bfc {

template <class Source, class Traits = source_traits<Source>>
class Parser {

    public:

        using Lexer = lexer<Source, Traits>;

        Parser(Lexer lexer) : lexer(std::move(lexer)) {}

        ast_node parse() {
            /* create result to hold lexer result */
            result_type res = result_type::OK;
            /* create token to pass into lexer */
            token tok{};

            for(;;) {
                res = lexer.next(tok);
                switch (res) {
                    case result_type::OK:
                        updateAst(tok);
                        break;
                    case result_type::DONE:
                        ast_node program(new ast_program(tok.loc, astSeq));
                        return program;
                    case result_type::FAIL:
                    default:
                        break;
                }
            }
        }

    private:

        Lexer lexer;

        /* vector of instructions to return */
        ast_seq astSeq;

        ast_node updateLoop(source_loc loopPos){
            /* create result to hold lexer result */
            result_type res = result_type::OK;
            /* create token to pass into lexer */
            token tok;
            /* create vector to use to create ast_loop */
            ast_seq loopAst{};

            for(;;) {
                res = lexer.next(tok);
                token::type kind = tok.kind;
                source_loc loc = tok.loc;
                switch (res) {
                    case result_type::OK:
                        switch (kind) {
                            case token::INC:
                              {
                                ast_node add(new ast_add(loc, 0, 1));
                                loopAst.push_back(add);
                                break;
                              }
                            case token::DEC:
                              {
                                ast_node sub(new ast_sub(loc, 0, 1));
                                loopAst.push_back(sub);
                                break;
                              }
                            case token::MOVE_R:
                              {
                                ast_node move_r(new ast_move(loc, 1));
                                loopAst.push_back(move_r);
                                break;
                              }
                            case token::MOVE_L:
                              {
                                ast_node move_l(new ast_move(loc, -1));
                                loopAst.push_back(move_l);
                                break;
                              }
                            case token::LOOP_BEGIN:
                              {
                                ast_node innerLoop = updateLoop(loc);
                                loopAst.push_back(innerLoop);
                                break;
                              }
                            case token::LOOP_END:
                              {
                                ast_node loop(new ast_loop(loopPos, loopAst));
                                return loop;
                              }
                            case token::PUT_CHAR:
                              {
                                ast_node write(new ast_write(loc, 0));
                                loopAst.push_back(write);
                                break;
                              }
                            case token::GET_CHAR:
                              {
                                ast_node read(new ast_read(loc, 0));
                                loopAst.push_back(read);
                                break;
                              }
                            default:
                                break;
                        }
                        break; /* result_type::OK */
                    case result_type::DONE:
                    case result_type::FAIL:
                    default:
                        break;
                        // Throw Exception (ends without closing loop)
                }
            }
        }

        void updateAst(token &tok) {
            token::type kind = tok.kind;
            source_loc loc = tok.loc;

            switch (kind) {
                case token::INC:
                  {
                    ast_node add(new ast_add(loc, 0, 1));
                    astSeq.push_back(add);
                    break;
                  }
                case token::DEC:
                  {
                    ast_node sub(new ast_sub(loc, 0, 1));
                    astSeq.push_back(sub);
                    break;
                  }
                case token::MOVE_R:
                  {
                    ast_node move_r(new ast_move(loc, 1));
                    astSeq.push_back(move_r);
                    break;
                  }
                case token::MOVE_L:
                  {
                    ast_node move_l(new ast_move(loc, -1));
                    astSeq.push_back(move_l);
                    break;
                  }
                case token::LOOP_BEGIN:
                  {
                    ast_node loop = updateLoop(loc);
                    astSeq.push_back(loop);
                    break;
                  }
                case token::LOOP_END:
                    // Throw Exception (No open loop to close)
                  break;
                case token::PUT_CHAR:
                  {
                    ast_node write(new ast_write(loc, 0));
                    astSeq.push_back(write);
                    break;
                  }
                case token::GET_CHAR:
                  {
                    ast_node read(new ast_read(loc, 0));
                    astSeq.push_back(read);
                    break;
                  }
                default:
                    break;
            }
        }

};

}

#endif /* !BFC_PARSER_HPP */
<commit_msg>Rename parser and fix names in parser<commit_after>#ifndef BFC_PARSER_HPP
#define BFC_PARSER_HPP

#include "lexer.hpp"
#include "result.hpp"
#include "ast.hpp"

namespace bfc {

template <class Source, class Traits = source_traits<Source>>
class parser {

    public:

        using Lexer = lexer<Source, Traits>;

        parser(Lexer lexer) : lexer(std::move(lexer)) {}

        ast_node parse() {
            /* create result to hold lexer result */
            result_type res = result_type::OK;
            /* create token to pass into lexer */
            token tok{};

            for(;;) {
                res = lexer.next(tok);
                switch (res) {
                    case result_type::OK:
                        updateAst(tok);
                        break;
                    case result_type::DONE:
                        {
                        ast_node program(new ast_program(tok.loc, astSeq));
                        return program;
                        }
                    case result_type::FAIL:
                    default:
                        break;
                }
            }
        }

    private:

        Lexer lexer;

        /* vector of instructions to return */
        ast_seq astSeq;

        ast_node updateLoop(source_loc loopPos){
            /* create result to hold lexer result */
            result_type res = result_type::OK;
            /* create token to pass into lexer */
            token tok;
            /* create vector to use to create ast_loop */
            ast_seq loopAst{};

            for(;;) {
                res = lexer.next(tok);
                token::type kind = tok.kind;
                source_loc loc = tok.loc;
                switch (res) {
                    case result_type::OK:
                        switch (kind) {
                            case token::INC:
                              {
                                ast_node add(new ast_add(loc, 0, 1));
                                loopAst.push_back(add);
                                break;
                              }
                            case token::DEC:
                              {
                                ast_node sub(new ast_sub(loc, 0, 1));
                                loopAst.push_back(sub);
                                break;
                              }
                            case token::MOVE_R:
                              {
                                ast_node move_r(new ast_mov(loc, 1));
                                loopAst.push_back(move_r);
                                break;
                              }
                            case token::MOVE_L:
                              {
                                ast_node move_l(new ast_mov(loc, -1));
                                loopAst.push_back(move_l);
                                break;
                              }
                            case token::LOOP_BEGIN:
                              {
                                ast_node innerLoop = updateLoop(loc);
                                loopAst.push_back(innerLoop);
                                break;
                              }
                            case token::LOOP_END:
                              {
                                ast_node loop(new ast_loop(loopPos, loopAst));
                                return loop;
                              }
                            case token::PUT_CHAR:
                              {
                                ast_node write(new ast_write(loc, 0));
                                loopAst.push_back(write);
                                break;
                              }
                            case token::GET_CHAR:
                              {
                                ast_node read(new ast_read(loc, 0));
                                loopAst.push_back(read);
                                break;
                              }
                            default:
                                break;
                        }
                        break; /* result_type::OK */
                    case result_type::DONE:
                    case result_type::FAIL:
                    default:
                        break;
                        // Throw Exception (ends without closing loop)
                }
            }
        }

        void updateAst(token &tok) {
            token::type kind = tok.kind;
            source_loc loc = tok.loc;

            switch (kind) {
                case token::INC:
                  {
                    ast_node add(new ast_add(loc, 0, 1));
                    astSeq.push_back(add);
                    break;
                  }
                case token::DEC:
                  {
                    ast_node sub(new ast_sub(loc, 0, 1));
                    astSeq.push_back(sub);
                    break;
                  }
                case token::MOVE_R:
                  {
                    ast_node move_r(new ast_mov(loc, 1));
                    astSeq.push_back(move_r);
                    break;
                  }
                case token::MOVE_L:
                  {
                    ast_node move_l(new ast_mov(loc, -1));
                    astSeq.push_back(move_l);
                    break;
                  }
                case token::LOOP_BEGIN:
                  {
                    ast_node loop = updateLoop(loc);
                    astSeq.push_back(loop);
                    break;
                  }
                case token::LOOP_END:
                    // Throw Exception (No open loop to close)
                  break;
                case token::PUT_CHAR:
                  {
                    ast_node write(new ast_write(loc, 0));
                    astSeq.push_back(write);
                    break;
                  }
                case token::GET_CHAR:
                  {
                    ast_node read(new ast_read(loc, 0));
                    astSeq.push_back(read);
                    break;
                  }
                default:
                    break;
            }
        }

};

}

#endif /* !BFC_PARSER_HPP */
<|endoftext|>


<commit_before>#include <ph.h>
#include <chef.h>
#include <phstream.h>
#include <phAttrib.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <parma.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <pcu_io.h>
#include <string>
#include <stdlib.h>
#include <assert.h>
#include <iostream>

#define SIZET(a) static_cast<size_t>(a)

namespace {

void switchToMasters(int splitFactor)
{
  int self = PCU_Comm_Self();
  int groupRank = self / splitFactor;
  int group = self % splitFactor;
  MPI_Comm groupComm;
  MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
  PCU_Switch_Comm(groupComm);
}

void switchToAll()
{
  MPI_Comm prevComm = PCU_Get_Comm();
  PCU_Switch_Comm(MPI_COMM_WORLD);
  MPI_Comm_free(&prevComm);
  PCU_Barrier();
}

void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
  ph::loadModelAndBCs(in, g, bcs);
}

void originalMain(apf::Mesh2*& m, ph::Input& in,
    gmi_model* g, apf::Migration*& plan)
{
  if(!m)
    m = apf::loadMdsMesh(g, in.meshFileName.c_str());
  else
    apf::printStats(m);
  m->verify();
  if (in.solutionMigration && !in.useAttachedFields)
    ph::readAndAttachFields(in, m);
  else
    ph::attachZeroSolution(in, m);
  if (in.buildMapping)
    ph::buildMapping(m);
  apf::setMigrationLimit(SIZET(in.elementsPerMigration));
  if (in.adaptFlag)
    ph::adapt(in, m);
  if (in.tetrahedronize)
    ph::tetrahedronize(in, m);
  plan = ph::split(in, m);
}
/*
static FILE* openfile_read(ph::Input&, const char* path) {
  return pcu_group_open(path, false);
}

static FILE* openfile_write(ph::Output&, const char* path) {
  return pcu_group_open(path, true);
}

static FILE* openstream_write(ph::Output& out, const char* path) {
  return openGRStreamWrite(out.grs, path);
}

static FILE* openstream_read(ph::Input& in, const char* path) {
  std::string fname(path);
  std::string restartStr("restart");
  FILE* f = NULL;
  if( fname.find(restartStr) != std::string::npos )
    f = openRStreamRead(in.rs);
  else {
    fprintf(stderr,
      "ERROR %s type of stream %s is unknown... exiting\n",
      __func__, fname.c_str());
    exit(1);
  }
  return f;
}
*/
}//end namespace

namespace chef {
  static FILE* openfile_read(ph::Input&, const char* path) {
    return pcu_group_open(path, false);
  }

  static FILE* openfile_write(ph::Output&, const char* path) {
    return pcu_group_open(path, true);
  }

  static FILE* openstream_write(ph::Output& out, const char* path) {
    return openGRStreamWrite(out.grs, path);
  }

  static FILE* openstream_read(ph::Input& in, const char* path) {
    std::string fname(path);
    std::string restartStr("restart");
    FILE* f = NULL;
    if( fname.find(restartStr) != std::string::npos )
      f = openRStreamRead(in.rs);
    else {
      fprintf(stderr,
        "ERROR %s type of stream %s is unknown... exiting\n",
        __func__, fname.c_str());
      exit(1);
    }
    return f;
  }
}

namespace ph {
  void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters)
  {
    /* check if the mesh changed at all or balancing was requested */
    if ( (PCU_Comm_Peers()!=numMasters) ||
        in.adaptFlag ||
        in.prePhastaBalanceMethod != "none" ||
        in.tetrahedronize ||
        in.isReorder )
    {
      if (in.prePhastaBalanceMethod != "none" && PCU_Comm_Peers() > 1)
        ph::balance(in,m);
      apf::MeshTag* order = NULL;
      if (in.isReorder && PCU_Comm_Peers() > 1)
        order = Parma_BfsReorder(m);
      apf::reorderMdsMesh(m,order);
    }
  }

  void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) {
    if (in.adaptFlag)
      ph::goToStepDir(in.timeStepNumber);
    std::string path = ph::setupOutputDir();
    ph::setupOutputSubdir(path);
    ph::enterFilteredMatching(m, in, bcs);
    ph::generateOutput(in, bcs, m, out);
    ph::exitFilteredMatching(m);
    if ( ! in.outMeshFileName.empty() )
      m->writeNative(in.outMeshFileName.c_str());
    // a path is not needed for inmem
    ph::detachAndWriteSolution(in,out,m,path); //write restart
//<<<<<<< HEAD
// NOTE: KEEPING MY CONFLICTS
    if (in.adaptFlag && (in.timeStepNumber % in.writeVizFiles == 0) ) {
      // store the value of the function pointer
      FILE* (*fn)(Output& out, const char* path) = out.openfile_write;
      // set function pointer for file writing
      out.openfile_write = chef::openfile_write;
      writeGeomBC(out, path, in.timeStepNumber); //write geombc for viz only
      // reset the function pointer to the original value
      out.openfile_write = fn;
    }
    ph::writeGeomBC(out, path); //write geombc
    ph::writeAuxiliaryFiles(path, in.timeStepNumber);
//    if ( ! in.outMeshFileName.empty() )
//      m->writeNative(in.outMeshFileName.c_str());
/*=======
    // user requests files and chef is setup to write to streams
    if ( in.writePhastaFiles && out.openfile_write == chef::openstream_write ) {
      out.openfile_write = chef::openfile_write;
      ph::writeGeomBC(out, path); //write geombc
      out.openfile_write = chef::openstream_write;
    }
    ph::writeGeomBC(out, path); //write geombc
    ph::writeAuxiliaryFiles(path, in.timeStepNumber);
>>>>>>> upstream/master
 */
    m->verify();
    gmi_model* g = m->getModel();
    ph::clearAttAssociation(g,in);
    if (in.adaptFlag)
      ph::goToParentDir();
  }
  void preprocess(apf::Mesh2* m, Input& in, Output& out) {
    gmi_model* g = m->getModel();
    assert(g);
    BCs bcs;
    ph::readBCs(g, in.attributeFileName.c_str(), in.axisymmetry, bcs);
    if (!in.solutionMigration)
      ph::attachZeroSolution(in, m);
    if (in.buildMapping)
      ph::buildMapping(m);
    preprocess(m,in,out,bcs);
  }
}

namespace chef {
  void bake(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& in, ph::Output& out) {
    apf::Migration* plan = 0;
    ph::BCs bcs;
    loadCommon(in, bcs, g);
    const int worldRank = PCU_Comm_Self();
    switchToMasters(in.splitFactor);
    const int numMasters = PCU_Comm_Peers();
    if ((worldRank % in.splitFactor) == 0)
      originalMain(m, in, g, plan);
    switchToAll();
    m = repeatMdsMesh(m, g, plan, in.splitFactor);
    ph::balanceAndReorder(m,in,numMasters);
    ph::preprocess(m,in,out,bcs);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m) {
    ph::Input in;
    in.load("adapt.inp");
    in.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,in,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, GRStream* grs) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
    return;
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs, GRStream* grs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
    return;
  }

  void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) {
    ph::readAndAttachFields(ctrl, m);
  }

  void balanceAndReorder(ph::Input& ctrl, apf::Mesh2* m) {
    ph::balanceAndReorder(m,ctrl,PCU_Comm_Peers());
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in) {
    ph::Output out;
    out.openfile_write = openfile_write;
    ph::preprocess(m,in,out);
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) {
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    ph::preprocess(m,in,out);
  }
}

<commit_msg>remove non-namespaced version openfile/stream_read/write. remove commented lines.<commit_after>#include <ph.h>
#include <chef.h>
#include <phstream.h>
#include <phAttrib.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <parma.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <pcu_io.h>
#include <string>
#include <stdlib.h>
#include <assert.h>
#include <iostream>

#define SIZET(a) static_cast<size_t>(a)

namespace {

void switchToMasters(int splitFactor)
{
  int self = PCU_Comm_Self();
  int groupRank = self / splitFactor;
  int group = self % splitFactor;
  MPI_Comm groupComm;
  MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
  PCU_Switch_Comm(groupComm);
}

void switchToAll()
{
  MPI_Comm prevComm = PCU_Get_Comm();
  PCU_Switch_Comm(MPI_COMM_WORLD);
  MPI_Comm_free(&prevComm);
  PCU_Barrier();
}

void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
  ph::loadModelAndBCs(in, g, bcs);
}

void originalMain(apf::Mesh2*& m, ph::Input& in,
    gmi_model* g, apf::Migration*& plan)
{
  if(!m)
    m = apf::loadMdsMesh(g, in.meshFileName.c_str());
  else
    apf::printStats(m);
  m->verify();
  if (in.solutionMigration && !in.useAttachedFields)
    ph::readAndAttachFields(in, m);
  else
    ph::attachZeroSolution(in, m);
  if (in.buildMapping)
    ph::buildMapping(m);
  apf::setMigrationLimit(SIZET(in.elementsPerMigration));
  if (in.adaptFlag)
    ph::adapt(in, m);
  if (in.tetrahedronize)
    ph::tetrahedronize(in, m);
  plan = ph::split(in, m);
}

}//end namespace

namespace chef {
  static FILE* openfile_read(ph::Input&, const char* path) {
    return pcu_group_open(path, false);
  }

  static FILE* openfile_write(ph::Output&, const char* path) {
    return pcu_group_open(path, true);
  }

  static FILE* openstream_write(ph::Output& out, const char* path) {
    return openGRStreamWrite(out.grs, path);
  }

  static FILE* openstream_read(ph::Input& in, const char* path) {
    std::string fname(path);
    std::string restartStr("restart");
    FILE* f = NULL;
    if( fname.find(restartStr) != std::string::npos )
      f = openRStreamRead(in.rs);
    else {
      fprintf(stderr,
        "ERROR %s type of stream %s is unknown... exiting\n",
        __func__, fname.c_str());
      exit(1);
    }
    return f;
  }
}

namespace ph {
  void balanceAndReorder(apf::Mesh2* m, ph::Input& in, int numMasters)
  {
    /* check if the mesh changed at all or balancing was requested */
    if ( (PCU_Comm_Peers()!=numMasters) ||
        in.adaptFlag ||
        in.prePhastaBalanceMethod != "none" ||
        in.tetrahedronize ||
        in.isReorder )
    {
      if (in.prePhastaBalanceMethod != "none" && PCU_Comm_Peers() > 1)
        ph::balance(in,m);
      apf::MeshTag* order = NULL;
      if (in.isReorder && PCU_Comm_Peers() > 1)
        order = Parma_BfsReorder(m);
      apf::reorderMdsMesh(m,order);
    }
  }

  void preprocess(apf::Mesh2* m, Input& in, Output& out, BCs& bcs) {
    if (in.adaptFlag)
      ph::goToStepDir(in.timeStepNumber);
    std::string path = ph::setupOutputDir();
    ph::setupOutputSubdir(path);
    ph::enterFilteredMatching(m, in, bcs);
    ph::generateOutput(in, bcs, m, out);
    ph::exitFilteredMatching(m);
    if ( ! in.outMeshFileName.empty() )
      m->writeNative(in.outMeshFileName.c_str());
    // a path is not needed for inmem
    ph::detachAndWriteSolution(in,out,m,path); //write restart
//<<<<<<< HEAD
// NOTE: KEEPING MY CONFLICTS
    if (in.adaptFlag && (in.timeStepNumber % in.writeVizFiles == 0) ) {
      // store the value of the function pointer
      FILE* (*fn)(Output& out, const char* path) = out.openfile_write;
      // set function pointer for file writing
      out.openfile_write = chef::openfile_write;
      writeGeomBC(out, path, in.timeStepNumber); //write geombc for viz only
      // reset the function pointer to the original value
      out.openfile_write = fn;
    }
    ph::writeGeomBC(out, path); //write geombc
    ph::writeAuxiliaryFiles(path, in.timeStepNumber);
//    if ( ! in.outMeshFileName.empty() )
//      m->writeNative(in.outMeshFileName.c_str());
/*=======
    // user requests files and chef is setup to write to streams
    if ( in.writePhastaFiles && out.openfile_write == chef::openstream_write ) {
      out.openfile_write = chef::openfile_write;
      ph::writeGeomBC(out, path); //write geombc
      out.openfile_write = chef::openstream_write;
    }
    ph::writeGeomBC(out, path); //write geombc
    ph::writeAuxiliaryFiles(path, in.timeStepNumber);
>>>>>>> upstream/master
 */
    m->verify();
    gmi_model* g = m->getModel();
    ph::clearAttAssociation(g,in);
    if (in.adaptFlag)
      ph::goToParentDir();
  }
  void preprocess(apf::Mesh2* m, Input& in, Output& out) {
    gmi_model* g = m->getModel();
    assert(g);
    BCs bcs;
    ph::readBCs(g, in.attributeFileName.c_str(), in.axisymmetry, bcs);
    if (!in.solutionMigration)
      ph::attachZeroSolution(in, m);
    if (in.buildMapping)
      ph::buildMapping(m);
    preprocess(m,in,out,bcs);
  }
}

namespace chef {
  void bake(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& in, ph::Output& out) {
    apf::Migration* plan = 0;
    ph::BCs bcs;
    loadCommon(in, bcs, g);
    const int worldRank = PCU_Comm_Self();
    switchToMasters(in.splitFactor);
    const int numMasters = PCU_Comm_Peers();
    if ((worldRank % in.splitFactor) == 0)
      originalMain(m, in, g, plan);
    switchToAll();
    m = repeatMdsMesh(m, g, plan, in.splitFactor);
    ph::balanceAndReorder(m,in,numMasters);
    ph::preprocess(m,in,out,bcs);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m) {
    ph::Input in;
    in.load("adapt.inp");
    in.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,in,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, GRStream* grs) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
    return;
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs, GRStream* grs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
    return;
  }

  void readAndAttachFields(ph::Input& ctrl, apf::Mesh2*& m) {
    ph::readAndAttachFields(ctrl, m);
  }

  void balanceAndReorder(ph::Input& ctrl, apf::Mesh2* m) {
    ph::balanceAndReorder(m,ctrl,PCU_Comm_Peers());
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in) {
    ph::Output out;
    out.openfile_write = openfile_write;
    ph::preprocess(m,in,out);
  }

  void preprocess(apf::Mesh2*& m, ph::Input& in, GRStream* grs) {
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    ph::preprocess(m,in,out);
  }
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbQtFileSelectionWidget.h"

namespace otb
{
namespace Wrapper
{

QtFileSelectionWidget::QtFileSelectionWidget()
  : QWidget()
{
  this->DoCreateWidget();
}

QtFileSelectionWidget::~QtFileSelectionWidget()
{
}

void QtFileSelectionWidget::DoUpdateGUI()
{

}

void QtFileSelectionWidget::DoCreateWidget()
{
  unsigned int sp = 2;
  // Set up input text edit
  m_HLayout = new QHBoxLayout;
  m_HLayout->setSpacing(sp);
  m_HLayout->setContentsMargins(sp, sp, sp, sp);

  m_Checkbox = new QCheckBox();
  m_HLayout->addWidget(m_Checkbox);

  m_Input = new QLineEdit;

  m_HLayout->addWidget(m_Input);

  // Set up input text edit
  m_Button = new QPushButton;
  m_Button->setText("...");
  m_Button->setToolTip("Select file...");
  m_Button->setFixedWidth(30);

  connect( m_Button, SIGNAL(clicked()), this, SLOT(SelectFile()) );
  m_HLayout->addWidget(m_Button);

  this->setLayout(m_HLayout);
}

void QtFileSelectionWidget::SelectFile()
{
  QFileDialog fileDialog;
  fileDialog.setConfirmOverwrite(true);
  fileDialog.setFileMode(QFileDialog::ExistingFile);
  fileDialog.setNameFilter("Raster files (*)");

  if (fileDialog.exec())
    {
    QString filemane(fileDialog.selectedFiles().at(0));
    m_Input->setText(filemane);
    }
}

}
}
<commit_msg>ENH: Message enhancement<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbQtFileSelectionWidget.h"

namespace otb
{
namespace Wrapper
{

QtFileSelectionWidget::QtFileSelectionWidget()
  : QWidget()
{
  this->DoCreateWidget();
}

QtFileSelectionWidget::~QtFileSelectionWidget()
{
}

void QtFileSelectionWidget::DoUpdateGUI()
{

}

void QtFileSelectionWidget::DoCreateWidget()
{
  unsigned int sp = 2;
  // Set up input text edit
  m_HLayout = new QHBoxLayout;
  m_HLayout->setSpacing(sp);
  m_HLayout->setContentsMargins(sp, sp, sp, sp);

  m_Checkbox = new QCheckBox();
  m_HLayout->addWidget(m_Checkbox);

  m_Input = new QLineEdit;
  m_HLayout->addWidget(m_Input);

  // Set up input text edit
  m_Button = new QPushButton;
  m_Button->setText("...");
  m_Button->setToolTip("Select file...");
  m_Button->setFixedWidth(30);

  connect( m_Button, SIGNAL(clicked()), this, SLOT(SelectFile()) );
  m_HLayout->addWidget(m_Button);

  this->setLayout(m_HLayout);
}

void QtFileSelectionWidget::SelectFile()
{
  QFileDialog fileDialog;
  fileDialog.setConfirmOverwrite(true);
  fileDialog.setFileMode(QFileDialog::ExistingFile);
  fileDialog.setNameFilter("All files (*)");

  if (fileDialog.exec())
    {
    QString filemane(fileDialog.selectedFiles().at(0));
    m_Input->setText(filemane);
    }
}

}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/animation/ActiveAnimations.h"

#include "core/rendering/RenderObject.h"

namespace WebCore {

bool shouldCompositeForActiveAnimations(const RenderObject& renderer)
{
    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());

    if (!renderer.node() || !renderer.node()->isElementNode())
        return false;

    const Element* element = toElement(renderer.node());
    if (const ActiveAnimations* activeAnimations = element->activeAnimations()) {
        if (activeAnimations->hasActiveAnimations(CSSPropertyOpacity)
            || activeAnimations->hasActiveAnimations(CSSPropertyWebkitTransform)
            || activeAnimations->hasActiveAnimations(CSSPropertyWebkitFilter))
            return true;
    }

    return false;
}

bool hasActiveAnimations(const RenderObject& renderer, CSSPropertyID property)
{
    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());

    if (!renderer.node() || !renderer.node()->isElementNode())
        return false;

    const Element* element = toElement(renderer.node());
    if (const ActiveAnimations* activeAnimations = element->activeAnimations())
        return activeAnimations->hasActiveAnimations(property);

    return false;
}

bool hasActiveAnimationsOnCompositor(const RenderObject& renderer, CSSPropertyID property)
{
    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());

    if (!renderer.node() || !renderer.node()->isElementNode())
        return false;

    const Element* element = toElement(renderer.node());
    if (const ActiveAnimations* activeAnimations = element->activeAnimations())
        return activeAnimations->hasActiveAnimationsOnCompositor(property);

    return false;
}

bool ActiveAnimations::hasActiveAnimations(CSSPropertyID property) const
{
    return m_defaultStack.affects(property);
}

bool ActiveAnimations::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
{
    return m_defaultStack.hasActiveAnimationsOnCompositor(property);
}

void ActiveAnimations::cancelAnimationOnCompositor()
{
    for (PlayerSet::iterator it = m_players.begin(); it != players().end(); ++it)
        it->key->cancelAnimationOnCompositor();
}

} // namespace WebCore
<commit_msg>Remove bogus ASSERT<commit_after>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/animation/ActiveAnimations.h"

#include "core/rendering/RenderObject.h"

namespace WebCore {

bool shouldCompositeForActiveAnimations(const RenderObject& renderer)
{
    if (!renderer.node() || !renderer.node()->isElementNode())
        return false;

    const Element* element = toElement(renderer.node());
    if (const ActiveAnimations* activeAnimations = element->activeAnimations()) {
        if (activeAnimations->hasActiveAnimations(CSSPropertyOpacity)
            || activeAnimations->hasActiveAnimations(CSSPropertyWebkitTransform)
            || activeAnimations->hasActiveAnimations(CSSPropertyWebkitFilter))
            return true;
    }

    return false;
}

bool hasActiveAnimations(const RenderObject& renderer, CSSPropertyID property)
{
    if (!renderer.node() || !renderer.node()->isElementNode())
        return false;

    const Element* element = toElement(renderer.node());
    if (const ActiveAnimations* activeAnimations = element->activeAnimations())
        return activeAnimations->hasActiveAnimations(property);

    return false;
}

bool hasActiveAnimationsOnCompositor(const RenderObject& renderer, CSSPropertyID property)
{
    if (!renderer.node() || !renderer.node()->isElementNode())
        return false;

    const Element* element = toElement(renderer.node());
    if (const ActiveAnimations* activeAnimations = element->activeAnimations())
        return activeAnimations->hasActiveAnimationsOnCompositor(property);

    return false;
}

bool ActiveAnimations::hasActiveAnimations(CSSPropertyID property) const
{
    return m_defaultStack.affects(property);
}

bool ActiveAnimations::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
{
    return m_defaultStack.hasActiveAnimationsOnCompositor(property);
}

void ActiveAnimations::cancelAnimationOnCompositor()
{
    for (PlayerSet::iterator it = m_players.begin(); it != players().end(); ++it)
        it->key->cancelAnimationOnCompositor();
}

} // namespace WebCore
<|endoftext|>


<commit_before>/* Copyright 2019 Google LLC. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <iostream>

#include "ruy.h"

void ExampleMulFloat(ruy::Context *context) {
  const float lhs_data[] = {1, 2, 3, 4};
  const float rhs_data[] = {1, 2, 3, 4};
  float dst_data[4];

  ruy::Matrix<float> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  ruy::Matrix<float> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  ruy::Matrix<float> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;

  ruy::BasicSpec<float, float> spec;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, float:\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

void ExampleMulFloatWithBiasAddAndClamp(ruy::Context *context) {
  const float lhs_data[] = {1, 2, 3, 4};
  const float rhs_data[] = {1, 2, 3, 4};
  const float bias_data[] = {1, 0};
  float dst_data[4];

  ruy::Matrix<float> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  ruy::Matrix<float> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  ruy::Matrix<float> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;

  ruy::BasicSpec<float, float> spec;
  spec.bias = bias_data;
  spec.clamp_min = 0;
  spec.clamp_max = 15;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, float with bias addition and clamp:\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

void ExampleMulUint8Quantized(ruy::Context *context) {
  const std::uint8_t lhs_data[] = {1, 2, 3, 4};
  const std::uint8_t rhs_data[] = {1, 2, 3, 4};
  std::uint8_t dst_data[4];

  ruy::Matrix<std::uint8_t> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  ruy::Matrix<std::uint8_t> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  ruy::Matrix<std::uint8_t> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;

  ruy::BasicSpec<std::int32_t, std::uint8_t> spec;
  spec.multiplier_fixedpoint = 1 << 30;
  spec.multiplier_exponent = 0;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, uint8 quantized:\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

void ExampleMulUint8QuantizedWithZeroPoints(ruy::Context *context) {
  const std::uint8_t lhs_data[] = {1, 2, 3, 4};
  const std::uint8_t rhs_data[] = {1, 2, 3, 4};
  std::uint8_t dst_data[4];

  ruy::Matrix<std::uint8_t> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  lhs.zero_point = 2;
  ruy::Matrix<std::uint8_t> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  rhs.zero_point = 3;
  ruy::Matrix<std::uint8_t> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;
  dst.zero_point = 1;

  ruy::BasicSpec<std::int32_t, std::uint8_t> spec;
  spec.multiplier_fixedpoint = 1 << 30;
  spec.multiplier_exponent = 0;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, uint8 quantized with zero_point's:\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

void ExampleMulInt8PerChannelQuantized(ruy::Context *context) {
  const std::int8_t lhs_data[] = {1, 2, 3, 4};
  const std::int8_t rhs_data[] = {1, 2, 3, 4};
  const std::int32_t multiplier_data[] = {3 << 28, 5 << 28};
  const int exponent_data[] = {1, -2};
  std::int8_t dst_data[4];

  ruy::Matrix<std::int8_t> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  ruy::Matrix<std::int8_t> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  ruy::Matrix<std::int8_t> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;

  ruy::BasicSpec<std::int32_t, std::uint8_t> spec;
  spec.multiplier_fixedpoint_perchannel = multiplier_data;
  spec.multiplier_exponent_perchannel = exponent_data;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, int8 quantized with per-channel multipliers\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

int main() {
  ruy::Context context;
  ExampleMulFloat(&context);
  ExampleMulFloatWithBiasAddAndClamp(&context);
  ExampleMulUint8Quantized(&context);
  ExampleMulUint8QuantizedWithZeroPoints(&context);
  ExampleMulInt8PerChannelQuantized(&context);
}
<commit_msg>Unbreak example.cc: it was running into the recently added assertion against both zero points being the minimum representable value.<commit_after>/* Copyright 2019 Google LLC. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <iostream>

#include "ruy.h"

void ExampleMulFloat(ruy::Context *context) {
  const float lhs_data[] = {1, 2, 3, 4};
  const float rhs_data[] = {1, 2, 3, 4};
  float dst_data[4];

  ruy::Matrix<float> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  ruy::Matrix<float> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  ruy::Matrix<float> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;

  ruy::BasicSpec<float, float> spec;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, float:\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

void ExampleMulFloatWithBiasAddAndClamp(ruy::Context *context) {
  const float lhs_data[] = {1, 2, 3, 4};
  const float rhs_data[] = {1, 2, 3, 4};
  const float bias_data[] = {1, 0};
  float dst_data[4];

  ruy::Matrix<float> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  ruy::Matrix<float> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  ruy::Matrix<float> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;

  ruy::BasicSpec<float, float> spec;
  spec.bias = bias_data;
  spec.clamp_min = 0;
  spec.clamp_max = 15;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, float with bias addition and clamp:\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

void ExampleMulUint8AsymmetricQuantized(ruy::Context *context) {
  const std::uint8_t lhs_data[] = {124, 125, 126, 127};
  const std::uint8_t rhs_data[] = {129, 130, 131, 132};
  std::uint8_t dst_data[4];

  ruy::Matrix<std::uint8_t> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  lhs.zero_point = 125;
  ruy::Matrix<std::uint8_t> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  rhs.zero_point = 132;
  ruy::Matrix<std::uint8_t> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;
  dst.zero_point = 129;

  ruy::BasicSpec<std::int32_t, std::uint8_t> spec;
  spec.multiplier_fixedpoint = 1 << 30;
  spec.multiplier_exponent = 0;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, uint8 quantized with asymmetric zero points:\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}
void ExampleMulInt8PerChannelQuantized(ruy::Context *context) {
  const std::int8_t lhs_data[] = {1, 2, 3, 4};
  const std::int8_t rhs_data[] = {1, 2, 3, 4};
  const std::int32_t multiplier_data[] = {3 << 28, 5 << 28};
  const int exponent_data[] = {1, -2};
  std::int8_t dst_data[4];

  ruy::Matrix<std::int8_t> lhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kRowMajor, &lhs.layout);
  lhs.data = lhs_data;
  ruy::Matrix<std::int8_t> rhs;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &rhs.layout);
  rhs.data = rhs_data;
  ruy::Matrix<std::int8_t> dst;
  ruy::MakeSimpleLayout(2, 2, ruy::Order::kColMajor, &dst.layout);
  dst.data = dst_data;

  ruy::BasicSpec<std::int32_t, std::uint8_t> spec;
  spec.multiplier_fixedpoint_perchannel = multiplier_data;
  spec.multiplier_exponent_perchannel = exponent_data;
  ruy::Mul<ruy::kAllPaths>(lhs, rhs, spec, context, &dst);

  std::cout << "Example Mul, int8 quantized with per-channel multipliers\n";
  std::cout << "LHS:\n" << lhs;
  std::cout << "RHS:\n" << rhs;
  std::cout << "Result:\n" << dst << "\n";
}

int main() {
  ruy::Context context;
  ExampleMulFloat(&context);
  ExampleMulFloatWithBiasAddAndClamp(&context);
  ExampleMulUint8AsymmetricQuantized(&context);
  ExampleMulInt8PerChannelQuantized(&context);
}
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "core/dom/ChildFrameDisconnector.h"

#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "wtf/Assertions.h"

namespace WebCore {

#ifndef NDEBUG
static unsigned checkConnectedSubrameCountIsConsistent(Node&);
#endif

void ChildFrameDisconnector::disconnect(DisconnectPolicy policy)
{
#ifndef NDEBUG
    checkConnectedSubrameCountIsConsistent(m_root);
#endif

    if (!m_root.connectedSubframeCount())
        return;

    if (policy == RootAndDescendants) {
        collectFrameOwners(m_root);
    } else {
        for (Node* child = m_root.firstChild(); child; child = child->nextSibling())
            collectFrameOwners(*child);
    }

    disconnectCollectedFrameOwners();
}

void ChildFrameDisconnector::collectFrameOwners(Node& root)
{
    if (!root.connectedSubframeCount())
        return;

    if (root.isHTMLElement() && root.isFrameOwnerElement())
        m_frameOwners.append(&toHTMLFrameOwnerElement(root));

    for (Node* child = root.firstChild(); child; child = child->nextSibling())
        collectFrameOwners(*child);

    ElementShadow* shadow = root.isElementNode() ? toElement(root).shadow() : 0;
    if (shadow)
        collectFrameOwners(*shadow);
}

void ChildFrameDisconnector::disconnectCollectedFrameOwners()
{
    // Must disable frame loading in the subtree so an unload handler cannot
    // insert more frames and create loaded frames in detached subtrees.
    SubframeLoadingDisabler disabler(m_root);

    for (unsigned i = 0; i < m_frameOwners.size(); ++i) {
        HTMLFrameOwnerElement* owner = m_frameOwners[i].get();
        // Don't need to traverse up the tree for the first owner since no
        // script could have moved it.
        if (!i || m_root.containsIncludingShadowDOM(owner))
            owner->disconnectContentFrame();
    }
}

void ChildFrameDisconnector::collectFrameOwners(ElementShadow& shadow)
{
    for (ShadowRoot* root = shadow.youngestShadowRoot(); root; root = root->olderShadowRoot())
        collectFrameOwners(*root);
}

#ifndef NDEBUG
static unsigned checkConnectedSubrameCountIsConsistent(Node& node)
{
    unsigned count = 0;

    if (node.isElementNode()) {
        if (node.isFrameOwnerElement() && toHTMLFrameOwnerElement(node).contentFrame())
            count++;

        if (ElementShadow* shadow = toElement(node).shadow()) {
            for (ShadowRoot* root = shadow->youngestShadowRoot(); root; root = root->olderShadowRoot())
                count += checkConnectedSubrameCountIsConsistent(*root);
        }
    }

    for (Node* child = node.firstChild(); child; child = child->nextSibling())
        count += checkConnectedSubrameCountIsConsistent(*child);

    // If we undercount there's possibly a security bug since we'd leave frames
    // in subtrees outside the document.
    ASSERT(node.connectedSubframeCount() >= count);

    // If we overcount it's safe, but not optimal because it means we'll traverse
    // through the document in ChildFrameDisconnector looking for frames that have
    // already been disconnected.
    ASSERT(node.connectedSubframeCount() == count);

    return count;
}
#endif

}
<commit_msg>Fix typo checkConnectedSubf(r)ameCountIsConsistent<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "core/dom/ChildFrameDisconnector.h"

#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "wtf/Assertions.h"

namespace WebCore {

#ifndef NDEBUG
static unsigned checkConnectedSubframeCountIsConsistent(Node&);
#endif

void ChildFrameDisconnector::disconnect(DisconnectPolicy policy)
{
#ifndef NDEBUG
    checkConnectedSubframeCountIsConsistent(m_root);
#endif

    if (!m_root.connectedSubframeCount())
        return;

    if (policy == RootAndDescendants) {
        collectFrameOwners(m_root);
    } else {
        for (Node* child = m_root.firstChild(); child; child = child->nextSibling())
            collectFrameOwners(*child);
    }

    disconnectCollectedFrameOwners();
}

void ChildFrameDisconnector::collectFrameOwners(Node& root)
{
    if (!root.connectedSubframeCount())
        return;

    if (root.isHTMLElement() && root.isFrameOwnerElement())
        m_frameOwners.append(&toHTMLFrameOwnerElement(root));

    for (Node* child = root.firstChild(); child; child = child->nextSibling())
        collectFrameOwners(*child);

    ElementShadow* shadow = root.isElementNode() ? toElement(root).shadow() : 0;
    if (shadow)
        collectFrameOwners(*shadow);
}

void ChildFrameDisconnector::disconnectCollectedFrameOwners()
{
    // Must disable frame loading in the subtree so an unload handler cannot
    // insert more frames and create loaded frames in detached subtrees.
    SubframeLoadingDisabler disabler(m_root);

    for (unsigned i = 0; i < m_frameOwners.size(); ++i) {
        HTMLFrameOwnerElement* owner = m_frameOwners[i].get();
        // Don't need to traverse up the tree for the first owner since no
        // script could have moved it.
        if (!i || m_root.containsIncludingShadowDOM(owner))
            owner->disconnectContentFrame();
    }
}

void ChildFrameDisconnector::collectFrameOwners(ElementShadow& shadow)
{
    for (ShadowRoot* root = shadow.youngestShadowRoot(); root; root = root->olderShadowRoot())
        collectFrameOwners(*root);
}

#ifndef NDEBUG
static unsigned checkConnectedSubframeCountIsConsistent(Node& node)
{
    unsigned count = 0;

    if (node.isElementNode()) {
        if (node.isFrameOwnerElement() && toHTMLFrameOwnerElement(node).contentFrame())
            count++;

        if (ElementShadow* shadow = toElement(node).shadow()) {
            for (ShadowRoot* root = shadow->youngestShadowRoot(); root; root = root->olderShadowRoot())
                count += checkConnectedSubframeCountIsConsistent(*root);
        }
    }

    for (Node* child = node.firstChild(); child; child = child->nextSibling())
        count += checkConnectedSubframeCountIsConsistent(*child);

    // If we undercount there's possibly a security bug since we'd leave frames
    // in subtrees outside the document.
    ASSERT(node.connectedSubframeCount() >= count);

    // If we overcount it's safe, but not optimal because it means we'll traverse
    // through the document in ChildFrameDisconnector looking for frames that have
    // already been disconnected.
    ASSERT(node.connectedSubframeCount() == count);

    return count;
}
#endif

}
<|endoftext|>


<commit_before>#include "papipp.h"

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    papi::event_set<PAPI_TOT_INS, PAPI_TOT_CYC, PAPI_BR_MSP, PAPI_L1_DCM> events;
    events.start_counters();

    {
        std::vector<int> v = {{11, 7, 5, 3, 1}};
        std::sort(std::begin(v), std::end(v));
    }

    events.stop_counters();

    // accessing counters via at<EventIndex>()
    std::cout << events.at<0>().counter() / static_cast<double>(events.at<1>().counter()) << " insns per cycle\n";

    // or via .get<EventCode>()
    std::cout << events.get<PAPI_L1_DCM>().counter() << " l1 dcache misses\n"
              << events.get<PAPI_BR_MSP>().counter() << " branch misses" << std::endl;

    return 0;
}
<commit_msg>updating example<commit_after>#include "papipp.h"

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    papi::event_set<PAPI_TOT_INS, PAPI_TOT_CYC, PAPI_BR_MSP, PAPI_L1_DCM> events;
    events.start_counters();

    {
        std::vector<int> v = {{11, 7, 5, 3, 1}};
        std::sort(std::begin(v), std::end(v));
    }

    events.stop_counters();

    // accessing counters via at<EventIndex>()
    std::cout << events.at<0>().counter() / static_cast<double>(events.at<1>().counter()) << " insns per cycle\n";

    // or via .get<EventCode>()
    std::cout << events.get<PAPI_L1_DCM>().counter() << " l1 dcache misses\n"
              << events.get<PAPI_BR_MSP>().counter() << " branch misses" << std::endl;

    std::cout << events <<std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef POSTGIS_CONNECTION_HPP
#define POSTGIS_CONNECTION_HPP

// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/timer.hpp>

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

// std
#include <sstream>
#include <iostream>

extern "C" {
#include "libpq-fe.h"
}

#include "resultset.hpp"

class Connection
{
public:
    Connection(std::string const& connection_str)
        : cursorId(0),
          closed_(false)
    {
        conn_ = PQconnectdb(connection_str.c_str());
        if (PQstatus(conn_) != CONNECTION_OK)
        {
            std::ostringstream s;
            s << "Postgis Plugin: ";
            if (conn_ )
            {
                std::string msg = PQerrorMessage(conn_);
                if (! msg.empty())
                {
                    s << msg.substr(0, msg.size() - 1);
                }
                else
                {
                    s << "unable to connect to postgres server";
                }
            }
            else
            {
                s << "unable to connect to postgres server";
            }
            s << "\n" << connection_str;

            throw mapnik::datasource_exception(s.str());
        }
    }

    ~Connection()
    {
        if (! closed_)
        {
            PQfinish(conn_);

            MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: postgresql connection closed - " << conn_;

            closed_ = true;
        }
    }

    bool execute(std::string const& sql) const
    {
#ifdef MAPNIK_STATS
        mapnik::progress_timer __stats__(std::clog, std::string("postgis_connection::execute ") + sql);
#endif

        PGresult *result = PQexec(conn_, sql.c_str());
        bool ok = (result && (PQresultStatus(result) == PGRES_COMMAND_OK));
        PQclear(result);
        return ok;
    }

    boost::shared_ptr<ResultSet> executeQuery(std::string const& sql, int type = 0) const
    {
#ifdef MAPNIK_STATS
        mapnik::progress_timer __stats__(std::clog, std::string("postgis_connection::execute_query ") + sql);
#endif

        PGresult* result = 0;
        if (type == 1)
        {
            result = PQexecParams(conn_,sql.c_str(), 0, 0, 0, 0, 0, 1);
        }
        else
        {
            result = PQexec(conn_, sql.c_str());
        }

        if (! result || (PQresultStatus(result) != PGRES_TUPLES_OK))
        {
            std::ostringstream s;
            s << "Postgis Plugin: PSQL error";
            if (conn_)
            {
                std::string msg = PQerrorMessage(conn_);
                if (! msg.empty())
                {
                    s << ":\n" <<  msg.substr(0, msg.size() - 1);
                }

                s << "\nFull sql was: '" <<  sql << "'\n";
            }
            else
            {
                s << "unable to connect to database";
            }

            if (result)
            {
                PQclear(result);
            }

            throw mapnik::datasource_exception(s.str());
        }

        return boost::make_shared<ResultSet>(result);
    }

    std::string client_encoding() const
    {
        return PQparameterStatus(conn_, "client_encoding");
    }

    bool isOK() const
    {
        return (PQstatus(conn_) != CONNECTION_BAD);
    }

    void close()
    {
        if (! closed_)
        {
            PQfinish(conn_);

            MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: datasource closed, also closing connection - " << conn_;

            closed_ = true;
        }
    }

    std::string new_cursor_name()
    {
        std::ostringstream s;
        s << "mapnik_" << (cursorId++);
        return s.str();
    }

private:
    PGconn *conn_;
    int cursorId;
    bool closed_;
};

#endif //CONNECTION_HPP
<commit_msg>+ add status() method to reduce code duplication<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef POSTGIS_CONNECTION_HPP
#define POSTGIS_CONNECTION_HPP

// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/timer.hpp>

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

// std
#include <sstream>
#include <iostream>

extern "C" {
#include "libpq-fe.h"
}

#include "resultset.hpp"

class Connection
{
public:
    Connection(std::string const& connection_str)
        : cursorId(0),
          closed_(false)
    {
        conn_ = PQconnectdb(connection_str.c_str());
        if (PQstatus(conn_) != CONNECTION_OK)
        {
            std::string err_msg = "Postgis Plugin: ";
            err_msg += status();
            err_msg += "\nConnection string:'";
            err_msg += connection_str;
            err_msg += "'\n";
            throw mapnik::datasource_exception(err_msg);
        }
    }

    ~Connection()
    {
        if (! closed_)
        {
            PQfinish(conn_);

            MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: postgresql connection closed - " << conn_;

            closed_ = true;
        }
    }

    bool execute(std::string const& sql) const
    {
#ifdef MAPNIK_STATS
        mapnik::progress_timer __stats__(std::clog, std::string("postgis_connection::execute ") + sql);
#endif

        PGresult *result = PQexec(conn_, sql.c_str());
        bool ok = (result && (PQresultStatus(result) == PGRES_COMMAND_OK));
        PQclear(result);
        return ok;
    }

    boost::shared_ptr<ResultSet> executeQuery(std::string const& sql, int type = 0) const
    {
#ifdef MAPNIK_STATS
        mapnik::progress_timer __stats__(std::clog, std::string("postgis_connection::execute_query ") + sql);
#endif

        PGresult* result = 0;
        if (type == 1)
        {
            result = PQexecParams(conn_,sql.c_str(), 0, 0, 0, 0, 0, 1);
        }
        else
        {
            result = PQexec(conn_, sql.c_str());
        }

        if (! result || (PQresultStatus(result) != PGRES_TUPLES_OK))
        {
            std::string err_msg = status();
            err_msg += "\nFull sql was: '";
            err_msg += sql;
            err_msg += "'\n";
            if (result)
            {
                PQclear(result);
            }

            throw mapnik::datasource_exception(err_msg);
        }

        return boost::make_shared<ResultSet>(result);
    }

    std::string status() const
    {
        std::string status;
        if (conn_)
        {
            status = PQerrorMessage(conn_);
        }
        else
        {
            status = "Uninitialized connection";
        }
        return status;
    }

    std::string client_encoding() const
    {
        return PQparameterStatus(conn_, "client_encoding");
    }

    bool isOK() const
    {
        return (PQstatus(conn_) != CONNECTION_BAD);
    }

    void close()
    {
        if (! closed_)
        {
            PQfinish(conn_);

            MAPNIK_LOG_DEBUG(postgis) << "postgis_connection: datasource closed, also closing connection - " << conn_;

            closed_ = true;
        }
    }

    std::string new_cursor_name()
    {
        std::ostringstream s;
        s << "mapnik_" << (cursorId++);
        return s.str();
    }

private:
    PGconn *conn_;
    int cursorId;
    bool closed_;
};

#endif //CONNECTION_HPP
<|endoftext|>