<commit_before>#include <iostream>

#include <unistd.h> // For getpid, getppid.

#include <gmock/gmock.h>

#include <set>

#include <stout/abort.hpp>
#include <stout/gtest.hpp>
#include <stout/numify.hpp>
#include <stout/os.hpp>
#include <stout/proc.hpp>
#include <stout/try.hpp>

using proc::CPU;
using proc::SystemStatus;
using proc::ProcessStatus;

using std::set;
using std::string;

TEST(ProcTest, pids)
{
  Try<set<pid_t> > pids = proc::pids();

  ASSERT_SOME(pids);
  EXPECT_NE(0u, pids.get().size());
  EXPECT_EQ(1u, pids.get().count(getpid()));
  EXPECT_EQ(1u, pids.get().count(1));
}

TEST(ProcTest, cpus)
{
  Try<std::list<CPU> > cpus = proc::cpus();

  ASSERT_SOME(cpus);
  EXPECT_LE(1u, cpus.get().size());
}

TEST(ProcTest, SystemStatus)
{
  Try<SystemStatus> status = proc::status();

  ASSERT_SOME(status);
  EXPECT_NE(0u, status.get().btime);
}

TEST(ProcTest, ProcessStatus)
{
  Result<ProcessStatus> status = proc::status(getpid());

  ASSERT_SOME(status);
  EXPECT_EQ(getpid(), status.get().pid);
  EXPECT_EQ(getppid(), status.get().ppid);
}

TEST(ProcTest, SingleThread)
{
  pid_t pid = ::fork();
  ASSERT_NE(-1, pid);

  if (pid == 0) {
    // In child process, wait until killed.
    while (true) { sleep(1); }

    // Should not reach here.
    ABORT("Error, child should be killed before reaching here");
  }

  // In parent process.
  // Check we have the expected number of threads.
  Try<set<pid_t> > threads = proc::threads(pid);

  ASSERT_SOME(threads);
  EXPECT_EQ(1u, threads.get().size());
  EXPECT_EQ(1u, threads.get().count(pid));

  // Kill the child process.
  ASSERT_NE(-1, ::kill(pid, SIGKILL));

  // Wait for the child process.
  int status;
  EXPECT_NE(-1, ::waitpid((pid_t) -1, &status, 0));
  ASSERT_TRUE(WIFSIGNALED(status));
  EXPECT_EQ(SIGKILL, WTERMSIG(status));
}

int threadFunction(void*)
{
  while (true) { sleep(1); }

  return -1;
}

TEST(ProcTest, MultipleThreads)
{
  int ready;
  int pipes[2];
  ASSERT_NE(-1, ::pipe(pipes));

  pid_t pid = ::fork();
  ASSERT_NE(-1, pid);

  if (pid == 0) {
    // In child process
    ::close(pipes[0]);

    int numThreads = 5;

    // 32 KiB stack (2x the common value for PTHREAD_STACK_MIN) for each thread
    // is sufficient since they are essentially no-ops.
    size_t stackSize = 32*1024 / sizeof(unsigned long long);
    unsigned long long stack[numThreads][stackSize];

    set<pid_t> threads;

    for (int i = 0; i < numThreads; i++) {
      pid_t thread;

      // We use clone here to create threads because pthread_create is not
      // async-signal-safe.
      thread = clone(
          threadFunction,
          &(stack[i][stackSize - 1]),
          CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FILES | SIGCHLD,
          NULL);

      EXPECT_NE(-1, thread);

      threads.insert(thread);
    }

    // Also add our own pid to the set.
    threads.insert(getpid());

    // Notify parent of the thread ids.
    ASSERT_SOME(os::write(pipes[1], strings::join(",", threads)));

    // NOTE: CLONE_FILES ensures the pipe file descriptor will be closed in the
    // threads as well, ensuring the parent gets the EOF.
    ::close(pipes[1]);

    // Sleep until killed.
    while (true) { sleep(1); }

    // Should not reach here.
    ABORT("Error, child should be killed before reaching here");
  }

  // In parent process.
  ::close(pipes[1]);

  // Get thread ids from the child. Read up to the first 1024 characters which
  // is sufficient for the expected number of stringified pids.
  Result<string> read = os::read(pipes[0], 1024);
  ASSERT_SOME(read);

  set<pid_t> childThreads;
  foreach (const string& token, strings::tokenize(read.get(), ",")) {
    Try<pid_t> thread = numify<pid_t>(token);
    ASSERT_SOME(thread);

    childThreads.insert(thread.get());
  }

  // Read thread ids from /proc for the child.
  Try<set<pid_t> > procThreads = proc::threads(pid);

  // Check we have the expected threads.
  ASSERT_SOME_EQ(childThreads, procThreads);

  // Kill the child process.
  ASSERT_NE(-1, ::kill(pid, SIGKILL));

  // Wait for the child process.
  int status;
  EXPECT_NE(-1, ::waitpid((pid_t) -1, &status, 0));
  EXPECT_TRUE(WIFSIGNALED(status));
  EXPECT_EQ(SIGKILL, WTERMSIG(status));
}
<commit_msg>Correct and simplify the ProcTests for threads.<commit_after>#include <iostream>

#include <pthread.h>
#include <unistd.h> // For getpid, getppid.

#include <gmock/gmock.h>

#include <set>

#include <stout/abort.hpp>
#include <stout/gtest.hpp>
#include <stout/numify.hpp>
#include <stout/os.hpp>
#include <stout/proc.hpp>
#include <stout/try.hpp>

using proc::CPU;
using proc::SystemStatus;
using proc::ProcessStatus;

using std::set;
using std::string;

TEST(ProcTest, pids)
{
  Try<set<pid_t> > pids = proc::pids();

  ASSERT_SOME(pids);
  EXPECT_NE(0u, pids.get().size());
  EXPECT_EQ(1u, pids.get().count(getpid()));
  EXPECT_EQ(1u, pids.get().count(1));
}

TEST(ProcTest, cpus)
{
  Try<std::list<CPU> > cpus = proc::cpus();

  ASSERT_SOME(cpus);
  EXPECT_LE(1u, cpus.get().size());
}

TEST(ProcTest, SystemStatus)
{
  Try<SystemStatus> status = proc::status();

  ASSERT_SOME(status);
  EXPECT_NE(0u, status.get().btime);
}

TEST(ProcTest, ProcessStatus)
{
  Result<ProcessStatus> status = proc::status(getpid());

  ASSERT_SOME(status);
  EXPECT_EQ(getpid(), status.get().pid);
  EXPECT_EQ(getppid(), status.get().ppid);
}

// NOTE: This test assumes there is a single thread running for the test.
TEST(ProcTest, SingleThread)
{
  // Check we have the expected number of threads.
  Try<set<pid_t> > threads = proc::threads(::getpid());

  ASSERT_SOME(threads);
  EXPECT_EQ(1u, threads.get().size());
  EXPECT_EQ(1u, threads.get().count(::getpid()));
}

void* threadFunction(void*)
{
  // Newly created threads have PTHREAD_CANCEL_ENABLE and
  // PTHREAD_CANCEL_DEFERRED so they can be cancelled from the main thread.
  while (true) { sleep(1); }
}

// NOTE: This test assumes there is only a single thread running for the test.
TEST(ProcTest, MultipleThreads)
{
  size_t numThreads = 5;

  pthread_t pthreads[numThreads];

  // Create additional threads.
  for (size_t i = 0; i < numThreads; i++)
  {
    EXPECT_EQ(0, pthread_create(&pthreads[i], NULL, threadFunction, NULL));
  }

  // Check we have the expected number of threads.
  Try<set<pid_t> > threads = proc::threads(::getpid());

  ASSERT_SOME(threads);
  EXPECT_EQ(1u + numThreads, threads.get().size());
  EXPECT_EQ(1u, threads.get().count(::getpid()));

  // Terminate the threads.
  for (int i = 0; i < numThreads; i++)
  {
    EXPECT_EQ(0, pthread_cancel(pthreads[i]));
    EXPECT_EQ(0, pthread_join(pthreads[i], NULL));
  }
}
<|endoftext|>


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

#pragma once

#include <pybind11/pybind11.h>
#include "pyngraph/ops/allreduce.hpp"
#include "pyngraph/ops/argmax.hpp"
#include "pyngraph/ops/argmin.hpp"
#include "pyngraph/ops/avg_pool.hpp"
#include "pyngraph/ops/batch_norm.hpp"
#include "pyngraph/ops/broadcast.hpp"
#include "pyngraph/ops/broadcast_distributed.hpp"
#include "pyngraph/ops/constant.hpp"
#include "pyngraph/ops/convert.hpp"
#include "pyngraph/ops/convolution.hpp"
#include "pyngraph/ops/dequantize.hpp"
#include "pyngraph/ops/dot.hpp"
#include "pyngraph/ops/fused/depth_to_space.hpp"
#include "pyngraph/ops/fused/gelu.hpp"
#include "pyngraph/ops/fused/gemm.hpp"
#include "pyngraph/ops/fused/grn.hpp"
#include "pyngraph/ops/fused/group_conv.hpp"
#include "pyngraph/ops/fused/hard_sigmoid.hpp"
#include "pyngraph/ops/fused/mvn.hpp"
#include "pyngraph/ops/fused/rnn_cell.hpp"
#include "pyngraph/ops/fused/scale_shift.hpp"
#include "pyngraph/ops/fused/shuffle_channels.hpp"
#include "pyngraph/ops/fused/space_to_depth.hpp"
#include "pyngraph/ops/fused/unsqueeze.hpp"
#include "pyngraph/ops/get_output_element.hpp"
#include "pyngraph/ops/max.hpp"
#include "pyngraph/ops/max_pool.hpp"
#include "pyngraph/ops/maximum.hpp"
#include "pyngraph/ops/min.hpp"
#include "pyngraph/ops/parameter.hpp"
#include "pyngraph/ops/passthrough.hpp"
#include "pyngraph/ops/product.hpp"
#include "pyngraph/ops/quantize.hpp"
#include "pyngraph/ops/quantized_convolution.hpp"
#include "pyngraph/ops/quantized_dot.hpp"
#include "pyngraph/ops/replace_slice.hpp"
#include "pyngraph/ops/result.hpp"
#include "pyngraph/ops/slice.hpp"
#include "pyngraph/ops/softmax.hpp"

namespace py = pybind11;

void regmodule_pyngraph_op(py::module m);
<commit_msg>Style apply<commit_after>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************

#pragma once

#include <pybind11/pybind11.h>
#include "pyngraph/ops/allreduce.hpp"
#include "pyngraph/ops/argmax.hpp"
#include "pyngraph/ops/argmin.hpp"
#include "pyngraph/ops/avg_pool.hpp"
#include "pyngraph/ops/batch_norm.hpp"
#include "pyngraph/ops/broadcast.hpp"
#include "pyngraph/ops/broadcast_distributed.hpp"
#include "pyngraph/ops/constant.hpp"
#include "pyngraph/ops/convert.hpp"
#include "pyngraph/ops/convolution.hpp"
#include "pyngraph/ops/dequantize.hpp"
#include "pyngraph/ops/dot.hpp"
#include "pyngraph/ops/fused/depth_to_space.hpp"
#include "pyngraph/ops/fused/gelu.hpp"
#include "pyngraph/ops/fused/gemm.hpp"
#include "pyngraph/ops/fused/grn.hpp"
#include "pyngraph/ops/fused/group_conv.hpp"
#include "pyngraph/ops/fused/hard_sigmoid.hpp"
#include "pyngraph/ops/fused/mvn.hpp"
#include "pyngraph/ops/fused/rnn_cell.hpp"
#include "pyngraph/ops/fused/scale_shift.hpp"
#include "pyngraph/ops/fused/shuffle_channels.hpp"
#include "pyngraph/ops/fused/space_to_depth.hpp"
#include "pyngraph/ops/fused/unsqueeze.hpp"
#include "pyngraph/ops/get_output_element.hpp"
#include "pyngraph/ops/max.hpp"
#include "pyngraph/ops/max_pool.hpp"
#include "pyngraph/ops/maximum.hpp"
#include "pyngraph/ops/min.hpp"
#include "pyngraph/ops/parameter.hpp"
#include "pyngraph/ops/passthrough.hpp"
#include "pyngraph/ops/product.hpp"
#include "pyngraph/ops/quantize.hpp"
#include "pyngraph/ops/quantized_convolution.hpp"
#include "pyngraph/ops/quantized_dot.hpp"
#include "pyngraph/ops/replace_slice.hpp"
#include "pyngraph/ops/result.hpp"
#include "pyngraph/ops/slice.hpp"
#include "pyngraph/ops/softmax.hpp"

namespace py = pybind11;

void regmodule_pyngraph_op(py::module m);
<|endoftext|>


<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"boost/spirit/home/support/common_terminals.hpp"
#include"boost/spirit/home/qi.hpp"
#include"ork/ork.hpp"

/*
Placeholders for parser components
*/
namespace ork {
namespace orq {//ork-qi :)

BOOST_SPIRIT_TERMINAL(id);
BOOST_SPIRIT_TERMINAL(quote);
BOOST_SPIRIT_TERMINAL(lb_com);//'pound comment'

}//namespace orq
}//namespace ork

/*
Enablers for parser components
*/
namespace boost {
namespace spirit {

//Make custom parser usable as a terminal only, and only for parser expressions (qi::domain).
template<> struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::quote> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::lb_com> : mpl::true_ {};

}//namespace spirit
}//namespace boost

namespace ork {

namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
namespace proto = boost::proto;

#if ORK_UNICODE
typedef spirit::char_encoding::standard_wide charset;
#else
typedef spirit::char_encoding::standard charset;
#endif

namespace orq {//ork-qi :)

struct ORK_ORK_API id_parser : qi::primitive_parser<id_parser> {
public://Parser component stuff
	template<typename context, typename iter>
	struct attribute {//Define the attribute type exposed by this parser component
		typedef string type;
	};

	//This function is called during the actual parsing process
	template<typename iter, typename context, typename skipper, typename attribute>
	bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
		boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip

		if(first == last) {
			return false;
		}

		iter it(first);
		if(!std::isalpha(*it) && *it != ORK('_')) {
			return false;//First character must be letter or underscore
		}
		while(it != last && (std::isalnum(*it) || *it == ORK('_'))) {
			++it;//Subsequent characters can be numbers also
		}

		attribute result(first, it);
		if(result.empty()) {
			return false;
		}

		first = it;
		spirit::traits::assign_to(result, attr);
		return true;
	}

	//This function is called during error handling to create a human readable string for the error context.
	template<typename context>
	boost::spirit::info what(context&) const {
		return boost::spirit::info("id");
	}
};

struct ORK_ORK_API quote_parser : qi::primitive_parser<quote_parser> {
public://Parser component stuff
	template<typename context, typename iter>
	struct attribute {//Define the attribute type exposed by this parser component
		typedef string type;
	};

	//This function is called during the actual parsing process
	template<typename iter, typename context, typename skipper, typename attribute>
	bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
		boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip

		if(first == last) {
			return false;
		}

		iter it(first);
		if(*it++ != ORK('"')) {//Consume the quote
			return false;
		}
		while(it != last && *it != ORK('"')) {//Up to but do not consume the quote
			++it;
		}
		if(it == last) {
			return false;
		}
		if(*it++ != ORK('"')) {//Consume the quote
			return false;
		}

		attribute result(first, it);
		//Allow empty attribute

		first = it;
		spirit::traits::assign_to(result, attr);
		return true;
	}

	//This function is called during error handling to create a human readable string for the error context.
	template<typename context>
	boost::spirit::info what(context&) const {
		return boost::spirit::info("quote");
	}
};

struct ORK_ORK_API lb_com_parser : qi::primitive_parser<lb_com_parser> {
public://Parser component stuff
	template<typename context, typename iter>
	struct attribute {//Define the attribute type exposed by this parser component
		typedef qi::unused_type type;
	};

	//This function is called during the actual parsing process
	template<typename iter, typename context, typename skipper, typename attribute>
	bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
		boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip

		if(first == last) {
			return false;
		}

		iter it(first);
		if(*it++ != ORK('#')) {//Consume the marker
			return false;
		}
		while(it != last && *it != ORK('\n')) {//Up to but do not consume the eol
			++it;
		}

		first = it;
		return true;
	}

	//This function is called during error handling to create a human readable string for the error context.
	template<typename context>
	boost::spirit::info what(context&) const {
		return boost::spirit::info("lb_com");
	}
};

}//namespace orq
}//namespace ork

/*
Instantiators for parser components
*/
namespace boost {
namespace spirit {
namespace qi {

//This is the factory function object invoked in order to create an instance of our parser.
template<typename modifiers>
struct make_primitive<ork::orq::tag::id, modifiers> {
	typedef typename ork::orq::id_parser result_type;

	result_type operator()(unused_type, unused_type) const {
		return result_type();
	}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::quote, modifiers> {
	typedef typename ork::orq::quote_parser result_type;

	result_type operator()(unused_type, unused_type) const {
		return result_type();
	}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::lb_com, modifiers> {
	typedef typename ork::orq::lb_com_parser result_type;

	result_type operator()(unused_type, unused_type) const {
		return result_type();
	}
};

}//namespace qi
}//namespace spirit
}//namespace boost<commit_msg>Fixed a bug including quotes in quoted string<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"boost/spirit/home/support/common_terminals.hpp"
#include"boost/spirit/home/qi.hpp"
#include"ork/ork.hpp"

/*
Placeholders for parser components
*/
namespace ork {
namespace orq {//ork-qi :)

BOOST_SPIRIT_TERMINAL(id);
BOOST_SPIRIT_TERMINAL(quote);
BOOST_SPIRIT_TERMINAL(lb_com);//'pound comment'

}//namespace orq
}//namespace ork

/*
Enablers for parser components
*/
namespace boost {
namespace spirit {

//Make custom parser usable as a terminal only, and only for parser expressions (qi::domain).
template<> struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::quote> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::lb_com> : mpl::true_ {};

}//namespace spirit
}//namespace boost

namespace ork {

namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
namespace proto = boost::proto;

#if ORK_UNICODE
typedef spirit::char_encoding::standard_wide charset;
#else
typedef spirit::char_encoding::standard charset;
#endif

namespace orq {//ork-qi :)

struct ORK_ORK_API id_parser : qi::primitive_parser<id_parser> {
public://Parser component stuff
	template<typename context, typename iter>
	struct attribute {//Define the attribute type exposed by this parser component
		typedef string type;
	};

	//This function is called during the actual parsing process
	template<typename iter, typename context, typename skipper, typename attribute>
	bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
		boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip

		if(first == last) {
			return false;
		}

		iter it(first);
		if(!std::isalpha(*it) && *it != ORK('_')) {
			return false;//First character must be letter or underscore
		}
		while(it != last && (std::isalnum(*it) || *it == ORK('_'))) {
			++it;//Subsequent characters can be numbers also
		}

		attribute result(first, it);
		if(result.empty()) {
			return false;
		}

		first = it;
		spirit::traits::assign_to(result, attr);
		return true;
	}

	//This function is called during error handling to create a human readable string for the error context.
	template<typename context>
	boost::spirit::info what(context&) const {
		return boost::spirit::info("id");
	}
};

struct ORK_ORK_API quote_parser : qi::primitive_parser<quote_parser> {
public://Parser component stuff
	template<typename context, typename iter>
	struct attribute {//Define the attribute type exposed by this parser component
		typedef string type;
	};

	//This function is called during the actual parsing process
	template<typename iter, typename context, typename skipper, typename attribute>
	bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
		boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip

		if(first == last) {
			return false;
		}

		iter it(first);
		if(*it++ != ORK('"')) {//Consume the quote
			return false;
		}
		while(it != last && *it != ORK('"')) {//Up to but do not consume the quote
			++it;
		}
		if(it == last) {
			return false;
		}
		if(*it++ != ORK('"')) {//Consume the quote
			return false;
		}

		attribute result(++first, it - 1);//Do not include quotes
		//Allow empty attribute

		first = it;
		spirit::traits::assign_to(result, attr);
		return true;
	}

	//This function is called during error handling to create a human readable string for the error context.
	template<typename context>
	boost::spirit::info what(context&) const {
		return boost::spirit::info("quote");
	}
};

struct ORK_ORK_API lb_com_parser : qi::primitive_parser<lb_com_parser> {
public://Parser component stuff
	template<typename context, typename iter>
	struct attribute {//Define the attribute type exposed by this parser component
		typedef qi::unused_type type;
	};

	//This function is called during the actual parsing process
	template<typename iter, typename context, typename skipper, typename attribute>
	bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
		boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip

		if(first == last) {
			return false;
		}

		iter it(first);
		if(*it++ != ORK('#')) {//Consume the marker
			return false;
		}
		while(it != last && *it != ORK('\n')) {//Up to but do not consume the eol
			++it;
		}

		first = it;
		return true;
	}

	//This function is called during error handling to create a human readable string for the error context.
	template<typename context>
	boost::spirit::info what(context&) const {
		return boost::spirit::info("lb_com");
	}
};

}//namespace orq
}//namespace ork

/*
Instantiators for parser components
*/
namespace boost {
namespace spirit {
namespace qi {

//This is the factory function object invoked in order to create an instance of our parser.
template<typename modifiers>
struct make_primitive<ork::orq::tag::id, modifiers> {
	typedef typename ork::orq::id_parser result_type;

	result_type operator()(unused_type, unused_type) const {
		return result_type();
	}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::quote, modifiers> {
	typedef typename ork::orq::quote_parser result_type;

	result_type operator()(unused_type, unused_type) const {
		return result_type();
	}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::lb_com, modifiers> {
	typedef typename ork::orq::lb_com_parser result_type;

	result_type operator()(unused_type, unused_type) const {
		return result_type();
	}
};

}//namespace qi
}//namespace spirit
}//namespace boost<|endoftext|>


<commit_before>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

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

#include <round/Round.h>
#include <round/core/LocalNode.h>
#include <round/core/SystemMethod.h>

////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////

Round::LocalNode::LocalNode() {
  init();
}

Round::LocalNode::~LocalNode() {
}

void Round::LocalNode::init() {
  setState(NodeStatus::STOP);
}

////////////////////////////////////////////////
// Configuration
////////////////////////////////////////////////

bool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) {
  if (this->nodeConfig.loadFromString(string, error) == false)
    return false;
  return true;
}

bool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) {
  if (this->nodeConfig.loadFromFile(filename, error) == false)
    return false;
  return true;
}

bool Round::LocalNode::isConfigValid(Error *error) {
  return this->nodeConfig.isValid(error);
}

bool Round::LocalNode::getClusterName(std::string *name, Error *error) {
  return this->nodeConfig.getCluster(name, error);
}

////////////////////////////////////////////////
// Thread
////////////////////////////////////////////////

bool Round::LocalNode::start(Error *error) {
  stop(error);

  bool areAllOperationSucess = true;

  setState(NodeStatus::ACTIVATING);

  nodeWorker.setObject(this);
  if (nodeWorker.start()) {
    if (!this->nodeGraph.addNode(this)) {
      areAllOperationSucess = false;
    }
  }
  else {
    areAllOperationSucess = false;
  }

  if (!areAllOperationSucess) {
    stop(error);
    return false;
  }

  setState(NodeStatus::ACTIVE);

  return true;
}

bool Round::LocalNode::stop(Error *error) {
  bool areAllOperationSucess = true;

  if (!nodeWorker.stop()) {
    areAllOperationSucess = false;
    return false;
  }

  NodeGraph *nodeGraph = getNodeGraph();
  if (!nodeGraph->clear()) {
    areAllOperationSucess = false;
  }

  if (areAllOperationSucess == true) {
    setState(NodeStatus::STOP);
  }

  return areAllOperationSucess;
}

bool Round::LocalNode::restart(Error *error) {
  if (stop(error) == false)
    return false;
  return start(error);
}

////////////////////////////////////////////////
// Notification
////////////////////////////////////////////////

bool Round::LocalNode::nodeAdded(Round::Node *notifyNode)  {
  Error error;

  std::string notifyNodeCluster;
  if (!notifyNode->getClusterName(&notifyNodeCluster, &error))
    return false;

  std::string thisNodeCluster;
  if (!getClusterName(&thisNodeCluster, &error))
    return false;

  if (thisNodeCluster.compare(notifyNodeCluster) != 0)
    return false;

  if (this->nodeGraph.hasNode(notifyNode))
    return true;

  if (!this->nodeGraph.addNode(notifyNode))
    return true;

  if (equals(notifyNode))
    return true;

  return true;
}

bool Round::LocalNode::nodeRemoved(Round::Node *notifyNode)  {
  if (!this->nodeGraph.hasNode(notifyNode))
    return true;

  if (equals(notifyNode)) {
    this->nodeGraph.removeNode(notifyNode);
    return true;
  }

  ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode);
  if (notifyNodeIndex < 0)
    return false;

  Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex);
  if (!failedNode)
    return false;

  return true;
}

////////////////////////////////////////////////
// Message
////////////////////////////////////////////////

bool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  // Set id and ts parameter

  clock_t localTs = getLocalClock();
  nodeReq->setId(localTs);
  nodeReq->setTimestamp(localTs);

  // Post RPC message

  return execMessage(nodeReq, nodeRes, error);
}

bool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) {
  return this->nodeMsgMgr.pushMessage(nodeReq);
}

bool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) {
  *nodeReq = NULL;
  const Message *nodeMsg = NULL;
  if (!this->nodeMsgMgr.waitMessage(&nodeMsg))
    return false;
  *nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg);
  return (*nodeReq) ? true : false;
}

////////////////////////////////////////////////
// Execution
////////////////////////////////////////////////

bool Round::LocalNode::hasUserMethod(const std::string &method) {
  return this->scriptMgr.hasScript(method);
}

bool Round::LocalNode::setError(int rpcErrorCode, Error *err) {
  if (!err)
    return false;
  RPC::JSON::ErrorCodeToError(rpcErrorCode, err);
  return true;
}

bool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
  if (!nodeReq || !nodeRes || !err)
    return false;

  // Check hash code

  if (nodeReq->hasHash()) {
    std::string hashCode;
    if (getHashCode(&hashCode)) {
      if (hashCode.length() != HashObject::GetHashCodeLength()) {
        setError(RPC::JSON::ErrorCodeBadHashCode, err);
        return false;
      }
      NodeGraph *nodeGraph = getNodeGraph();
      if (!nodeGraph->isHandleNode(this, hashCode)) {
        setError(RPC::JSON::ErrorCodeMovedPermanently, err);
        return false;
      }
    }
  }

  // Update local clock

  clock_t remoteTs;
  if (nodeRes->getTimestamp(&remoteTs)) {
    setRemoteClock(remoteTs);
  }
  else {
    incrementLocalClock();
  }

  // Set id and ts parameter

  size_t msgId;
  if (nodeReq->getId(&msgId)) {
    nodeRes->setId(msgId);
  }
  nodeRes->setTimestamp(getLocalClock());

  // Exec Message

  std::string name;
  nodeReq->getMethod(&name);

  if (isSetMethod(name)) {
    if (!setMethod(nodeReq, nodeRes, err)) {
      setError(RPC::JSON::ErrorCodeInvalidParams, err);
      return false;
    }
    return true;
  }

  if (hasUserMethod(name)) {
    std::string params;
    nodeReq->getParams(&params);
    std::string result;
    return this->scriptMgr.run(name, params, &result, err);
  }

  if (isSystemMethod(name)) {
    return execSystemMethod(nodeReq, nodeRes, err);
  }

  setError(RPC::JSON::ErrorCodeMethodNotFound, err);

  return false;
}

////////////////////////////////////////////////
// System Static Method
////////////////////////////////////////////////

bool Round::LocalNode::isSetMethod(const std::string &method) {
  return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false;
}

bool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
  std::string params;
  nodeReq->getParams(&params);

  JSONParser jsonParser;
  if (!jsonParser.parse(params, err)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  JSONObject *jsonObj = jsonParser.getRootObject();
  if (!jsonObj->isDictionary()) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj);
  if (!jsonDict) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  std::string scriptMethod;
  if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  // Couldn't override '_set_method'
  if (isSetMethod(scriptMethod)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  std::string scriptLang;
  if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  // This method is removed if the code parameter is null.
  std::string scriptCode;
  jsonDict->get(SystemMethodRequest::CODE, &scriptCode);

  // Encode
  int encodeType = Script::ENCODING_NONE;
  std::string encodeTypeStr;
  if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) {
    if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) {
      encodeType = Script::ENCODING_BASE64;
    }
  }

  return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err);
}

////////////////////////////////////////////////
// System Dynamic Method
////////////////////////////////////////////////

bool Round::LocalNode::isSystemMethod(const std::string &method) {
  return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false;
}

bool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  static std::map<std::string, int> systemMethods;
  enum {
      SystemGetNodeInfo,
      SystemGetClusterInfo,
      SystemGetNetworkInfo,
  };

  if (systemMethods.size() <= 0) {
    systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo;
    systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo;
    systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo;
  }

  std::string reqMethod;
  nodeReq->getMethod(&reqMethod);

  if (systemMethods.find(reqMethod) == systemMethods.end()) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);
    return false;
  }

  int systemMethodType = systemMethods[reqMethod];
  switch (systemMethodType) {
  case SystemGetNodeInfo:
    return _get_node_info(nodeReq, nodeRes, error);
  case SystemGetClusterInfo:
    return _get_cluster_info(nodeReq, nodeRes, error);
  case SystemGetNetworkInfo:
    return _get_network_info(nodeReq, nodeRes, error);
  }

  RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);

  return false;
}

bool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  SystemGetNodeInfoResponse sysRes(nodeRes);
  return sysRes.setNode(this);
}

bool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  SystemGetClusterInfoResponse sysRes(nodeRes);
  return sysRes.setCluster(this);
}

bool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  SystemGetNetworkInfoResponse sysRes(nodeRes);
  return sysRes.setClusters(this);
}
<commit_msg>* Fixed LocalNode::execMessage() to return the result of user script execution. * Updated LocalNode::execMessage() to check if the method is null.<commit_after>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

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

#include <round/Round.h>
#include <round/core/LocalNode.h>
#include <round/core/SystemMethod.h>

////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////

Round::LocalNode::LocalNode() {
  init();
}

Round::LocalNode::~LocalNode() {
}

void Round::LocalNode::init() {
  setState(NodeStatus::STOP);
}

////////////////////////////////////////////////
// Configuration
////////////////////////////////////////////////

bool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) {
  if (this->nodeConfig.loadFromString(string, error) == false)
    return false;
  return true;
}

bool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) {
  if (this->nodeConfig.loadFromFile(filename, error) == false)
    return false;
  return true;
}

bool Round::LocalNode::isConfigValid(Error *error) {
  return this->nodeConfig.isValid(error);
}

bool Round::LocalNode::getClusterName(std::string *name, Error *error) {
  return this->nodeConfig.getCluster(name, error);
}

////////////////////////////////////////////////
// Thread
////////////////////////////////////////////////

bool Round::LocalNode::start(Error *error) {
  stop(error);

  bool areAllOperationSucess = true;

  setState(NodeStatus::ACTIVATING);

  nodeWorker.setObject(this);
  if (nodeWorker.start()) {
    if (!this->nodeGraph.addNode(this)) {
      areAllOperationSucess = false;
    }
  }
  else {
    areAllOperationSucess = false;
  }

  if (!areAllOperationSucess) {
    stop(error);
    return false;
  }

  setState(NodeStatus::ACTIVE);

  return true;
}

bool Round::LocalNode::stop(Error *error) {
  bool areAllOperationSucess = true;

  if (!nodeWorker.stop()) {
    areAllOperationSucess = false;
    return false;
  }

  NodeGraph *nodeGraph = getNodeGraph();
  if (!nodeGraph->clear()) {
    areAllOperationSucess = false;
  }

  if (areAllOperationSucess == true) {
    setState(NodeStatus::STOP);
  }

  return areAllOperationSucess;
}

bool Round::LocalNode::restart(Error *error) {
  if (stop(error) == false)
    return false;
  return start(error);
}

////////////////////////////////////////////////
// Notification
////////////////////////////////////////////////

bool Round::LocalNode::nodeAdded(Round::Node *notifyNode)  {
  Error error;

  std::string notifyNodeCluster;
  if (!notifyNode->getClusterName(&notifyNodeCluster, &error))
    return false;

  std::string thisNodeCluster;
  if (!getClusterName(&thisNodeCluster, &error))
    return false;

  if (thisNodeCluster.compare(notifyNodeCluster) != 0)
    return false;

  if (this->nodeGraph.hasNode(notifyNode))
    return true;

  if (!this->nodeGraph.addNode(notifyNode))
    return true;

  if (equals(notifyNode))
    return true;

  return true;
}

bool Round::LocalNode::nodeRemoved(Round::Node *notifyNode)  {
  if (!this->nodeGraph.hasNode(notifyNode))
    return true;

  if (equals(notifyNode)) {
    this->nodeGraph.removeNode(notifyNode);
    return true;
  }

  ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode);
  if (notifyNodeIndex < 0)
    return false;

  Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex);
  if (!failedNode)
    return false;

  return true;
}

////////////////////////////////////////////////
// Message
////////////////////////////////////////////////

bool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  // Set id and ts parameter

  clock_t localTs = getLocalClock();
  nodeReq->setId(localTs);
  nodeReq->setTimestamp(localTs);

  // Post RPC message

  return execMessage(nodeReq, nodeRes, error);
}

bool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) {
  return this->nodeMsgMgr.pushMessage(nodeReq);
}

bool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) {
  *nodeReq = NULL;
  const Message *nodeMsg = NULL;
  if (!this->nodeMsgMgr.waitMessage(&nodeMsg))
    return false;
  *nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg);
  return (*nodeReq) ? true : false;
}

////////////////////////////////////////////////
// Execution
////////////////////////////////////////////////

bool Round::LocalNode::hasUserMethod(const std::string &method) {
  return this->scriptMgr.hasScript(method);
}

bool Round::LocalNode::setError(int rpcErrorCode, Error *err) {
  if (!err)
    return false;
  RPC::JSON::ErrorCodeToError(rpcErrorCode, err);
  return true;
}

bool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
  if (!nodeReq || !nodeRes || !err)
    return false;

  // Check hash code

  if (nodeReq->hasHash()) {
    std::string hashCode;
    if (getHashCode(&hashCode)) {
      if (hashCode.length() != HashObject::GetHashCodeLength()) {
        setError(RPC::JSON::ErrorCodeBadHashCode, err);
        return false;
      }
      NodeGraph *nodeGraph = getNodeGraph();
      if (!nodeGraph->isHandleNode(this, hashCode)) {
        setError(RPC::JSON::ErrorCodeMovedPermanently, err);
        return false;
      }
    }
  }

  // Update local clock

  clock_t remoteTs;
  if (nodeRes->getTimestamp(&remoteTs)) {
    setRemoteClock(remoteTs);
  }
  else {
    incrementLocalClock();
  }

  // Set id and ts parameter

  size_t msgId;
  if (nodeReq->getId(&msgId)) {
    nodeRes->setId(msgId);
  }
  nodeRes->setTimestamp(getLocalClock());

  // Exec Message

  std::string name;
  if (!nodeReq->getMethod(&name) || (name.length() <= 0)) {
    setError(RPC::JSON::ErrorCodeMethodNotFound, err);
    return false;
  }

  if (isSetMethod(name)) {
    if (!setMethod(nodeReq, nodeRes, err)) {
      setError(RPC::JSON::ErrorCodeInvalidParams, err);
      return false;
    }
    return true;
  }

  if (hasUserMethod(name)) {
    std::string params;
    nodeReq->getParams(&params);
    std::string result;
    bool isSuccess = this->scriptMgr.run(name, params, &result, err);
    if (isSuccess) {
      nodeRes->setResult(result);
    }
    else {
      nodeRes->setError(err);
    }
    return isSuccess;
  }

  if (isSystemMethod(name)) {
    return execSystemMethod(nodeReq, nodeRes, err);
  }

  setError(RPC::JSON::ErrorCodeMethodNotFound, err);

  return false;
}

////////////////////////////////////////////////
// System Static Method
////////////////////////////////////////////////

bool Round::LocalNode::isSetMethod(const std::string &method) {
  return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false;
}

bool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
  std::string params;
  nodeReq->getParams(&params);

  JSONParser jsonParser;
  if (!jsonParser.parse(params, err)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  JSONObject *jsonObj = jsonParser.getRootObject();
  if (!jsonObj->isDictionary()) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj);
  if (!jsonDict) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  std::string scriptMethod;
  if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  // Couldn't override '_set_method'
  if (isSetMethod(scriptMethod)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  std::string scriptLang;
  if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
    return false;
  }

  // This method is removed if the code parameter is null.
  std::string scriptCode;
  jsonDict->get(SystemMethodRequest::CODE, &scriptCode);

  // Encode
  int encodeType = Script::ENCODING_NONE;
  std::string encodeTypeStr;
  if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) {
    if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) {
      encodeType = Script::ENCODING_BASE64;
    }
  }

  return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err);
}

////////////////////////////////////////////////
// System Dynamic Method
////////////////////////////////////////////////

bool Round::LocalNode::isSystemMethod(const std::string &method) {
  return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false;
}

bool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  static std::map<std::string, int> systemMethods;
  enum {
      SystemGetNodeInfo,
      SystemGetClusterInfo,
      SystemGetNetworkInfo,
  };

  if (systemMethods.size() <= 0) {
    systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo;
    systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo;
    systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo;
  }

  std::string reqMethod;
  nodeReq->getMethod(&reqMethod);

  if (systemMethods.find(reqMethod) == systemMethods.end()) {
    RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);
    return false;
  }

  int systemMethodType = systemMethods[reqMethod];
  switch (systemMethodType) {
  case SystemGetNodeInfo:
    return _get_node_info(nodeReq, nodeRes, error);
  case SystemGetClusterInfo:
    return _get_cluster_info(nodeReq, nodeRes, error);
  case SystemGetNetworkInfo:
    return _get_network_info(nodeReq, nodeRes, error);
  }

  RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);

  return false;
}

bool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  SystemGetNodeInfoResponse sysRes(nodeRes);
  return sysRes.setNode(this);
}

bool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  SystemGetClusterInfoResponse sysRes(nodeRes);
  return sysRes.setCluster(this);
}

bool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
  SystemGetNetworkInfoResponse sysRes(nodeRes);
  return sysRes.setClusters(this);
}
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2003-2012
  \file      output.cpp
  \author      (rdo@rk9.bmstu.ru)
  \date      20.02.2003
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/report/build_edit_line_info.h"
#include "app/rdo_studio_mfc/src/output.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/src/model/model.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdobuildedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdodebugedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditorresults.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/rdo_tracer/rdotracer.h"
#include "app/rdo_studio_mfc/rdo_tracer/tracer_ctrls/rdotracerlogctrl.h"
// --------------------------------------------------------------------------------

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

using namespace rdoEditor;
using namespace rdoEditCtrl;
using namespace rdo::simulation::report;

// --------------------------------------------------------------------------------
// -------------------- RDOStudioOutput
// --------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(RDOStudioOutput, RDOStudioDockWnd)
	ON_WM_CREATE()
END_MESSAGE_MAP()

RDOStudioOutput::RDOStudioOutput()
	: build  (NULL)
	, debug  (NULL)
	, trace  (NULL)
	, results(NULL)
	, find   (NULL)
{}

RDOStudioOutput::~RDOStudioOutput()
{
	eraseMenu( &popupMenu );
}

int RDOStudioOutput::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (RDOStudioDockWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	tab.Create( NULL, NULL, 0, CRect(0, 0, 100, 100), this, 0 );
	tab.modifyTabStyle( 0, TCS_MULTILINE );
//	tab.modifyTabStyle( 0, TCS_BOTTOM | TCS_MULTILINE );

	popupMenu.CreatePopupMenu();

	if (AfxGetMainWnd())
	{
		CMenu* mainMenu = AfxGetMainWnd()->GetMenu();
		if (mainMenu)
		{
			rbool maximized = studioApp.getIMainWnd()->isMDIMaximazed();
			int delta = maximized ? 1 : 0;

			appendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 1 + delta ), 8, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu );
			popupMenu.AppendMenu( MF_SEPARATOR );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 2, &popupMenu );
			popupMenu.AppendMenu( MF_SEPARATOR );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 7, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 8, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 9, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 10, &popupMenu );
		}
	}

	build   = new RDOBuildEdit;
	debug   = new RDODebugEdit;
	trace   = tracer->createLog();
	results = new RDOEditorResults;
	find    = new RDOFindEdit;

	build->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	debug->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	trace->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	results->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	find->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );

	build->setEditorStyle( &studioApp.getStyle()->style_build );
	build->setPopupMenu( &popupMenu );

	debug->setEditorStyle( &studioApp.getStyle()->style_debug );
	debug->setPopupMenu( &popupMenu );

	trace->setStyle( &studioApp.getStyle()->style_trace );

	results->setEditorStyle( &studioApp.getStyle()->style_results );
	results->setPopupMenu( &popupMenu );

	find->setEditorStyle( &studioApp.getStyle()->style_find );
	find->setPopupMenu( &popupMenu );

	tab.insertItem( build, rdo::format( IDS_TAB_BUILD ).c_str() );
	tab.insertItem( debug, rdo::format( IDS_TAB_DEBUG ).c_str() );
	tab.insertItem( trace, rdo::format( IDS_TAB_TRACE ).c_str() );
	tab.insertItem( results, rdo::format( IDS_TAB_RESULT ).c_str() );
	tab.insertItem( find, rdo::format( IDS_TAB_FIND ).c_str() );

	//studioApp.m_pMainFrame->registerCmdWnd( build, build->getSCIHWND() );
	//studioApp.m_pMainFrame->registerCmdWnd( debug, debug->getSCIHWND() );
	//studioApp.m_pMainFrame->registerCmdWnd( trace );
	//studioApp.m_pMainFrame->registerCmdWnd( results, results->getSCIHWND() );
	//studioApp.m_pMainFrame->registerCmdWnd( find, find->getSCIHWND() );

	return 0;
}

void RDOStudioOutput::showBuild()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 0 );
	if ( plugins->studioIsShow() ) {
		build->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showDebug()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 1 );
	if ( plugins->studioIsShow() ) {
		debug->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showTrace()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 2 );
	if ( plugins->studioIsShow() ) {
		trace->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showResults()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 3 );
	if ( plugins->studioIsShow() ) {
		results->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showFind()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 4 );
	if ( plugins->studioIsShow() ) {
		find->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::clearBuild()
{
	if ( build ) build->clearAll();
}

void RDOStudioOutput::clearDebug()
{
	if ( debug ) debug->clearAll();
}

void RDOStudioOutput::clearResults()
{
	if ( results ) results->clearAll();
}

void RDOStudioOutput::clearFind()
{
	if ( find ) find->clearAll();
}

void RDOStudioOutput::appendStringToBuild( CREF(tstring) str ) const
{
	PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo( str );
	build->appendLine( pLine );
}

void RDOStudioOutput::appendStringToBuild( CREF(rdo::simulation::report::FileMessage) message ) const
{
	if ( message.getType() == rdo::simulation::report::FileMessage::MT_ERROR || (message.getType() == FileMessage::MT_WARNING && static_cast<PTR(RDOBuildEditTheme)>(studioApp.m_pMainFrame->style_build.theme)->warning) )
	{
		PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo(message);
		build->appendLine(pLine);
	}
}

void RDOStudioOutput::appendStringToDebug( CREF(tstring) str ) const
{
	debug->appendLine( str );
}

void RDOStudioOutput::appendStringToResults( CREF(tstring) str ) const
{
	int pos = results->getCurrentPos();
	results->setCurrentPos(results->getLength());
	results->setReadOnly  (false);
	results->appendText   (str  );
	results->setReadOnly  (true );
	results->setCurrentPos(pos  );
}

void RDOStudioOutput::appendStringToFind( CREF(tstring) str, rdoModelObjects::RDOFileType fileType, int lineNumber, int posInLine ) const
{
	LogEditLineInfo* line = new LogEditLineInfo( rdo::simulation::report::FileMessage(str, fileType, lineNumber, posInLine ) );
	find->appendLine( line );
}

void RDOStudioOutput::Tab::changeCurrentItem()
{
	studioApp.getIMainWnd()->output.updateLogConnection();
}

void RDOStudioOutput::updateLogConnection() const
{
	int item = tab.getCurrentIndex();
	RDOLogEdit* log = NULL;
	if ( item == 0 ) {
		log = build;
	} else if ( item == 4 ) {
		log = find;
	}
	if ( log ) {
		rdoEditor::RDOEditorTabCtrl* editor_tab = model->getTab();
		if ( editor_tab ) {
			for ( int i = 0; i < editor_tab->getItemCount(); i++ ) {
				editor_tab->getItemEdit( i )->setLog( *log );
			}
		}
	}
}

void RDOStudioOutput::updateStyles() const
{
	build->setEditorStyle( &studioApp.getStyle()->style_build );
	debug->setEditorStyle( &studioApp.getStyle()->style_debug );
	trace->setStyle( &studioApp.getStyle()->style_trace );
	results->setEditorStyle( &studioApp.getStyle()->style_results );
	find->setEditorStyle( &studioApp.getStyle()->style_find );
}
<commit_msg> - конфликт после мержа<commit_after>/*!
  \copyright (c) RDO-Team, 2003-2012
  \file      output.cpp
  \author      (rdo@rk9.bmstu.ru)
  \date      20.02.2003
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/report/build_edit_line_info.h"
#include "app/rdo_studio_mfc/src/output.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/src/model/model.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdobuildedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdodebugedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditorresults.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/rdo_tracer/rdotracer.h"
#include "app/rdo_studio_mfc/rdo_tracer/tracer_ctrls/rdotracerlogctrl.h"
// --------------------------------------------------------------------------------

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

using namespace rdoEditor;
using namespace rdoEditCtrl;
using namespace rdo::simulation::report;

// --------------------------------------------------------------------------------
// -------------------- RDOStudioOutput
// --------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(RDOStudioOutput, RDOStudioDockWnd)
	ON_WM_CREATE()
END_MESSAGE_MAP()

RDOStudioOutput::RDOStudioOutput()
	: build  (NULL)
	, debug  (NULL)
	, trace  (NULL)
	, results(NULL)
	, find   (NULL)
{}

RDOStudioOutput::~RDOStudioOutput()
{
	eraseMenu( &popupMenu );
}

int RDOStudioOutput::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (RDOStudioDockWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	tab.Create( NULL, NULL, 0, CRect(0, 0, 100, 100), this, 0 );
	tab.modifyTabStyle( 0, TCS_MULTILINE );
//	tab.modifyTabStyle( 0, TCS_BOTTOM | TCS_MULTILINE );

	popupMenu.CreatePopupMenu();

	if (AfxGetMainWnd())
	{
		CMenu* mainMenu = AfxGetMainWnd()->GetMenu();
		if (mainMenu)
		{
			rbool maximized = studioApp.getIMainWnd()->isMDIMaximazed();
			int delta = maximized ? 1 : 0;

			appendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 1 + delta ), 8, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu );
			popupMenu.AppendMenu( MF_SEPARATOR );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 2, &popupMenu );
			popupMenu.AppendMenu( MF_SEPARATOR );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 7, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 8, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 9, &popupMenu );
			appendMenu( mainMenu->GetSubMenu( 2 + delta ), 10, &popupMenu );
		}
	}

	build   = new RDOBuildEdit;
	debug   = new RDODebugEdit;
	trace   = tracer->createLog();
	results = new RDOEditorResults;
	find    = new RDOFindEdit;

	build->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	debug->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	trace->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	results->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
	find->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );

	build->setEditorStyle( &studioApp.getStyle()->style_build );
	build->setPopupMenu( &popupMenu );

	debug->setEditorStyle( &studioApp.getStyle()->style_debug );
	debug->setPopupMenu( &popupMenu );

	trace->setStyle( &studioApp.getStyle()->style_trace );

	results->setEditorStyle( &studioApp.getStyle()->style_results );
	results->setPopupMenu( &popupMenu );

	find->setEditorStyle( &studioApp.getStyle()->style_find );
	find->setPopupMenu( &popupMenu );

	tab.insertItem( build, rdo::format( IDS_TAB_BUILD ).c_str() );
	tab.insertItem( debug, rdo::format( IDS_TAB_DEBUG ).c_str() );
	tab.insertItem( trace, rdo::format( IDS_TAB_TRACE ).c_str() );
	tab.insertItem( results, rdo::format( IDS_TAB_RESULT ).c_str() );
	tab.insertItem( find, rdo::format( IDS_TAB_FIND ).c_str() );

	//studioApp.m_pMainFrame->registerCmdWnd( build, build->getSCIHWND() );
	//studioApp.m_pMainFrame->registerCmdWnd( debug, debug->getSCIHWND() );
	//studioApp.m_pMainFrame->registerCmdWnd( trace );
	//studioApp.m_pMainFrame->registerCmdWnd( results, results->getSCIHWND() );
	//studioApp.m_pMainFrame->registerCmdWnd( find, find->getSCIHWND() );

	return 0;
}

void RDOStudioOutput::showBuild()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 0 );
	if ( plugins->studioIsShow() ) {
		build->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showDebug()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 1 );
	if ( plugins->studioIsShow() ) {
		debug->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showTrace()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 2 );
	if ( plugins->studioIsShow() ) {
		trace->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showResults()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 3 );
	if ( plugins->studioIsShow() ) {
		results->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::showFind()
{
	studioApp.getIMainWnd()->showOutput();
	tab.setCurrentItem( 4 );
	if ( plugins->studioIsShow() ) {
		find->SetFocus();
		UpdateWindow();
	}
}

void RDOStudioOutput::clearBuild()
{
	if ( build ) build->clearAll();
}

void RDOStudioOutput::clearDebug()
{
	if ( debug ) debug->clearAll();
}

void RDOStudioOutput::clearResults()
{
	if ( results ) results->clearAll();
}

void RDOStudioOutput::clearFind()
{
	if ( find ) find->clearAll();
}

void RDOStudioOutput::appendStringToBuild( CREF(tstring) str ) const
{
	PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo( str );
	build->appendLine( pLine );
}

void RDOStudioOutput::appendStringToBuild( CREF(rdo::simulation::report::FileMessage) message ) const
{
	if ( message.getType() == rdo::simulation::report::FileMessage::MT_ERROR || (message.getType() == FileMessage::MT_WARNING && static_cast<PTR(RDOBuildEditTheme)>(studioApp.getStyle()->style_build.theme)->warning) )
	{
		PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo(message);
		build->appendLine(pLine);
	}
}

void RDOStudioOutput::appendStringToDebug( CREF(tstring) str ) const
{
	debug->appendLine( str );
}

void RDOStudioOutput::appendStringToResults( CREF(tstring) str ) const
{
	int pos = results->getCurrentPos();
	results->setCurrentPos(results->getLength());
	results->setReadOnly  (false);
	results->appendText   (str  );
	results->setReadOnly  (true );
	results->setCurrentPos(pos  );
}

void RDOStudioOutput::appendStringToFind( CREF(tstring) str, rdoModelObjects::RDOFileType fileType, int lineNumber, int posInLine ) const
{
	LogEditLineInfo* line = new LogEditLineInfo( rdo::simulation::report::FileMessage(str, fileType, lineNumber, posInLine ) );
	find->appendLine( line );
}

void RDOStudioOutput::Tab::changeCurrentItem()
{
	studioApp.getIMainWnd()->output.updateLogConnection();
}

void RDOStudioOutput::updateLogConnection() const
{
	int item = tab.getCurrentIndex();
	RDOLogEdit* log = NULL;
	if ( item == 0 ) {
		log = build;
	} else if ( item == 4 ) {
		log = find;
	}
	if ( log ) {
		rdoEditor::RDOEditorTabCtrl* editor_tab = model->getTab();
		if ( editor_tab ) {
			for ( int i = 0; i < editor_tab->getItemCount(); i++ ) {
				editor_tab->getItemEdit( i )->setLog( *log );
			}
		}
	}
}

void RDOStudioOutput::updateStyles() const
{
	build->setEditorStyle( &studioApp.getStyle()->style_build );
	debug->setEditorStyle( &studioApp.getStyle()->style_debug );
	trace->setStyle( &studioApp.getStyle()->style_trace );
	results->setEditorStyle( &studioApp.getStyle()->style_results );
	find->setEditorStyle( &studioApp.getStyle()->style_find );
}
<|endoftext|>


<commit_before>/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mdirectinputcontextplugin.h"

#include "mimserver.h"
#include "mimapphostedserverlogic.h"

#include "connectionfactory.h"
#include "mimdirectserverconnection.h"
#include "miminputcontextdirectconnection.h"

#include <maliit/inputmethod.h>

using namespace std::tr1;

#include <minputcontext.h>
#include <QString>
#include <QStringList>

namespace {
    const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME"Direct");
}

MDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)
    : QInputContextPlugin(parent)
{
    // nothing
}

MDirectInputContextPlugin::~MDirectInputContextPlugin()
{
    // nothing
}

QInputContext *MDirectInputContextPlugin::create(const QString &key)
{
    QInputContext *ctx = NULL;

    if (key == MaliitDirectInputContextName) {
        QSharedPointer<MImDirectServerConnection> serverConnection =
                qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));
        MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;
        serverConnection->connectTo(icConnection);

        shared_ptr<MInputContextConnection> icConn(icConnection);
        QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);
        MImServer::configureSettings(MImServer::TemporarySettings);
        MImServer *imServer = new MImServer(serverLogic, icConn);

        Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());

        ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);
        imServer->setParent(ctx);
    } else {
        qCritical() << "Unknown plugin name";
    }

    return ctx;
}

QString MDirectInputContextPlugin::description(const QString &s)
{
    Q_UNUSED(s);

    return "Maliit input context plugin";
}

QString MDirectInputContextPlugin::displayName(const QString &s)
{
    Q_UNUSED(s);

    // TODO: want this translated?
    return "Input context for Maliit input methods";
}

QStringList MDirectInputContextPlugin::keys() const
{
    return QStringList(MaliitDirectInputContextName);
}

QStringList MDirectInputContextPlugin::languages(const QString &)
{
    return QStringList("EN"); // FIXME
}

Q_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)

<commit_msg>Differentiate direct input context plugin description strings<commit_after>/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mdirectinputcontextplugin.h"

#include "mimserver.h"
#include "mimapphostedserverlogic.h"

#include "connectionfactory.h"
#include "mimdirectserverconnection.h"
#include "miminputcontextdirectconnection.h"

#include <maliit/inputmethod.h>

using namespace std::tr1;

#include <minputcontext.h>
#include <QString>
#include <QStringList>

namespace {
    const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME"Direct");
}

MDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)
    : QInputContextPlugin(parent)
{
    // nothing
}

MDirectInputContextPlugin::~MDirectInputContextPlugin()
{
    // nothing
}

QInputContext *MDirectInputContextPlugin::create(const QString &key)
{
    QInputContext *ctx = NULL;

    if (key == MaliitDirectInputContextName) {
        QSharedPointer<MImDirectServerConnection> serverConnection =
                qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));
        MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;
        serverConnection->connectTo(icConnection);

        shared_ptr<MInputContextConnection> icConn(icConnection);
        QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);
        MImServer::configureSettings(MImServer::TemporarySettings);
        MImServer *imServer = new MImServer(serverLogic, icConn);

        Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());

        ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);
        imServer->setParent(ctx);
    } else {
        qCritical() << "Unknown plugin name";
    }

    return ctx;
}

QString MDirectInputContextPlugin::description(const QString &s)
{
    Q_UNUSED(s);

    return "Maliit input context plugin (direct)";
}

QString MDirectInputContextPlugin::displayName(const QString &s)
{
    Q_UNUSED(s);

    // TODO: want this translated?
    return "Input context for Maliit input methods (direct)";
}

QStringList MDirectInputContextPlugin::keys() const
{
    return QStringList(MaliitDirectInputContextName);
}

QStringList MDirectInputContextPlugin::languages(const QString &)
{
    return QStringList("EN"); // FIXME
}

Q_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)

<|endoftext|>


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

#include <game.hpp>
#include <engine.hpp>
#include <entity.hpp>
#include <entity_manager.hpp>
#include <viewport.hpp>
#include <score.hpp>

#include <hgeresource.h>

#include <algorithm>
#include <set>

//==============================================================================
Game::Game()
    :
    Context(),
    m_arena()
{
}

//------------------------------------------------------------------------------
Game::~Game()
{
}

//------------------------------------------------------------------------------
// public:
//------------------------------------------------------------------------------
void
Game::init()
{
    HGE * hge( Engine::hge() );
    b2World * b2d( Engine::b2d() );
    hgeResourceManager * rm( Engine::rm() );
    ViewPort * vp( Engine::vp() );

    Engine::em()->init();

    vp->offset().x = 0.0f;
    vp->offset().y = 0.0f;
    vp->centre().x = 0.0f;
    vp->centre().y = 0.0f;
    vp->bounds().x = 1280.0f;
    vp->bounds().y = 720.0f;
    vp->setAngle( 0.0f );
    vp->setScale( 10.0f );

    for ( int x = 0; x < 10; ++x )
    {
        for ( int y = 0; y < 20; ++y )
        {
            m_arena[x][y] = false;
        }
    }
}

//------------------------------------------------------------------------------
void
Game::fini()
{
    Engine::em()->fini();
}

//------------------------------------------------------------------------------
bool
Game::update( float dt )
{
    const Controller & pad( Engine::instance()->getController() );
    HGE * hge( Engine::hge() );
    ViewPort * vp( Engine::vp() );

    bool paused( Engine::instance()->isPaused() );

    return false;
}

//------------------------------------------------------------------------------
void
Game::render()
{
    hgeResourceManager * rm( Engine::rm() );
    hgeFont* font = Engine::rm()->GetFont("menu");
    ViewPort * vp( Engine::vp() );

    vp->setTransform();

    float scale( 1.0f );
    std::vector< Entity * > entities;
    for ( b2Body * body( Engine::b2d()->GetBodyList() ); body != NULL;
          body = body->GetNext() )
    {
        Entity * entity( static_cast< Entity * >( body->GetUserData() ) );
        if ( entity )
        {
            entity->render( scale );
        }
    }

    Engine::vp()->reset();
    vp->setTransform();

    hgeSprite * black( rm->GetSprite( "empty" ) );
    hgeSprite * white( rm->GetSprite( "tile" ) );

    for ( int x = 0; x < 10; ++x )
    {
        for ( int y = 0; y < 20; ++y )
        {
            hgeSprite * sprite( m_arena[x][y] ? white : black );
            sprite->RenderEx( ( x - 4.5  ) * 3.2f, ( y - 9.5 ) * 3.2f,
                              0.0f, 0.1f );
        }
    }
}

//==============================================================================
<commit_msg>Fix warning<commit_after>//==============================================================================

#include <game.hpp>
#include <engine.hpp>
#include <entity.hpp>
#include <entity_manager.hpp>
#include <viewport.hpp>
#include <score.hpp>

#include <hgeresource.h>

#include <algorithm>
#include <set>

//==============================================================================
Game::Game()
    :
    Context(),
    m_arena()
{
}

//------------------------------------------------------------------------------
Game::~Game()
{
}

//------------------------------------------------------------------------------
// public:
//------------------------------------------------------------------------------
void
Game::init()
{
    HGE * hge( Engine::hge() );
    b2World * b2d( Engine::b2d() );
    hgeResourceManager * rm( Engine::rm() );
    ViewPort * vp( Engine::vp() );

    Engine::em()->init();

    vp->offset().x = 0.0f;
    vp->offset().y = 0.0f;
    vp->centre().x = 0.0f;
    vp->centre().y = 0.0f;
    vp->bounds().x = 1280.0f;
    vp->bounds().y = 720.0f;
    vp->setAngle( 0.0f );
    vp->setScale( 10.0f );

    for ( int x = 0; x < 10; ++x )
    {
        for ( int y = 0; y < 20; ++y )
        {
            m_arena[x][y] = false;
        }
    }
}

//------------------------------------------------------------------------------
void
Game::fini()
{
    Engine::em()->fini();
}

//------------------------------------------------------------------------------
bool
Game::update( float dt )
{
    const Controller & pad( Engine::instance()->getController() );
    HGE * hge( Engine::hge() );
    ViewPort * vp( Engine::vp() );

    bool paused( Engine::instance()->isPaused() );

    return false;
}

//------------------------------------------------------------------------------
void
Game::render()
{
    hgeResourceManager * rm( Engine::rm() );
    hgeFont* font = Engine::rm()->GetFont("menu");
    ViewPort * vp( Engine::vp() );

    vp->setTransform();

    float scale( 1.0f );
    std::vector< Entity * > entities;
    for ( b2Body * body( Engine::b2d()->GetBodyList() ); body != NULL;
          body = body->GetNext() )
    {
        Entity * entity( static_cast< Entity * >( body->GetUserData() ) );
        if ( entity )
        {
            entity->render( scale );
        }
    }

    Engine::vp()->reset();
    vp->setTransform();

    hgeSprite * black( rm->GetSprite( "empty" ) );
    hgeSprite * white( rm->GetSprite( "tile" ) );

    for ( int x = 0; x < 10; ++x )
    {
        for ( int y = 0; y < 20; ++y )
        {
            hgeSprite * sprite( m_arena[x][y] ? white : black );
            sprite->RenderEx( ( x - 4.5f  ) * 3.2f, ( y - 9.5f ) * 3.2f,
                              0.0f, 0.1f );
        }
    }
}

//==============================================================================
<|endoftext|>


<commit_before>#include "game.h"
#include "rook.h"
#include "pawn.h"
#include "queen.h"
#include "bishop.h"
#include "knight.h"
#include "king.h"
game::game()
{
	turn = true;
	board.addPiece(new rook(0,0,true));
	board.addPiece(new knight(1,0,true));
	board.addPiece(new bishop(2,0,true));
	board.addPiece(new queen(3,0,true));
	board.addPiece(new king(4,0,true));
	board.addPiece(new bishop(5,0,true));
	board.addPiece(new knight(6,0,true));
	board.addPiece(new rook(7,0,true));
	for(int i = 0;i<8;i++)
	{
		board.addPiece(new pawn(i,1,true));
	}

	board.addPiece(new rook(0,7,true));
	board.addPiece(new knight(1,7,true));
	board.addPiece(new bishop(2,7,true));
	board.addPiece(new queen(3,7,true));
	board.addPiece(new king(4,7,true));
	board.addPiece(new bishop(5,7,true));
	board.addPiece(new knight(6,7,true));
	board.addPiece(new rook(7,7,true));
	for(int i = 0;i<8;i++)
	{
		board.addPiece(new pawn(i,6,true));
	}

}
game::~game(){}

void game::print()
{
	board.printBoard();
}<commit_msg>Fixed naming issue<commit_after>#include "game.h"
#include "rook.h"
#include "pawn.h"
#include "queen.h"
#include "bishop.h"
#include "knight.h"
#include "king.h"
game::game()
{
	turn = true;
	boardGame.addPiece(new rook(0,0,true));
	boardGame.addPiece(new knight(1,0,true));
	boardGame.addPiece(new bishop(2,0,true));
	boardGame.addPiece(new queen(3,0,true));
	boardGame.addPiece(new king(4,0,true));
	boardGame.addPiece(new bishop(5,0,true));
	boardGame.addPiece(new knight(6,0,true));
	boardGame.addPiece(new rook(7,0,true));
	for(int i = 0;i<8;i++)
	{
		boardGame.addPiece(new pawn(i,1,true));
	}

	boardGame.addPiece(new rook(0,7,true));
	boardGame.addPiece(new knight(1,7,true));
	boardGame.addPiece(new bishop(2,7,true));
	boardGame.addPiece(new queen(3,7,true));
	boardGame.addPiece(new king(4,7,true));
	boardGame.addPiece(new bishop(5,7,true));
	boardGame.addPiece(new knight(6,7,true));
	boardGame.addPiece(new rook(7,7,true));
	for(int i = 0;i<8;i++)
	{
		boardGame.addPiece(new pawn(i,6,true));
	}

}
game::~game(){}

void game::print()
{
	boardGame.printBoard();
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

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

*/

#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP

#include "coordinate_calculation.hpp"

#include <boost/assert.hpp>

#include <algorithm>
#include <cstdint>
#include <limits>

// TODO: Make template type, add tests
struct RectangleInt2D
{
    RectangleInt2D()
        : min_lon(std::numeric_limits<int32_t>::max()),
          max_lon(std::numeric_limits<int32_t>::min()),
          min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())
    {
    }

    int32_t min_lon, max_lon;
    int32_t min_lat, max_lat;

    void MergeBoundingBoxes(const RectangleInt2D &other)
    {
        min_lon = std::min(min_lon, other.min_lon);
        max_lon = std::max(max_lon, other.max_lon);
        min_lat = std::min(min_lat, other.min_lat);
        max_lat = std::max(max_lat, other.max_lat);
        BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
    }

    FixedPointCoordinate Centroid() const
    {
        FixedPointCoordinate centroid;
        // The coordinates of the midpoints are given by:
        // x = (x1 + x2) /2 and y = (y1 + y2) /2.
        centroid.lon = (min_lon + max_lon) / 2;
        centroid.lat = (min_lat + max_lat) / 2;
        return centroid;
    }

    bool Intersects(const RectangleInt2D &other) const
    {
        FixedPointCoordinate upper_left(other.max_lat, other.min_lon);
        FixedPointCoordinate upper_right(other.max_lat, other.max_lon);
        FixedPointCoordinate lower_right(other.min_lat, other.max_lon);
        FixedPointCoordinate lower_left(other.min_lat, other.min_lon);

        return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||
                Contains(lower_left));
    }

    float GetMinDist(const FixedPointCoordinate &location) const
    {
        const bool is_contained = Contains(location);
        if (is_contained)
        {
            return 0.0f;
        }

        enum Direction
        {
            INVALID = 0,
            NORTH = 1,
            SOUTH = 2,
            EAST = 4,
            NORTH_EAST = 5,
            SOUTH_EAST = 6,
            WEST = 8,
            NORTH_WEST = 9,
            SOUTH_WEST = 10
        };

        Direction d = INVALID;
        if (location.lat > max_lat)
            d = (Direction)(d | NORTH);
        else if (location.lat < min_lat)
            d = (Direction)(d | SOUTH);
        if (location.lon > max_lon)
            d = (Direction)(d | EAST);
        else if (location.lon < min_lon)
            d = (Direction)(d | WEST);

        BOOST_ASSERT(d != INVALID);

        float min_dist = std::numeric_limits<float>::max();
        switch (d)
        {
        case NORTH:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(max_lat, location.lon));
            break;
        case SOUTH:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(min_lat, location.lon));
            break;
        case WEST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(location.lat, min_lon));
            break;
        case EAST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(location.lat, max_lon));
            break;
        case NORTH_EAST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(max_lat, max_lon));
            break;
        case NORTH_WEST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(max_lat, min_lon));
            break;
        case SOUTH_EAST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(min_lat, max_lon));
            break;
        case SOUTH_WEST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(min_lat, min_lon));
            break;
        default:
            break;
        }

        BOOST_ASSERT(min_dist < std::numeric_limits<float>::max());

        return min_dist;
    }

    float GetMinMaxDist(const FixedPointCoordinate &location) const
    {
        float min_max_dist = std::numeric_limits<float>::max();
        // Get minmax distance to each of the four sides
        const FixedPointCoordinate upper_left(max_lat, min_lon);
        const FixedPointCoordinate upper_right(max_lat, max_lon);
        const FixedPointCoordinate lower_right(min_lat, max_lon);
        const FixedPointCoordinate lower_left(min_lat, min_lon);

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, upper_left),
                              coordinate_calculation::euclidean_distance(location, upper_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, upper_right),
                              coordinate_calculation::euclidean_distance(location, lower_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, lower_right),
                              coordinate_calculation::euclidean_distance(location, lower_left)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, lower_left),
                              coordinate_calculation::euclidean_distance(location, upper_left)));
        return min_max_dist;
    }

    bool Contains(const FixedPointCoordinate &location) const
    {
        const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
        const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
        return lats_contained && lons_contained;
    }

    friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)
    {
        out << rect.min_lat / COORDINATE_PRECISION << "," << rect.min_lon / COORDINATE_PRECISION
            << " " << rect.max_lat / COORDINATE_PRECISION << ","
            << rect.max_lon / COORDINATE_PRECISION;
        return out;
    }
};

#endif
<commit_msg>add include to be self-sufficient<commit_after>/*

Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

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

*/

#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP

#include "coordinate_calculation.hpp"

#include <boost/assert.hpp>

#include <osrm/coordinate.hpp>

#include <algorithm>
#include <cstdint>
#include <limits>

// TODO: Make template type, add tests
struct RectangleInt2D
{
    RectangleInt2D()
        : min_lon(std::numeric_limits<int32_t>::max()),
          max_lon(std::numeric_limits<int32_t>::min()),
          min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())
    {
    }

    int32_t min_lon, max_lon;
    int32_t min_lat, max_lat;

    void MergeBoundingBoxes(const RectangleInt2D &other)
    {
        min_lon = std::min(min_lon, other.min_lon);
        max_lon = std::max(max_lon, other.max_lon);
        min_lat = std::min(min_lat, other.min_lat);
        max_lat = std::max(max_lat, other.max_lat);
        BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
    }

    FixedPointCoordinate Centroid() const
    {
        FixedPointCoordinate centroid;
        // The coordinates of the midpoints are given by:
        // x = (x1 + x2) /2 and y = (y1 + y2) /2.
        centroid.lon = (min_lon + max_lon) / 2;
        centroid.lat = (min_lat + max_lat) / 2;
        return centroid;
    }

    bool Intersects(const RectangleInt2D &other) const
    {
        FixedPointCoordinate upper_left(other.max_lat, other.min_lon);
        FixedPointCoordinate upper_right(other.max_lat, other.max_lon);
        FixedPointCoordinate lower_right(other.min_lat, other.max_lon);
        FixedPointCoordinate lower_left(other.min_lat, other.min_lon);

        return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||
                Contains(lower_left));
    }

    float GetMinDist(const FixedPointCoordinate &location) const
    {
        const bool is_contained = Contains(location);
        if (is_contained)
        {
            return 0.0f;
        }

        enum Direction
        {
            INVALID = 0,
            NORTH = 1,
            SOUTH = 2,
            EAST = 4,
            NORTH_EAST = 5,
            SOUTH_EAST = 6,
            WEST = 8,
            NORTH_WEST = 9,
            SOUTH_WEST = 10
        };

        Direction d = INVALID;
        if (location.lat > max_lat)
            d = (Direction)(d | NORTH);
        else if (location.lat < min_lat)
            d = (Direction)(d | SOUTH);
        if (location.lon > max_lon)
            d = (Direction)(d | EAST);
        else if (location.lon < min_lon)
            d = (Direction)(d | WEST);

        BOOST_ASSERT(d != INVALID);

        float min_dist = std::numeric_limits<float>::max();
        switch (d)
        {
        case NORTH:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(max_lat, location.lon));
            break;
        case SOUTH:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(min_lat, location.lon));
            break;
        case WEST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(location.lat, min_lon));
            break;
        case EAST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(location.lat, max_lon));
            break;
        case NORTH_EAST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(max_lat, max_lon));
            break;
        case NORTH_WEST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(max_lat, min_lon));
            break;
        case SOUTH_EAST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(min_lat, max_lon));
            break;
        case SOUTH_WEST:
            min_dist = coordinate_calculation::euclidean_distance(
                location, FixedPointCoordinate(min_lat, min_lon));
            break;
        default:
            break;
        }

        BOOST_ASSERT(min_dist < std::numeric_limits<float>::max());

        return min_dist;
    }

    float GetMinMaxDist(const FixedPointCoordinate &location) const
    {
        float min_max_dist = std::numeric_limits<float>::max();
        // Get minmax distance to each of the four sides
        const FixedPointCoordinate upper_left(max_lat, min_lon);
        const FixedPointCoordinate upper_right(max_lat, max_lon);
        const FixedPointCoordinate lower_right(min_lat, max_lon);
        const FixedPointCoordinate lower_left(min_lat, min_lon);

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, upper_left),
                              coordinate_calculation::euclidean_distance(location, upper_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, upper_right),
                              coordinate_calculation::euclidean_distance(location, lower_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, lower_right),
                              coordinate_calculation::euclidean_distance(location, lower_left)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::euclidean_distance(location, lower_left),
                              coordinate_calculation::euclidean_distance(location, upper_left)));
        return min_max_dist;
    }

    bool Contains(const FixedPointCoordinate &location) const
    {
        const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
        const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
        return lats_contained && lons_contained;
    }

    friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)
    {
        out << rect.min_lat / COORDINATE_PRECISION << "," << rect.min_lon / COORDINATE_PRECISION
            << " " << rect.max_lat / COORDINATE_PRECISION << ","
            << rect.max_lon / COORDINATE_PRECISION;
        return out;
    }
};

#endif
<|endoftext|>


<commit_before>#include <lib/Numeric.hpp>

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <atomic>

struct Fraction
{
    Fraction(uint64_t n, uint64_t d)
        :   numerator(n),
            denominator(d),
            value((double)n / d)
    {

    }

    Fraction(uint64_t n, uint64_t d, double f)
        :   numerator(n),
            denominator(d),
            value(f)
    {

    }

    size_t numerator;
    size_t denominator;
    double value;

    auto operator<(const Fraction& other) const -> bool
    {
        return value < other.value;
    }
};

/**
 * Counting fractions in a range
 * Problem 71
 *
 * Consider the fraction, n/d, where n and d are positive integers.
 * If n < d and HCF(n, d) = 1, it is called a reduced proper fraction.
 *
 * If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get:
 *  1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
 *
 * It can be seen that there are 3 fractions between 1/3 and 1/2.
 *
 * How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d <= 12,000?
 */
int main()
{
    Fraction lower_bound{1, 3};
    Fraction upper_bound{1, 2};
    std::atomic<size_t> worker_position{0};
    std::atomic<size_t> g_count{0};

    std::vector<std::thread> workers;

    constexpr size_t WORKER_COUNT = 8;
    constexpr size_t STOP = 1'000'000;
    constexpr size_t WORK_AMOUNT = 1000;

    for(size_t w = 0; w < WORKER_COUNT; ++w)
    {
        workers.emplace_back(
            [&lower_bound, &upper_bound, &worker_position, &g_count]()
            {
                while(worker_position < STOP)
                {
                    size_t start_idx = worker_position.fetch_add(WORK_AMOUNT);
                    size_t stop_idx = start_idx + WORK_AMOUNT;

                    size_t local_count{0};

                    if(__glibc_unlikely(start_idx == 0))
                    {
                        start_idx = 2;
                    }

                    if(__glibc_unlikely(stop_idx >= STOP))
                    {
                        stop_idx = STOP + 1;
                    }

                    for(size_t d = start_idx; d < stop_idx; ++d)
                    {
                        for(size_t n = 1; n < d; ++n)
                        {
                            // skip anything less than current left fraction
                            double value = ((double)n) / d;
                            if(value <= lower_bound.value)
                            {
                                continue;
                            }
                            // stop entirely if the fraction is now 3/7 or greater.
                            else if(value >= upper_bound.value)
                            {
                                break;
                            }

                            // If the gcd equals 1, reduce the fraction
                            // and save to merge into the global to_the_left var
                            // across threads. These are our candidates to be the
                            // next version
                            auto hcf = lib::gcd(n, d);
                            if(hcf == 1)
                            {
                                ++local_count;
                            }
                        }
                    }

                    g_count += local_count;
                }
            }
        );
    }

    while(worker_position < STOP)
    {
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(1000ms);
        std::cout << worker_position << "\n";
    }

    for(auto& t : workers)
    {
        t.join();
    }

    std::cout << g_count;

    return 0;
}
<commit_msg>add p073 c++ solution<commit_after>#include <lib/Numeric.hpp>

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <atomic>

struct Fraction
{
    Fraction(uint64_t n, uint64_t d)
        :   numerator(n),
            denominator(d),
            value((double)n / d)
    {

    }

    Fraction(uint64_t n, uint64_t d, double f)
        :   numerator(n),
            denominator(d),
            value(f)
    {

    }

    size_t numerator;
    size_t denominator;
    double value;

    auto operator<(const Fraction& other) const -> bool
    {
        return value < other.value;
    }
};

/**
 * Counting fractions in a range
 * Problem 71
 *
 * Consider the fraction, n/d, where n and d are positive integers.
 * If n < d and HCF(n, d) = 1, it is called a reduced proper fraction.
 *
 * If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get:
 *  1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
 *
 * It can be seen that there are 3 fractions between 1/3 and 1/2.
 *
 * How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d <= 12,000?
 */
int main()
{
    Fraction lower_bound{1, 3};
    Fraction upper_bound{1, 2};
    std::atomic<size_t> worker_position{0};
    std::atomic<size_t> g_count{0};

    std::vector<std::thread> workers;

    constexpr size_t WORKER_COUNT = 8;
    constexpr size_t STOP = 12'000;
    constexpr size_t WORK_AMOUNT = 1000;

    for(size_t w = 0; w < WORKER_COUNT; ++w)
    {
        workers.emplace_back(
            [&lower_bound, &upper_bound, &worker_position, &g_count]()
            {
                while(worker_position < STOP)
                {
                    size_t start_idx = worker_position.fetch_add(WORK_AMOUNT);
                    size_t stop_idx = start_idx + WORK_AMOUNT;

                    size_t local_count{0};

                    if(__glibc_unlikely(start_idx == 0))
                    {
                        start_idx = 2;
                    }

                    if(__glibc_unlikely(stop_idx >= STOP))
                    {
                        stop_idx = STOP + 1;
                    }

                    for(size_t d = start_idx; d < stop_idx; ++d)
                    {
                        for(size_t n = 1; n < d; ++n)
                        {
                            // skip anything less than current left fraction
                            double value = ((double)n) / d;
                            if(value <= lower_bound.value)
                            {
                                continue;
                            }
                            // stop entirely if the fraction is now 3/7 or greater.
                            else if(value >= upper_bound.value)
                            {
                                break;
                            }

                            // If the gcd equals 1, reduce the fraction
                            // and save to merge into the global to_the_left var
                            // across threads. These are our candidates to be the
                            // next version
                            auto hcf = lib::gcd(n, d);
                            if(hcf == 1)
                            {
                                ++local_count;
                            }
                        }
                    }

                    g_count += local_count;
                }
            }
        );
    }

    while(worker_position < STOP)
    {
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(1000ms);
        std::cout << worker_position << "\n";
    }

    for(auto& t : workers)
    {
        t.join();
    }

    std::cout << g_count;

    return 0;
}
<|endoftext|>