<commit_before>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#ifdef _WIN32
 #ifdef NIXEXPORT
 #define NIXAPI __declspec(dllexport)
 #else
 #define NIXAPI __declspec(dllimport)
 #endif
#pragma warning(disable: 4250 4251)

 //workaround for missing ssize_t on windows
 #ifndef ssize_t
   #include <BaseTsd.h>
   typedef SSIZE_T ssize_t;
 #endif
#else
 #define NIXAPI
#endif

#ifdef _MSC_VER
#define NOEXCEPT
#else
#define NOEXCEPT noexcept
#endif
<commit_msg>[win] define ssize_t as int in 32 bit windows<commit_after>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#ifdef _WIN32
 #ifdef NIXEXPORT
 #define NIXAPI __declspec(dllexport)
 #else
 #define NIXAPI __declspec(dllimport)
 #endif
#pragma warning(disable: 4250 4251)

 //workaround for missing ssize_t on windows
 #ifndef ssize_t
   #ifdef _WIN64
     #include <BaseTsd.h>
     typedef SSIZE_T ssize_t;
   #else
     //hdf5 defines ssize_t to be int on 32bit Win
     typedef int ssize_t;
   #endif
 #endif
#else
 #define NIXAPI
#endif

#ifdef _MSC_VER
#define NOEXCEPT
#else
#define NOEXCEPT noexcept
#endif
<|endoftext|>


<commit_before><commit_msg>Property::unit(str): Deblank string before unit checks<commit_after><|endoftext|>


<commit_before>#ifndef PROTON_TUPLE_HEADER
#define PROTON_TUPLE_HEADER

/** @file tuple.hpp
 *  @brief tuple support.
 *  Please include this header instead of \<tuple\>.
 */

#include <tuple>
#include <algorithm>
#include <iostream>
#include <initializer_list>
#include <algorithm>
#include <stdexcept>
#include <limits>

#include <proton/base.hpp>

namespace proton{

namespace detail{

constexpr long fix_index(long i, long size)
{
    return (i>size)?
				size
			:(
				(i<0)?
					(i+size < 0 ?
						0
					:
						i+size
					)
				:
					i
			);
}

constexpr long sub_index(long i, long size)
{
    return (i>=size)?
				size-1
			:(
				(i<0)?
					(i+size < 0 ?
						0
					:
						i+size
					)
				:
					i
			);
}

constexpr long get_index(long i, long size)
{
    return (i>=size)?
				-1
			:(
				(i<0)?
					(i+size < 0 ?
						-1
					:
						i+size
					)
				:
					i
			);
}

template<long i, typename ...T>
struct at_index{
	const std::tuple<T...>* p;
	typedef decltype(std::get<get_index(i,sizeof...(T))>(*p)) type;
};

constexpr long fix_size(long begin, long end, long size)
{
	return fix_index(begin,size)>fix_index(end,size)  ?
				0
			:
				fix_index(end,size)-fix_index(begin,size);
}

template<typename ...T>
struct len_t<std::tuple<T...> >{
    static size_t result(const std::tuple<T...>& x)
    {
        return sizeof...(T);
    }
};

template<typename T>
class tuple_size;

template<typename ...T>
class tuple_size<std::tuple<T...> >{
public:
	static constexpr size_t value=sizeof...(T);
};

////////////////////
// build index_tuple<start, ... start+size-1>
////////////////////

template<long... _Indexes>
struct index_tuple;

template<>
struct index_tuple<>
{};

template<long start, long... _Indexes>
struct index_tuple<start, _Indexes...>
{
	typedef index_tuple<start, _Indexes..., start+1+sizeof...(_Indexes)> next;
};

// Builds an _Index_tuple<0, 1, 2, ..., _Num-1>.
template<long begin, long size>
struct build_index_tuple
{
	typedef typename build_index_tuple<begin, size - 1>::type::next type;
};

template<long start>
struct build_index_tuple<start, 1>
{
	typedef index_tuple<start> type;
};

template<long start>
struct build_index_tuple<start, 0>
{
	typedef index_tuple<> type;
};
///////////////////////

///////////////////////
// get the sub type
///////////////////////
template<long, long, typename, typename>
struct make_tuple_impl;

template<long start, long size, typename T, typename... _Tp>
struct make_tuple_impl<start, size, T, std::tuple<_Tp...> >
{
	typedef typename make_tuple_impl<start + 1, size-1,
				T, std::tuple<_Tp..., typename std::tuple_element<start, T>::type>
				>::type
		type;
};

template<long start, typename T, typename... _Tp>
struct make_tuple_impl<start, 0, T, std::tuple<_Tp...>>
{
	typedef std::tuple<_Tp...> type;
};

template<typename T, long start, long size>
struct sub_tuple_type{
	typedef typename make_tuple_impl<start, size, T, std::tuple<> >::type type;
};

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

template<typename retT, typename tupT, typename I>
struct sub_tuple;

template<typename retT, typename tupT, long... i>
struct sub_tuple<retT, tupT, index_tuple<i...> >{
	static retT sub(const tupT& t)
	{
		return retT(std::get<i>(t)...);
	}
};
//////////////////////

} // ns detail

/** @addtogroup tuple
 * @{
 */

/** like x[index] in python
 */

template<long index, typename ...T>
typename detail::at_index<index,T...>::type
	at(const std::tuple<T...>& x)
{
	return std::get<detail::get_index(index,sizeof...(T))>(x);
}

namespace detail{
// helper function to print a tuple of any size
template<typename T, long I>
struct output_tuple {
    static void output(std::ostream& s, const T& t)
    {
        s << at<-I>(t) << ", ";
        output_tuple<T, I-1>::output(s,t);
    }
};

template<typename T>
struct output_tuple<T, 1> {
    static void output(std::ostream& s, const T& t)
    {
        s << at<-1>(t);
    }
};

template<typename T>
struct output_tuple<T, 0> {
    static void output(std::ostream& s, const T& t)
    {
    }
};

} // ns detail

/** get a slice of tuple x[begin:end] in python
 */

template<long begin, long end, typename T>
typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
		detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type sub(const T& t)
{
	typedef typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
			detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type retT;
	return detail::sub_tuple<retT, T,
			typename detail::build_index_tuple<detail::fix_index(begin, detail::tuple_size<T>::value),
					detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type
			>::sub(t);
}
/*
template<long begin, long end=std::numeric_limits<long>::max(), typename ...T>
typename detail::sub_type<std::tuple<T...>, begin, end>::type
	sub(const std::tuple<T...>& x)
{
	typedef typename detail::sub_type<std::tuple<T...>, begin, end>::type ret_t;
#ifdef __clang__
	return ret_t(*reinterpret_cast<const ret_t*>(&std::get<(detail::sub_index(begin, sizeof...(T)))>(x)));
#else
	#ifdef __GNUC__
		return ret_t(*reinterpret_cast<const ret_t*>(&std::get<(detail::sub_index(end-1, sizeof...(T)))>(x)));
	#else
		static_assert(0, "unknown compiler")
	#endif
#endif
}
*/

/** general output for tuple.
 * @param s the output stream
 * @param x the tuple to be outputed
 * @return s
 */
template <typename ...T>
std::ostream& operator<<(std::ostream& s, const std::tuple<T...>& x)
{
    s << "(";
    detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
    s << ")";
    return s;
}

template <typename ...T>
std::wostream& operator<<(std::wostream& s, const std::tuple<T...>& x)
{
    s << L"(";
    detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
    s << L")";
    return s;
}

/** tuple + tuple
 */
template<typename T2, typename ...T1>
auto operator+(const std::tuple<T1...>& x, T2&& y) -> decltype(std::tuple_cat(x,y))
{
	return std::tuple_cat(x,y);
}

template<typename T2, typename ...T1>
auto operator+(std::tuple<T1...>&& x, T2&& y) -> decltype(std::tuple_cat(x,y))
{
	return std::tuple_cat(x,y);
}

/** eq to make_tuple
 */
template<typename ...T>
auto _t(T&& ...x) -> decltype(std::make_tuple(x...))
{
	return std::make_tuple(x...);
}

/** eq to forward_as_tuple
 */
template<typename ...T>
auto _f(T&& ...x) -> decltype(std::forward_as_tuple(x...))
{
	return std::forward_as_tuple(x...);
}

#if 0
/* vector_ * n
 */
template<typename T, typename A>
vector_<T,A> operator*(const std::vector<T,A>& s, size_t n)
{
    vector_<T,A> r;
    r.reserve(s.size()*n);
    for(size_t i=0; i<n; i++)
        r.extend(s);
    return r;
}

/* n * vector_
 */
template<typename T, typename A>
vector_<T,A> operator*(size_t n, const std::vector<T,A>& s)
{
    return s*n;
}
#endif

/**
 * @example tuple.cpp
 * @}
 */
}

#endif // PROTON_TUPLE_HEADER
<commit_msg>simplify tuple +<commit_after>#ifndef PROTON_TUPLE_HEADER
#define PROTON_TUPLE_HEADER

/** @file tuple.hpp
 *  @brief tuple support.
 *  Please include this header instead of \<tuple\>.
 */

#include <tuple>
#include <algorithm>
#include <iostream>
#include <initializer_list>
#include <algorithm>
#include <stdexcept>
#include <limits>

#include <proton/base.hpp>

namespace proton{

namespace detail{

constexpr long fix_index(long i, long size)
{
    return (i>size)?
				size
			:(
				(i<0)?
					(i+size < 0 ?
						0
					:
						i+size
					)
				:
					i
			);
}

constexpr long sub_index(long i, long size)
{
    return (i>=size)?
				size-1
			:(
				(i<0)?
					(i+size < 0 ?
						0
					:
						i+size
					)
				:
					i
			);
}

constexpr long get_index(long i, long size)
{
    return (i>=size)?
				-1
			:(
				(i<0)?
					(i+size < 0 ?
						-1
					:
						i+size
					)
				:
					i
			);
}

template<long i, typename ...T>
struct at_index{
	const std::tuple<T...>* p;
	typedef decltype(std::get<get_index(i,sizeof...(T))>(*p)) type;
};

constexpr long fix_size(long begin, long end, long size)
{
	return fix_index(begin,size)>fix_index(end,size)  ?
				0
			:
				fix_index(end,size)-fix_index(begin,size);
}

template<typename ...T>
struct len_t<std::tuple<T...> >{
    static size_t result(const std::tuple<T...>& x)
    {
        return sizeof...(T);
    }
};

template<typename T>
class tuple_size;

template<typename ...T>
class tuple_size<std::tuple<T...> >{
public:
	static constexpr size_t value=sizeof...(T);
};

////////////////////
// build index_tuple<start, ... start+size-1>
////////////////////

template<long... _Indexes>
struct index_tuple;

template<>
struct index_tuple<>
{};

template<long start, long... _Indexes>
struct index_tuple<start, _Indexes...>
{
	typedef index_tuple<start, _Indexes..., start+1+sizeof...(_Indexes)> next;
};

// Builds an _Index_tuple<0, 1, 2, ..., _Num-1>.
template<long begin, long size>
struct build_index_tuple
{
	typedef typename build_index_tuple<begin, size - 1>::type::next type;
};

template<long start>
struct build_index_tuple<start, 1>
{
	typedef index_tuple<start> type;
};

template<long start>
struct build_index_tuple<start, 0>
{
	typedef index_tuple<> type;
};
///////////////////////

///////////////////////
// get the sub type
///////////////////////
template<long, long, typename, typename>
struct make_tuple_impl;

template<long start, long size, typename T, typename... _Tp>
struct make_tuple_impl<start, size, T, std::tuple<_Tp...> >
{
	typedef typename make_tuple_impl<start + 1, size-1,
				T, std::tuple<_Tp..., typename std::tuple_element<start, T>::type>
				>::type
		type;
};

template<long start, typename T, typename... _Tp>
struct make_tuple_impl<start, 0, T, std::tuple<_Tp...>>
{
	typedef std::tuple<_Tp...> type;
};

template<typename T, long start, long size>
struct sub_tuple_type{
	typedef typename make_tuple_impl<start, size, T, std::tuple<> >::type type;
};

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

template<typename retT, typename tupT, typename I>
struct sub_tuple;

template<typename retT, typename tupT, long... i>
struct sub_tuple<retT, tupT, index_tuple<i...> >{
	static retT sub(const tupT& t)
	{
		return retT(std::get<i>(t)...);
	}
};
//////////////////////

} // ns detail

/** @addtogroup tuple
 * @{
 */

/** like x[index] in python
 */

template<long index, typename ...T>
typename detail::at_index<index,T...>::type
	at(const std::tuple<T...>& x)
{
	return std::get<detail::get_index(index,sizeof...(T))>(x);
}

namespace detail{
// helper function to print a tuple of any size
template<typename T, long I>
struct output_tuple {
    static void output(std::ostream& s, const T& t)
    {
        s << at<-I>(t) << ", ";
        output_tuple<T, I-1>::output(s,t);
    }
};

template<typename T>
struct output_tuple<T, 1> {
    static void output(std::ostream& s, const T& t)
    {
        s << at<-1>(t);
    }
};

template<typename T>
struct output_tuple<T, 0> {
    static void output(std::ostream& s, const T& t)
    {
    }
};

} // ns detail

/** get a slice of tuple x[begin:end] in python
 */

template<long begin, long end=std::numeric_limits<long>::max(), typename T>
typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
		detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type sub(const T& t)
{
	typedef typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
			detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type retT;
	return detail::sub_tuple<retT, T,
			typename detail::build_index_tuple<detail::fix_index(begin, detail::tuple_size<T>::value),
					detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type
			>::sub(t);
}
/*
template<long begin, long end=std::numeric_limits<long>::max(), typename ...T>
typename detail::sub_type<std::tuple<T...>, begin, end>::type
	sub(const std::tuple<T...>& x)
{
	typedef typename detail::sub_type<std::tuple<T...>, begin, end>::type ret_t;
#ifdef __clang__
	return ret_t(*reinterpret_cast<const ret_t*>(&std::get<(detail::sub_index(begin, sizeof...(T)))>(x)));
#else
	#ifdef __GNUC__
		return ret_t(*reinterpret_cast<const ret_t*>(&std::get<(detail::sub_index(end-1, sizeof...(T)))>(x)));
	#else
		static_assert(0, "unknown compiler")
	#endif
#endif
}
*/

/** general output for tuple.
 * @param s the output stream
 * @param x the tuple to be outputed
 * @return s
 */
template <typename ...T>
std::ostream& operator<<(std::ostream& s, const std::tuple<T...>& x)
{
    s << "(";
    detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
    s << ")";
    return s;
}

template <typename ...T>
std::wostream& operator<<(std::wostream& s, const std::tuple<T...>& x)
{
    s << L"(";
    detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
    s << L")";
    return s;
}

/** tuple + tuple
 */
template<typename... T2, typename... T1>
std::tuple<T1..., T2...> operator+(const std::tuple<T1...>& x, const std::tuple<T2...>& y)
{
	return std::tuple_cat(x,y);
}

template<typename T2, typename ...T1>
auto operator+(std::tuple<T1...>&& x, T2&& y) -> decltype(std::tuple_cat(x,y))
{
	return std::tuple_cat(x,y);
}

/** eq to make_tuple
 */
template<typename ...T>
auto _t(T&& ...x) -> decltype(std::make_tuple(x...))
{
	return std::make_tuple(x...);
}

/** eq to forward_as_tuple
 */
template<typename ...T>
auto _f(T&& ...x) -> decltype(std::forward_as_tuple(x...))
{
	return std::forward_as_tuple(x...);
}

#if 0
/* vector_ * n
 */
template<typename T, typename A>
vector_<T,A> operator*(const std::vector<T,A>& s, size_t n)
{
    vector_<T,A> r;
    r.reserve(s.size()*n);
    for(size_t i=0; i<n; i++)
        r.extend(s);
    return r;
}

/* n * vector_
 */
template<typename T, typename A>
vector_<T,A> operator*(size_t n, const std::vector<T,A>& s)
{
    return s*n;
}
#endif

/**
 * @example tuple.cpp
 * @}
 */
}

#endif // PROTON_TUPLE_HEADER
<|endoftext|>


<commit_before>/*
** Copyright 2011-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <sstream>
#include <QHostAddress>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/influxdb/influxdb.hh"

using namespace com::centreon::broker;

static const char* query_header =
    "[{\"name\":\"metric_data\",\"columns\":[\"time\", \"metric_id\", \"name\", \"interval\", \"value\", \"value_type\"],\"points\":[";
static const char* query_footer = "]}]";

/**
 *  Constructor.
 */
influxdb::influxdb::influxdb(
            std::string const& user,
            std::string const& passwd,
            std::string const& addr,
            unsigned short port,
            std::string const& db)
  : _host(addr),
    _port(port) {
  _connect_socket();
  _socket->close();

  std::string base_url;
  base_url
    .append("/db/").append(db)
    .append("/series?u=").append(user)
    .append("&p=").append(passwd)
    .append("&time_precision=s");
  _post_header.append("POST ").append(base_url).append(" HTTP/1.0\n");
}

/**
 *  Copy constructor.
 *
 *  @param[in] f Object to copy.
 */
influxdb::influxdb::influxdb(influxdb const& f) {
  influxdb::operator=(f);
}

/**
 *  Destructor.
 */
influxdb::influxdb::~influxdb() {}

/**
 *  Assignment operator.
 *
 *  @param[in] f Object to copy.
 *
 *  @return This object.
 */
influxdb::influxdb& influxdb::influxdb::operator=(influxdb const& f) {
  if (this != &f) {
    _query = f._query;
  }
  return (*this);
}

/**
 *  Clear the query.
 */
void influxdb::influxdb::clear() {
  _query.clear();
}

/**
 *  Write a metric to the query.
 *
 *  @param[in] m  The metric to write.
 */
void influxdb::influxdb::write(storage::metric const& m) {
  std::stringstream s;

  s << "["
    << m.ctime << ","
    << m.metric_id << ","
    << "\"" << m.name.toStdString() << "\"" << ","
    << m.interval << ","
    << m.value << ","
    << m.value_type
    << "]";
  if (!_query.empty())
    _query.append(",");
  _query.append(s.str());
}

/**
 *  Commit a query.
 */
void influxdb::influxdb::commit() {
  if (_query.empty())
    return ;

  std::stringstream content_length;
  size_t length = _query.size() + ::strlen(query_header) + ::strlen(query_footer);
  content_length << "Content-Length: " << length << "\n";

  std::string final_query;
  final_query.reserve(length + _post_header.size() + content_length.str().size() + 1);
  final_query
    .append(_post_header).append(content_length.str()).append("\n")
    .append(query_header).append(_query).append(query_footer);

  _connect_socket();

  if (_socket->write(final_query.c_str(), final_query.size())
        != final_query.size())
    throw exceptions::msg()
      << "influxdb: couldn't commit data to influxdb with address '"
      << _socket->peerAddress().toString()
      << "' and port '" << _socket->peerPort() << "': "
      << _socket->errorString();

  _socket->waitForBytesWritten();

  _query.clear();
}

/**
 *  Connect the socket to the endpoint.
 */
void influxdb::influxdb::_connect_socket() {
  _socket.reset(new QTcpSocket);
  _socket->connectToHost(QString::fromStdString(_host), _port);
  if (!_socket->waitForConnected())
    throw exceptions::msg()
      << "influxdb: couldn't connect to influxdb with address '"
      << _host << "' and port '" << _port << "': " << _socket->error();
}
<commit_msg>Influxdb: Print error string instead of error number when failing to connect.<commit_after>/*
** Copyright 2011-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <sstream>
#include <QHostAddress>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/influxdb/influxdb.hh"

using namespace com::centreon::broker;

static const char* query_header =
    "[{\"name\":\"metric_data\",\"columns\":[\"time\", \"metric_id\", \"name\", \"interval\", \"value\", \"value_type\"],\"points\":[";
static const char* query_footer = "]}]";

/**
 *  Constructor.
 */
influxdb::influxdb::influxdb(
            std::string const& user,
            std::string const& passwd,
            std::string const& addr,
            unsigned short port,
            std::string const& db)
  : _host(addr),
    _port(port) {
  _connect_socket();
  _socket->close();

  std::string base_url;
  base_url
    .append("/db/").append(db)
    .append("/series?u=").append(user)
    .append("&p=").append(passwd)
    .append("&time_precision=s");
  _post_header.append("POST ").append(base_url).append(" HTTP/1.0\n");
}

/**
 *  Copy constructor.
 *
 *  @param[in] f Object to copy.
 */
influxdb::influxdb::influxdb(influxdb const& f) {
  influxdb::operator=(f);
}

/**
 *  Destructor.
 */
influxdb::influxdb::~influxdb() {}

/**
 *  Assignment operator.
 *
 *  @param[in] f Object to copy.
 *
 *  @return This object.
 */
influxdb::influxdb& influxdb::influxdb::operator=(influxdb const& f) {
  if (this != &f) {
    _query = f._query;
  }
  return (*this);
}

/**
 *  Clear the query.
 */
void influxdb::influxdb::clear() {
  _query.clear();
}

/**
 *  Write a metric to the query.
 *
 *  @param[in] m  The metric to write.
 */
void influxdb::influxdb::write(storage::metric const& m) {
  std::stringstream s;

  s << "["
    << m.ctime << ","
    << m.metric_id << ","
    << "\"" << m.name.toStdString() << "\"" << ","
    << m.interval << ","
    << m.value << ","
    << m.value_type
    << "]";
  if (!_query.empty())
    _query.append(",");
  _query.append(s.str());
}

/**
 *  Commit a query.
 */
void influxdb::influxdb::commit() {
  if (_query.empty())
    return ;

  std::stringstream content_length;
  size_t length = _query.size() + ::strlen(query_header) + ::strlen(query_footer);
  content_length << "Content-Length: " << length << "\n";

  std::string final_query;
  final_query.reserve(length + _post_header.size() + content_length.str().size() + 1);
  final_query
    .append(_post_header).append(content_length.str()).append("\n")
    .append(query_header).append(_query).append(query_footer);

  _connect_socket();

  if (_socket->write(final_query.c_str(), final_query.size())
        != final_query.size())
    throw exceptions::msg()
      << "influxdb: couldn't commit data to influxdb with address '"
      << _socket->peerAddress().toString()
      << "' and port '" << _socket->peerPort() << "': "
      << _socket->errorString();

  _socket->waitForBytesWritten();

  _query.clear();
}

/**
 *  Connect the socket to the endpoint.
 */
void influxdb::influxdb::_connect_socket() {
  _socket.reset(new QTcpSocket);
  _socket->connectToHost(QString::fromStdString(_host), _port);
  if (!_socket->waitForConnected())
    throw exceptions::msg()
      << "influxdb: couldn't connect to influxdb with address '"
      << _host << "' and port '" << _port << "': " << _socket->errorString();
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>

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

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

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

#include "entityupdateadapter.h"

#include <akonadi/session.h>
#include <akonadi/collectionfetchjob.h>
#include <akonadi/collectionmodifyjob.h>
#include <akonadi/collectiondeletejob.h>
#include <akonadi/collectioncreatejob.h>
#include <akonadi/collectioncopyjob.h>
#include <akonadi/collectionstatisticsjob.h>
#include <akonadi/collectionstatistics.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemmovejob.h>
#include <akonadi/itemdeletejob.h>
#include <akonadi/itemcreatejob.h>
#include <akonadi/itemmodifyjob.h>
#include <akonadi/transactionsequence.h>
#include <akonadi/entitydisplayattribute.h>
#include "collectionchildorderattribute.h"

#include <QVariant>
#include <QStringList>

#include <kdebug.h>

using namespace Akonadi;

EntityUpdateAdapter::EntityUpdateAdapter( Session *s, ItemFetchScope scope, QObject *parent, int includeUnsubscribed )
    : QObject( parent ), m_session( s ), m_job_parent( s ), m_itemFetchScope( scope )
{

  m_includeUnsubscribed = ( includeUnsubscribed == IncludeUnsubscribed ) ? true : false;
}

void EntityUpdateAdapter::addEntities( Item::List newItems, Collection::List newCollections, Collection parent, int row )
{

}

void EntityUpdateAdapter::beginTransaction()
{
//   m_job_parent = new TransactionSequence(m_session);
}

void EntityUpdateAdapter::endTransaction()
{
//   delete m_job_parent;
//   m_job_parent = m_session;
}

void EntityUpdateAdapter::fetchCollections( Collection col, CollectionFetchJob::Type type )
{
  CollectionFetchJob *job = new CollectionFetchJob( col, type, m_job_parent );
  job->includeUnsubscribed( m_includeUnsubscribed );
  connect( job, SIGNAL( collectionsReceived( Akonadi::Collection::List ) ),
           this, SIGNAL( collectionsReceived( Akonadi::Collection::List ) ) );
  connect( job, SIGNAL( result( KJob* ) ), this, SLOT( listJobDone( KJob* ) ) );

}

void EntityUpdateAdapter::fetchItems( Item::List items )
{

}

void EntityUpdateAdapter::fetchItems( Collection parent )
{
  Akonadi::ItemFetchJob *itemJob = new Akonadi::ItemFetchJob( parent, m_job_parent );
  itemJob->setFetchScope( m_itemFetchScope );

  // ### HACK: itemsAdded needs to know which collection items were added to.
  // That is not provided by akonadi, so we attach it in a property.
  itemJob->setProperty( ItemFetchCollectionId(), QVariant( parent.id() ) );

  connect( itemJob, SIGNAL( itemsReceived( Akonadi::Item::List ) ),
           this, SLOT( itemsReceivedFromJob( Akonadi::Item::List ) ) );
  connect( itemJob, SIGNAL( result( KJob* ) ),
           this, SLOT( listJobDone( KJob* ) ) );
}

void EntityUpdateAdapter::itemsReceivedFromJob( Akonadi::Item::List list )
{
  QObject *job = this->sender();
  kDebug() << job;
  if ( job ) {
    Collection::Id colId = job->property( ItemFetchCollectionId() ).value<Collection::Id>();
    kDebug() << colId;
    emit itemsReceived( list, colId );
  }
}

void EntityUpdateAdapter::moveEntities( Item::List movedItems, Collection::List movedCollections, Collection src, Collection dst, int row )
{
  kDebug() << movedItems.size() << movedCollections.size() << src.remoteId() << dst.remoteId();

  // TODO: Use row to update the CollectionChildOrderAttribute correctly.

  TransactionSequence *transaction = new TransactionSequence( m_session );

  foreach( Collection col, movedCollections ) {
    // This is effectively a collectionmovejob.
    col.setParent( dst.id() );
    Akonadi::CollectionModifyJob *modifyJob = new Akonadi::CollectionModifyJob( col, transaction );
//     Akonadi::CollectionModifyJob *modifyJob = new Akonadi::CollectionModifyJob(col, m_job_parent);
  }
  foreach( Item item, movedItems ) {
    // This doesn't have any effect on the resource.
    Akonadi::ItemMoveJob *itemMoveJob = new Akonadi::ItemMoveJob( item, dst, transaction );
//     Akonadi::ItemMoveJob *itemMoveJob = new Akonadi::ItemMoveJob(item, dst, m_job_parent);
  }

  if ( src.hasAttribute<CollectionChildOrderAttribute>() ) {
    // Update the source collection...
    CollectionChildOrderAttribute *srcCcoa = src.attribute<CollectionChildOrderAttribute>();
    QStringList srcl = srcCcoa->orderList();
    kDebug() << srcl;
    foreach( Collection col, movedCollections ) {
      srcl.removeOne( col.remoteId() );
    }
    foreach( Item item, movedItems ) {
      srcl.removeOne( item.remoteId() );
    }
    kDebug() << srcl;
    srcCcoa->setOrderList( srcl );
    src.addAttribute( srcCcoa );

    // ... And the destination collection.
    CollectionChildOrderAttribute *dstCcoa = dst.attribute<CollectionChildOrderAttribute>();
    QStringList dstl = dstCcoa->orderList();
    kDebug() << dstl;
    foreach( Collection col, movedCollections ) {
      dstl.append( col.remoteId() );
    }
    foreach( Item item, movedItems ) {
      dstl.append( item.remoteId() );
    }
    kDebug() << dstl;
    dstCcoa->setOrderList( dstl );
    dst.addAttribute( dstCcoa );

    Akonadi::CollectionModifyJob *srcModifyJob = new Akonadi::CollectionModifyJob( src, transaction );
//     Akonadi::CollectionModifyJob *srcModifyJob = new Akonadi::CollectionModifyJob( src, m_job_parent );
    if ( dst != src ) {
      Akonadi::CollectionModifyJob *dstModifyJob = new Akonadi::CollectionModifyJob( dst, transaction );
//       Akonadi::CollectionModifyJob *dstModifyJob = new Akonadi::CollectionModifyJob( dst, m_job_parent );
    }
  }
}

void EntityUpdateAdapter::removeEntities( Item::List removedItems, Collection::List removedCollections, Collection parent )
{

}

void EntityUpdateAdapter::updateEntities( Collection::List updatedCollections, Item::List updatedItems )
{

}

void EntityUpdateAdapter::updateEntities( Collection::List updatedCollections )
{

}

void EntityUpdateAdapter::updateEntities( Item::List updatedItems )
{
  foreach( Item item, updatedItems ) {
    Akonadi::ItemModifyJob *itemModifyJob = new Akonadi::ItemModifyJob( item, m_job_parent );
  }
}

void EntityUpdateAdapter::listJobDone( KJob *job )
{
  if ( job->error() ) {
    kWarning( 5250 ) << "Job error: " << job->errorString() << endl;
  }
}

void EntityUpdateAdapter::updateJobDone( KJob *job )
{
  if ( job->error() ) {
    // TODO: handle job errors
    kWarning( 5250 ) << "Job error:" << job->errorString();
  } else {
    // TODO: Is this trying to do the job of collectionstatisticschanged?
//     CollectionStatisticsJob *csjob = static_cast<CollectionStatisticsJob*>( job );
//     Collection result = csjob->collection();
//     collectionStatisticsChanged( result.id(), csjob->statistics() );
  }
}

// #include "entityupdateadapter.moc"
<commit_msg>Make the update adapter take ownership of the session.<commit_after>/*
    Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>

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

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

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

#include "entityupdateadapter.h"

#include <akonadi/session.h>
#include <akonadi/collectionfetchjob.h>
#include <akonadi/collectionmodifyjob.h>
#include <akonadi/collectiondeletejob.h>
#include <akonadi/collectioncreatejob.h>
#include <akonadi/collectioncopyjob.h>
#include <akonadi/collectionstatisticsjob.h>
#include <akonadi/collectionstatistics.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemmovejob.h>
#include <akonadi/itemdeletejob.h>
#include <akonadi/itemcreatejob.h>
#include <akonadi/itemmodifyjob.h>
#include <akonadi/transactionsequence.h>
#include <akonadi/entitydisplayattribute.h>
#include "collectionchildorderattribute.h"

#include <QVariant>
#include <QStringList>

#include <kdebug.h>

using namespace Akonadi;

EntityUpdateAdapter::EntityUpdateAdapter( Session *s, ItemFetchScope scope, QObject *parent, int includeUnsubscribed )
    : QObject( parent ), m_session( s ), m_job_parent( s ), m_itemFetchScope( scope )
{

  m_includeUnsubscribed = ( includeUnsubscribed == IncludeUnsubscribed ) ? true : false;

  m_session->setParent(this);

}

EntityUpdateAdapter::~EntityUpdateAdapter()
{
  delete m_job_parent;
}

void EntityUpdateAdapter::addEntities( Item::List newItems, Collection::List newCollections, Collection parent, int row )
{

}

void EntityUpdateAdapter::beginTransaction()
{
  m_job_parent = new TransactionSequence(m_session);
}

void EntityUpdateAdapter::endTransaction()
{
  m_job_parent = m_session;
}

void EntityUpdateAdapter::fetchCollections( Collection col, CollectionFetchJob::Type type )
{
  CollectionFetchJob *job = new CollectionFetchJob( col, type, m_job_parent );
  job->includeUnsubscribed( m_includeUnsubscribed );
  connect( job, SIGNAL( collectionsReceived( Akonadi::Collection::List ) ),
           this, SIGNAL( collectionsReceived( Akonadi::Collection::List ) ) );
  connect( job, SIGNAL( result( KJob* ) ), this, SLOT( listJobDone( KJob* ) ) );

}

void EntityUpdateAdapter::fetchItems( Item::List items )
{

}

void EntityUpdateAdapter::fetchItems( Collection parent )
{
  Akonadi::ItemFetchJob *itemJob = new Akonadi::ItemFetchJob( parent, m_job_parent );
  itemJob->setFetchScope( m_itemFetchScope );

  // ### HACK: itemsAdded needs to know which collection items were added to.
  // That is not provided by akonadi, so we attach it in a property.
  itemJob->setProperty( ItemFetchCollectionId(), QVariant( parent.id() ) );

  connect( itemJob, SIGNAL( itemsReceived( Akonadi::Item::List ) ),
           this, SLOT( itemsReceivedFromJob( Akonadi::Item::List ) ) );
  connect( itemJob, SIGNAL( result( KJob* ) ),
           this, SLOT( listJobDone( KJob* ) ) );
}

void EntityUpdateAdapter::itemsReceivedFromJob( Akonadi::Item::List list )
{
  QObject *job = this->sender();
  kDebug() << job;
  if ( job ) {
    Collection::Id colId = job->property( ItemFetchCollectionId() ).value<Collection::Id>();
    kDebug() << colId;
    emit itemsReceived( list, colId );
  }
}

void EntityUpdateAdapter::moveEntities( Item::List movedItems, Collection::List movedCollections, Collection src, Collection dst, int row )
{
  kDebug() << movedItems.size() << movedCollections.size() << src.remoteId() << dst.remoteId();

  // TODO: Use row to update the CollectionChildOrderAttribute correctly.

  TransactionSequence *transaction = new TransactionSequence( m_session );

  foreach( Collection col, movedCollections ) {
    // This is effectively a collectionmovejob.
    col.setParent( dst.id() );
    Akonadi::CollectionModifyJob *modifyJob = new Akonadi::CollectionModifyJob( col, transaction );
//     Akonadi::CollectionModifyJob *modifyJob = new Akonadi::CollectionModifyJob(col, m_job_parent);
  }
  foreach( Item item, movedItems ) {
    // This doesn't have any effect on the resource.
    Akonadi::ItemMoveJob *itemMoveJob = new Akonadi::ItemMoveJob( item, dst, transaction );
//     Akonadi::ItemMoveJob *itemMoveJob = new Akonadi::ItemMoveJob(item, dst, m_job_parent);
  }

  if ( src.hasAttribute<CollectionChildOrderAttribute>() ) {
    // Update the source collection...
    CollectionChildOrderAttribute *srcCcoa = src.attribute<CollectionChildOrderAttribute>();
    QStringList srcl = srcCcoa->orderList();
    kDebug() << srcl;
    foreach( Collection col, movedCollections ) {
      srcl.removeOne( col.remoteId() );
    }
    foreach( Item item, movedItems ) {
      srcl.removeOne( item.remoteId() );
    }
    kDebug() << srcl;
    srcCcoa->setOrderList( srcl );
    src.addAttribute( srcCcoa );

    // ... And the destination collection.
    CollectionChildOrderAttribute *dstCcoa = dst.attribute<CollectionChildOrderAttribute>();
    QStringList dstl = dstCcoa->orderList();
    kDebug() << dstl;
    foreach( Collection col, movedCollections ) {
      dstl.append( col.remoteId() );
    }
    foreach( Item item, movedItems ) {
      dstl.append( item.remoteId() );
    }
    kDebug() << dstl;
    dstCcoa->setOrderList( dstl );
    dst.addAttribute( dstCcoa );

    Akonadi::CollectionModifyJob *srcModifyJob = new Akonadi::CollectionModifyJob( src, transaction );
//     Akonadi::CollectionModifyJob *srcModifyJob = new Akonadi::CollectionModifyJob( src, m_job_parent );
    if ( dst != src ) {
      Akonadi::CollectionModifyJob *dstModifyJob = new Akonadi::CollectionModifyJob( dst, transaction );
//       Akonadi::CollectionModifyJob *dstModifyJob = new Akonadi::CollectionModifyJob( dst, m_job_parent );
    }
  }
}

void EntityUpdateAdapter::removeEntities( Item::List removedItems, Collection::List removedCollections, Collection parent )
{

}

void EntityUpdateAdapter::updateEntities( Collection::List updatedCollections, Item::List updatedItems )
{

}

void EntityUpdateAdapter::updateEntities( Collection::List updatedCollections )
{

}

void EntityUpdateAdapter::updateEntities( Item::List updatedItems )
{
  foreach( Item item, updatedItems ) {
    Akonadi::ItemModifyJob *itemModifyJob = new Akonadi::ItemModifyJob( item, m_job_parent );
  }
}

void EntityUpdateAdapter::listJobDone( KJob *job )
{
  if ( job->error() ) {
    kWarning( 5250 ) << "Job error: " << job->errorString() << endl;
  }
}

void EntityUpdateAdapter::updateJobDone( KJob *job )
{
  if ( job->error() ) {
    // TODO: handle job errors
    kWarning( 5250 ) << "Job error:" << job->errorString();
  } else {
    // TODO: Is this trying to do the job of collectionstatisticschanged?
//     CollectionStatisticsJob *csjob = static_cast<CollectionStatisticsJob*>( job );
//     Collection result = csjob->collection();
//     collectionStatisticsChanged( result.id(), csjob->statistics() );
  }
}

// #include "entityupdateadapter.moc"
<|endoftext|>


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

#include "qtrackerrelationshipsaverequest.h"

#include <QtTracker/Tracker>
#include <QtTracker/ontologies/nco.h>
#include <QHash>
using namespace SopranoLive;

QTrackerRelationshipSaveRequest::QTrackerRelationshipSaveRequest(QContactAbstractRequest* req, QContactManagerEngine* parent)
: QObject(parent), QTrackerContactAsyncRequest(req)
{
    Q_ASSERT(req);
    Q_ASSERT(req->type() == QContactAbstractRequest::RelationshipSaveRequest);

    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (!r)
    {
        commitError(QString());
    }

    QList<QContactRelationship> links = r->relationships();
    if(links.isEmpty()) {
        QMap<int, QContactManager::Error> errors;
        errors[0] = QContactManager::BadArgumentError;
        QContactManagerEngine::updateRelationshipSaveRequest(r, links, QContactManager::BadArgumentError, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
        return;
    }
    QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::ActiveState);

    // the logic is like this
    // 1) get contacts (first() and second())
    // 2) when that is done set all metacontacts of 1sts to 2nds

    QSet<QString> ids;
    foreach(QContactRelationship rel, links)
    {
        ids << QString::number(rel.first().localId());
        ids << QString::number(rel.second().localId());
    }

    RDFVariable contact;
    QStringList idstrings(QStringList(ids.toList()));
    contact.property<nco::contactUID>().isMemberOf(idstrings);
    m_nodes = ::tracker()->modelVariable(contact);

    // need to store LiveNodes in order to receive notification from model
    QObject::connect(m_nodes.model(), SIGNAL(modelUpdated()), this, SLOT(nodesDataReady()));

}

void QTrackerRelationshipSaveRequest::nodesDataReady()
{
    // now that nodes are ready we can enumerate them without blocking
    RDFTransactionPtr transaction_ = ::tracker()->initiateTransaction();
    connect(transaction_.data(), SIGNAL(commitFinished()), this, SLOT(commitFinished()));
    connect(transaction_.data(), SIGNAL(commitError(QString)), this, SLOT(commitError(QString)));

    QHash<QString, Live<nco::PersonContact> > lContacts;
    for(int i = 0; i < m_nodes->rowCount(); i++)
    {
        Live<nco::PersonContact> contact = m_nodes->liveNode(i);
        lContacts[contact->getContactUID()] = contact;
    }
    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (!r)
        commitError(QString());
    QList<QContactRelationship> links = r->relationships();
    foreach(QContactRelationship rel, links)
    {
        Live<nco::PersonContact> first = lContacts.value(QString::number(rel.first().localId()));
        Live<nco::PersonContact> second = lContacts.value(QString::number(rel.second().localId()));
        //TODO: we should prefer the local contact information over the remote info.
        mergeContacts(first, second);
    }

    transaction_->commit(false);
    // temporary fix - signals not yet implemented in libqttracker
    commitFinished();
}

void QTrackerRelationshipSaveRequest::mergeContacts(const Live<nco::PersonContact>& preferedContact, const Live<nco::PersonContact>& inferiorContact)
{
   QList<LiveNode> mergedNodes = preferedContact->getHasIMAddresss();
   mergedNodes += inferiorContact->getHasIMAddresss();
   preferedContact->setHasIMAddresss( mergedNodes );
   RDFVariable rdfInferior = inferiorContact->iri();
   ::tracker()->removeResources(rdfInferior);
}

void QTrackerRelationshipSaveRequest::commitFinished()
{
    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (r && r->isActive())
    {
        QContactManager::Error error = QContactManager::NoError;
        QMap<int, QContactManager::Error> errors;
        errors[0] = error;
        QContactManagerEngine::updateRelationshipSaveRequest(r, r->relationships(), error, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
    }
    else
        qWarning()<<Q_FUNC_INFO<<r;
}

void QTrackerRelationshipSaveRequest::commitError(QString message)
{
    qWarning()<<Q_FUNC_INFO<<message;
    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (r)
    {
        QContactManager::Error error = QContactManager::InvalidRelationshipError;
        QMap<int, QContactManager::Error> errors;
        errors[0] = error;
        QContactManagerEngine::updateRelationshipSaveRequest(r, r->relationships(), error, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
    }
    else
    {
        QMap<int, QContactManager::Error> errors;
        errors[0] = QContactManager::UnspecifiedError;
        QContactManagerEngine::updateRelationshipSaveRequest(r, QList<QContactRelationship>(), QContactManager::UnspecifiedError, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
        return;
    }
}

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

#include "qtrackerrelationshipsaverequest.h"

#include <QtTracker/Tracker>
#include <QtTracker/ontologies/nco.h>
#include <QHash>
using namespace SopranoLive;

QTrackerRelationshipSaveRequest::QTrackerRelationshipSaveRequest(QContactAbstractRequest* req, QContactManagerEngine* parent)
: QObject(parent), QTrackerContactAsyncRequest(req)
{
    Q_ASSERT(req);
    Q_ASSERT(req->type() == QContactAbstractRequest::RelationshipSaveRequest);

    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (!r)
    {
        commitError(QString());
    }

    QList<QContactRelationship> links = r->relationships();
    if(links.isEmpty()) {
        QMap<int, QContactManager::Error> errors;
        errors[0] = QContactManager::BadArgumentError;
        QContactManagerEngine::updateRelationshipSaveRequest(r, links, QContactManager::BadArgumentError, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
        return;
    }
    QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::ActiveState);

    // the logic is like this
    // 1) get contacts (first() and second())
    // 2) when that is done set all metacontacts of 1sts to 2nds

    QSet<QString> ids;
    foreach(QContactRelationship rel, links)
    {
        ids << QString::number(rel.first().localId());
        ids << QString::number(rel.second().localId());
    }

    RDFVariable contact;
    QStringList idstrings(QStringList(ids.toList()));
    contact.property<nco::contactUID>().isMemberOf(idstrings);
    m_nodes = ::tracker()->modelVariable(contact);

    // need to store LiveNodes in order to receive notification from model
    QObject::connect(m_nodes.model(), SIGNAL(modelUpdated()), this, SLOT(nodesDataReady()));

}

void QTrackerRelationshipSaveRequest::nodesDataReady()
{
    // now that nodes are ready we can enumerate them without blocking
    RDFTransactionPtr transaction_ = ::tracker()->initiateTransaction();
    connect(transaction_.data(), SIGNAL(commitFinished()), this, SLOT(commitFinished()));
    connect(transaction_.data(), SIGNAL(commitError(QString)), this, SLOT(commitError(QString)));

    QHash<QString, Live<nco::PersonContact> > lContacts;
    for(int i = 0; i < m_nodes->rowCount(); i++)
    {
        Live<nco::PersonContact> contact = m_nodes->liveNode(i);
        lContacts[contact->getContactUID()] = contact;
    }
    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (!r)
        commitError(QString());
    QList<QContactRelationship> links = r->relationships();
    foreach(QContactRelationship rel, links)
    {
        Live<nco::PersonContact> first = lContacts.value(QString::number(rel.first().localId()));
        Live<nco::PersonContact> second = lContacts.value(QString::number(rel.second().localId()));
        //TODO: we should prefer the local contact information over the remote info.
        mergeContacts(first, second);
    }

    transaction_->commit(false);
    // temporary fix - signals not yet implemented in libqttracker
    commitFinished();
}

void QTrackerRelationshipSaveRequest::mergeContacts(const Live<nco::PersonContact>& preferedContact, const Live<nco::PersonContact>& inferiorContact)
{
   QList<LiveNode> mergedNodes = preferedContact->getHasIMAddresss();
   mergedNodes += inferiorContact->getHasIMAddresss();
   preferedContact->setHasIMAddresss( mergedNodes );
   inferiorContact->remove();
}

void QTrackerRelationshipSaveRequest::commitFinished()
{
    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (r && r->isActive())
    {
        QContactManager::Error error = QContactManager::NoError;
        QMap<int, QContactManager::Error> errors;
        errors[0] = error;
        QContactManagerEngine::updateRelationshipSaveRequest(r, r->relationships(), error, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
    }
    else
        qWarning()<<Q_FUNC_INFO<<r;
}

void QTrackerRelationshipSaveRequest::commitError(QString message)
{
    qWarning()<<Q_FUNC_INFO<<message;
    QContactRelationshipSaveRequest* r = qobject_cast<QContactRelationshipSaveRequest*>(req);
    if (r)
    {
        QContactManager::Error error = QContactManager::InvalidRelationshipError;
        QMap<int, QContactManager::Error> errors;
        errors[0] = error;
        QContactManagerEngine::updateRelationshipSaveRequest(r, r->relationships(), error, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
    }
    else
    {
        QMap<int, QContactManager::Error> errors;
        errors[0] = QContactManager::UnspecifiedError;
        QContactManagerEngine::updateRelationshipSaveRequest(r, QList<QContactRelationship>(), QContactManager::UnspecifiedError, errors);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
        return;
    }
}

<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>

// Includes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"

static constexpr auto FPS = 30;

int main() {
    dai::Pipeline pipeline;

    // Define a source - color camera
    auto camRgb = pipeline.create<dai::node::ColorCamera>();
    // Since we are saving RGB frames in Script node we need to make the
    // video pool size larger, otherwise the pipeline will freeze because
    // the ColorCamera won't be able to produce new video frames.
    camRgb->setVideoNumFramesPool(10);
    camRgb->setFps(FPS);

    auto left = pipeline.create<dai::node::MonoCamera>();
    left->setResolution(dai::MonoCameraProperties::SensorResolution::THE_400_P);
    left->setBoardSocket(dai::CameraBoardSocket::LEFT);
    left->setFps(FPS);

    auto right = pipeline.create<dai::node::MonoCamera>();
    right->setResolution(dai::MonoCameraProperties::SensorResolution::THE_400_P);
    right->setBoardSocket(dai::CameraBoardSocket::RIGHT);
    right->setFps(FPS);

    auto stereo = pipeline.create<dai::node::StereoDepth>();
    stereo->initialConfig.setMedianFilter(dai::MedianFilter::KERNEL_7x7);
    stereo->setLeftRightCheck(true);
    stereo->setExtendedDisparity(false);
    stereo->setSubpixel(false);
    stereo->setDepthAlign(dai::CameraBoardSocket::RGB);
    left->out.link(stereo->left);
    right->out.link(stereo->right);

    // Script node will sync high-res frames
    auto script = pipeline.create<dai::node::Script>();

    // Send both streams to the Script node so we can sync them
    stereo->disparity.link(script->inputs["disp_in"]);
    camRgb->video.link(script->inputs["rgb_in"]);

    script->setScript(R"(
        FPS=30
        import time
        from datetime import timedelta
        import math

        # Timestamp threshold (in miliseconds) under which frames will be considered synced.
        # Lower number means frames will have less delay between them, which can potentially
        # lead to dropped frames.
        MS_THRESHOL=math.ceil(500 / FPS)

        def check_sync(queues, timestamp):
            matching_frames = []
            for name, list in queues.items(): # Go through each available stream
                # node.warn(f"List {name}, len {str(len(list))}")
                for i, msg in enumerate(list): # Go through each frame of this stream
                    time_diff = abs(msg.getTimestamp() - timestamp)
                    if time_diff <= timedelta(milliseconds=MS_THRESHOL): # If time diff is below threshold, this frame is considered in-sync
                        matching_frames.append(i) # Append the position of the synced frame, so we can later remove all older frames
                        break

            if len(matching_frames) == len(queues):
                # We have all frames synced. Remove the excess ones
                i = 0
                for name, list in queues.items():
                    queues[name] = queues[name][matching_frames[i]:] # Remove older (excess) frames
                    i+=1
                return True
            else:
                return False # We don't have synced frames yet

        names = ['disp', 'rgb']
        frames = dict() # Dict where we store all received frames
        for name in names:
            frames[name] = []

        while True:
            for name in names:
                f = node.io[name+"_in"].tryGet()
                if f is not None:
                    frames[name].append(f) # Save received frame

                    if check_sync(frames, f.getTimestamp()): # Check if we have any synced frames
                        # Frames synced!
                        node.info(f"Synced frame!")
                        for name, list in frames.items():
                            syncedF = list.pop(0) # We have removed older (excess) frames, so at positions 0 in dict we have synced frames
                            node.info(f"{name}, ts: {str(syncedF.getTimestamp())}, seq {str(syncedF.getSequenceNum())}")
                            node.io[name+'_out'].send(syncedF) # Send synced frames to the host

            time.sleep(0.001)  # Avoid lazy looping
        )");

    std::vector<std::string> scriptOut{"disp", "rgb"};
    // Create XLinkOut for disp/rgb streams
    for(auto& name : scriptOut) {
        auto xout = pipeline.create<dai::node::XLinkOut>();
        xout->setStreamName(name);
        script->outputs[name + "_out"].link(xout->input);
    }

    dai::Device device(pipeline);

    device.setLogOutputLevel(dai::LogLevel::INFO);

    std::vector<std::string> names{"rgb", "disp"};
    std::map<std::string, std::shared_ptr<dai::DataOutputQueue>> streams;
    for(auto& name : names) {
        streams[name] = device.getOutputQueue(name);
    }
    while(true) {
        for(auto& iter : streams) {
            auto name = iter.first;
            auto queue = iter.second;
            auto img = queue->get<dai::ImgFrame>();
            // Display timestamp/sequence number of two synced frames
            std::cout << "Stream " << name << ", timestamp: " << img->getTimestamp().time_since_epoch().count()
                      << ", sequence number: " << img->getSequenceNum() << std::endl;
        }
    }
}
<commit_msg>Both log levels need to be set<commit_after>#include <chrono>
#include <iostream>

// Includes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"

static constexpr auto FPS = 30;

int main() {
    dai::Pipeline pipeline;

    // Define a source - color camera
    auto camRgb = pipeline.create<dai::node::ColorCamera>();
    // Since we are saving RGB frames in Script node we need to make the
    // video pool size larger, otherwise the pipeline will freeze because
    // the ColorCamera won't be able to produce new video frames.
    camRgb->setVideoNumFramesPool(10);
    camRgb->setFps(FPS);

    auto left = pipeline.create<dai::node::MonoCamera>();
    left->setResolution(dai::MonoCameraProperties::SensorResolution::THE_400_P);
    left->setBoardSocket(dai::CameraBoardSocket::LEFT);
    left->setFps(FPS);

    auto right = pipeline.create<dai::node::MonoCamera>();
    right->setResolution(dai::MonoCameraProperties::SensorResolution::THE_400_P);
    right->setBoardSocket(dai::CameraBoardSocket::RIGHT);
    right->setFps(FPS);

    auto stereo = pipeline.create<dai::node::StereoDepth>();
    stereo->initialConfig.setMedianFilter(dai::MedianFilter::KERNEL_7x7);
    stereo->setLeftRightCheck(true);
    stereo->setExtendedDisparity(false);
    stereo->setSubpixel(false);
    stereo->setDepthAlign(dai::CameraBoardSocket::RGB);
    left->out.link(stereo->left);
    right->out.link(stereo->right);

    // Script node will sync high-res frames
    auto script = pipeline.create<dai::node::Script>();

    // Send both streams to the Script node so we can sync them
    stereo->disparity.link(script->inputs["disp_in"]);
    camRgb->video.link(script->inputs["rgb_in"]);

    script->setScript(R"(
        FPS=30
        import time
        from datetime import timedelta
        import math

        # Timestamp threshold (in miliseconds) under which frames will be considered synced.
        # Lower number means frames will have less delay between them, which can potentially
        # lead to dropped frames.
        MS_THRESHOL=math.ceil(500 / FPS)

        def check_sync(queues, timestamp):
            matching_frames = []
            for name, list in queues.items(): # Go through each available stream
                # node.warn(f"List {name}, len {str(len(list))}")
                for i, msg in enumerate(list): # Go through each frame of this stream
                    time_diff = abs(msg.getTimestamp() - timestamp)
                    if time_diff <= timedelta(milliseconds=MS_THRESHOL): # If time diff is below threshold, this frame is considered in-sync
                        matching_frames.append(i) # Append the position of the synced frame, so we can later remove all older frames
                        break

            if len(matching_frames) == len(queues):
                # We have all frames synced. Remove the excess ones
                i = 0
                for name, list in queues.items():
                    queues[name] = queues[name][matching_frames[i]:] # Remove older (excess) frames
                    i+=1
                return True
            else:
                return False # We don't have synced frames yet

        names = ['disp', 'rgb']
        frames = dict() # Dict where we store all received frames
        for name in names:
            frames[name] = []

        while True:
            for name in names:
                f = node.io[name+"_in"].tryGet()
                if f is not None:
                    frames[name].append(f) # Save received frame

                    if check_sync(frames, f.getTimestamp()): # Check if we have any synced frames
                        # Frames synced!
                        node.info(f"Synced frame!")
                        for name, list in frames.items():
                            syncedF = list.pop(0) # We have removed older (excess) frames, so at positions 0 in dict we have synced frames
                            node.info(f"{name}, ts: {str(syncedF.getTimestamp())}, seq {str(syncedF.getSequenceNum())}")
                            node.io[name+'_out'].send(syncedF) # Send synced frames to the host

            time.sleep(0.001)  # Avoid lazy looping
        )");

    std::vector<std::string> scriptOut{"disp", "rgb"};
    // Create XLinkOut for disp/rgb streams
    for(auto& name : scriptOut) {
        auto xout = pipeline.create<dai::node::XLinkOut>();
        xout->setStreamName(name);
        script->outputs[name + "_out"].link(xout->input);
    }

    dai::Device device(pipeline);

    device.setLogOutputLevel(dai::LogLevel::INFO);
    device.setLogLevel(dai::LogLevel::INFO);
    std::vector<std::string> names{"rgb", "disp"};
    std::map<std::string, std::shared_ptr<dai::DataOutputQueue>> streams;
    for(auto& name : names) {
        streams[name] = device.getOutputQueue(name);
    }
    while(true) {
        for(auto& iter : streams) {
            auto name = iter.first;
            auto queue = iter.second;
            auto img = queue->get<dai::ImgFrame>();
            // Display timestamp/sequence number of two synced frames
            std::cout << "Stream " << name << ", timestamp: " << img->getTimestamp().time_since_epoch().count()
                      << ", sequence number: " << img->getSequenceNum() << std::endl;
        }
    }
}
<|endoftext|>


<commit_before>/***********************************************************************
 store_if.cpp - Demonstrates Query::store_if(), showing only the rows
	from the sample table with prime quantities.  This isn't intended
	to be useful, only to show how you can do result set filtering that
	outstrips the power of SQL.

 Copyright (c) 2005-2007 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

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

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

 You should have received a copy of the GNU Lesser General Public
 License along with MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "util.h"
#include "stock.h"

#include <mysql++.h>

#include <iostream>

// Define a functor for testing primality.
struct is_prime
{
	bool operator()(const stock& s)
	{
		if ((s.num == 2) || (s.num == 3)) {
			return true;	// 2 and 3 are trivial cases
		}
		else if ((s.num < 2) || ((s.num % 2) == 0)) {
			return false;	// can't be prime if < 2 or even
		}
		else {
			// The only possibility left is that it's divisible by an
			// odd number that's less or equal to its square root.
			for (int i = 3; i <= sqrt(s.num); i += 2) {
				if ((s.num % i) == 0) {
					return false;
				}
			}
			return true;
		}
	}
};

int
main(int argc, char *argv[])
{
	try {
		// Connect to the sample database
		mysqlpp::Connection con;
		if (!connect_to_db(argc, argv, con)) {
			return 1;
		}

		// Pull only the stock items with prime quantities
		std::vector<stock> results;
		mysqlpp::Query query = con.query();
		query.store_if(results, "select * from stock", is_prime());

		// Show the results
		print_stock_header(results.size());
		std::vector<stock>::const_iterator it;
		for (it = results.begin(); it != results.end(); ++it) {
			print_stock_row(it->item.c_str(), it->num, it->weight,
					it->price, it->sdate);
		}
	}
	catch (const mysqlpp::BadQuery& e) {
		// Something went wrong with the SQL query.
		std::cerr << "Query failed: " << e.what() << std::endl;
		return 1;
	}
	catch (const mysqlpp::Exception& er) {
		// Catch-all for any other MySQL++ exceptions
		std::cerr << "Error: " << er.what() << std::endl;
		return 1;
	}

	return 0;
}
<commit_msg>Small build fixes for VC++<commit_after>/***********************************************************************
 store_if.cpp - Demonstrates Query::store_if(), showing only the rows
	from the sample table with prime quantities.  This isn't intended
	to be useful, only to show how you can do result set filtering that
	outstrips the power of SQL.

 Copyright (c) 2005-2007 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

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

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

 You should have received a copy of the GNU Lesser General Public
 License along with MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "util.h"
#include "stock.h"

#include <mysql++.h>

#include <iostream>

#include <math.h>

// Define a functor for testing primality.
struct is_prime
{
	bool operator()(const stock& s)
	{
		if ((s.num == 2) || (s.num == 3)) {
			return true;	// 2 and 3 are trivial cases
		}
		else if ((s.num < 2) || ((s.num % 2) == 0)) {
			return false;	// can't be prime if < 2 or even
		}
		else {
			// The only possibility left is that it's divisible by an
			// odd number that's less or equal to its square root.
			for (int i = 3; i <= sqrt(double(s.num)); i += 2) {
				if ((s.num % i) == 0) {
					return false;
				}
			}
			return true;
		}
	}
};

int
main(int argc, char *argv[])
{
	try {
		// Connect to the sample database
		mysqlpp::Connection con;
		if (!connect_to_db(argc, argv, con)) {
			return 1;
		}

		// Pull only the stock items with prime quantities
		std::vector<stock> results;
		mysqlpp::Query query = con.query();
		query.store_if(results, "select * from stock", is_prime());

		// Show the results
		print_stock_header(results.size());
		std::vector<stock>::const_iterator it;
		for (it = results.begin(); it != results.end(); ++it) {
			print_stock_row(it->item.c_str(), it->num, it->weight,
					it->price, it->sdate);
		}
	}
	catch (const mysqlpp::BadQuery& e) {
		// Something went wrong with the SQL query.
		std::cerr << "Query failed: " << e.what() << std::endl;
		return 1;
	}
	catch (const mysqlpp::Exception& er) {
		// Catch-all for any other MySQL++ exceptions
		std::cerr << "Error: " << er.what() << std::endl;
		return 1;
	}

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Significantly increase timeouts to reduce flakiness<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <amgcl/backend/viennacl.hpp>
#include <amgcl/runtime.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/profiler.hpp>

#include "sample_problem.hpp"

namespace amgcl {
    profiler<> prof;
}

int main(int argc, char *argv[]) {
    using amgcl::prof;

    // Read configuration from command line
    int m = 32;
    amgcl::runtime::coarsening::type coarsening = amgcl::runtime::coarsening::smoothed_aggregation;
    amgcl::runtime::relaxation::type relaxation = amgcl::runtime::relaxation::spai0;
    amgcl::runtime::solver::type     solver     = amgcl::runtime::solver::bicgstab;
    std::string parameter_file;
#ifdef VIENNACL_WITH_OPENCL
    int pid = 0;
#endif

    namespace po = boost::program_options;
    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "show help")
#ifdef VIENNACL_WITH_OPENCL
        (
         "platform",
         po::value<int>(&pid)->default_value(pid),
         "Index of OpenCL platform to use"
        )
#endif
        (
         "size,n",
         po::value<int>(&m)->default_value(m),
         "domain size"
        )
        (
         "coarsening,c",
         po::value<amgcl::runtime::coarsening::type>(&coarsening)->default_value(coarsening),
         "ruge_stuben, aggregation, smoothed_aggregation, smoothed_aggr_emin"
        )
        (
         "relaxation,r",
         po::value<amgcl::runtime::relaxation::type>(&relaxation)->default_value(relaxation),
         "gauss_seidel, multicolor_gauss_seidel, ilu0, damped_jacobi, spai0, chebyshev"
        )
        (
         "solver,s",
         po::value<amgcl::runtime::solver::type>(&solver)->default_value(solver),
         "cg, bicgstab, bicgstabl, gmres"
        )
        (
         "params,p",
         po::value<std::string>(&parameter_file),
         "parameter file in json format"
        )
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    boost::property_tree::ptree prm;
    if (vm.count("params")) read_json(parameter_file, prm);

    prm.put("precond.coarsening.type", coarsening);
    prm.put("precond.relaxation.type", relaxation);
    prm.put("solver.type",             solver);

#ifdef VIENNACL_WITH_OPENCL
    viennacl::ocl::set_context_platform_index(0, pid);
    std::cout << "Device: " << viennacl::ocl::current_context().current_device().name() << std::endl;
#endif

    // Assemble problem
    prof.tic("assemble");
    std::vector<int>    ptr;
    std::vector<int>    col;
    std::vector<double> val;
    std::vector<double> rhs;

    int n = sample_problem(m, val, col, ptr, rhs);
    prof.toc("assemble");

    typedef
        amgcl::runtime::make_solver<
            amgcl::backend::viennacl<
                viennacl::compressed_matrix<double>
                >
            >
        Solver;

    // Setup solver
    prof.tic("setup");
    Solver solve( boost::tie(n, ptr, col, val), prm );
    prof.toc("setup");

    std::cout << solve.precond() << std::endl;

    // Solve the problem
    viennacl::vector<double> f(n);
    viennacl::vector<double> x(n);

    viennacl::fast_copy(rhs, f);
    x.clear();

    size_t iters;
    double resid;
    prof.tic("solve");
    boost::tie(iters, resid) = solve(f, x);
    prof.toc("solve");

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << resid << std::endl
              << std::endl      << prof  << std::endl;
}
<commit_msg>Update viennacl example<commit_after>#include <iostream>
#include <string>

#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <amgcl/backend/viennacl.hpp>
#include <amgcl/runtime.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/profiler.hpp>

#include "sample_problem.hpp"

namespace amgcl {
    profiler<> prof;
}

int main(int argc, char *argv[]) {
    using amgcl::prof;

    // Read configuration from command line
    int m = 32;
    amgcl::runtime::coarsening::type coarsening = amgcl::runtime::coarsening::smoothed_aggregation;
    amgcl::runtime::relaxation::type relaxation = amgcl::runtime::relaxation::spai0;
    amgcl::runtime::solver::type     solver     = amgcl::runtime::solver::bicgstab;
    std::string parameter_file;
#ifdef VIENNACL_WITH_OPENCL
    int pid = 0;
#endif

    namespace po = boost::program_options;
    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "show help")
#ifdef VIENNACL_WITH_OPENCL
        (
         "platform",
         po::value<int>(&pid)->default_value(pid),
         "Index of OpenCL platform to use"
        )
#endif
        (
         "size,n",
         po::value<int>(&m)->default_value(m),
         "domain size"
        )
        (
         "coarsening,c",
         po::value<amgcl::runtime::coarsening::type>(&coarsening)->default_value(coarsening),
         "ruge_stuben, aggregation, smoothed_aggregation, smoothed_aggr_emin"
        )
        (
         "relaxation,r",
         po::value<amgcl::runtime::relaxation::type>(&relaxation)->default_value(relaxation),
         "gauss_seidel, multicolor_gauss_seidel, ilu0, damped_jacobi, spai0, chebyshev"
        )
        (
         "solver,s",
         po::value<amgcl::runtime::solver::type>(&solver)->default_value(solver),
         "cg, bicgstab, bicgstabl, gmres"
        )
        (
         "params,p",
         po::value<std::string>(&parameter_file),
         "parameter file in json format"
        )
        ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    boost::property_tree::ptree prm;
    if (vm.count("params")) read_json(parameter_file, prm);

    prm.put("precond.coarsening.type", coarsening);
    prm.put("precond.relaxation.type", relaxation);
    prm.put("solver.type",             solver);

#ifdef VIENNACL_WITH_OPENCL
    viennacl::ocl::set_context_platform_index(0, pid);
    std::cout << "Device: " << viennacl::ocl::current_context().current_device().name() << std::endl;
#endif

    // Assemble problem
    prof.tic("assemble");
    std::vector<int>    ptr;
    std::vector<int>    col;
    std::vector<double> val;
    std::vector<double> rhs;

    int n = sample_problem(m, val, col, ptr, rhs);
    prof.toc("assemble");

    typedef
        amgcl::backend::viennacl< viennacl::compressed_matrix<double> >
        Backend;

    typedef
        amgcl::make_solver<
            amgcl::runtime::amg<Backend>,
            amgcl::runtime::iterative_solver<Backend>
            >
        Solver;

    // Setup solver
    prof.tic("setup");
    Solver solve( boost::tie(n, ptr, col, val), prm );
    prof.toc("setup");

    std::cout << solve.precond() << std::endl;

    // Solve the problem
    viennacl::vector<double> f(n);
    viennacl::vector<double> x(n);

    viennacl::fast_copy(rhs, f);
    x.clear();

    size_t iters;
    double resid;
    prof.tic("solve");
    boost::tie(iters, resid) = solve(f, x);
    prof.toc("solve");

    std::cout << "Iterations: " << iters << std::endl
              << "Error:      " << resid << std::endl
              << std::endl      << prof  << std::endl;
}
<|endoftext|>


<commit_before><commit_msg>Early-out when the PrivateWorkingSetSnapshot is being flaky<commit_after><|endoftext|>


<commit_before><commit_msg>If you click a link to a malware page or if a page redirects to malware, the malware blocking page is shown but it says that the malware page is a resource of the originating page. This is because the blocking page was using the page URL to determine if we are dealing with the main frame, and in these cases the URL was not set yet.<commit_after><|endoftext|>


<commit_before><commit_msg>Avoid closing the reauth dialog twice.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix DIR_SOURCE_ROOT for WebKit checkouts on linux<commit_after><|endoftext|>


<commit_before><commit_msg>Make base::GetProcId() thread-safe on windows and drop w2k support<commit_after><|endoftext|>


<commit_before>#pragma once

#include <cassert>
#include <cstdint>
#include <functional>
#include <sstream>
#include <vector>

#include "callbackQueue.hpp"
#include "state.hpp"
#include "staticData.hpp"

class Solver
{
private:
    using u8 = std::uint8_t;
    using u16 = std::uint16_t;
    using u64 = std::uint64_t;

    State mState;
    std::vector<State>* mCurrSolutions = nullptr;
    CallbackQueue mDirtyCells;
    bool mContradiction = false;

    void ProcessCell(u8 cellNo)
    {
        u16 cell = mState.GetCell(cellNo);

        for (u8 neighbourNo : GetCellNeighbours(cellNo))
        {
            u16 neighbour = mState.GetCell(neighbourNo);

            if ((neighbour & cell) != 0u)
            {
                neighbour &= ~cell;
                if ((neighbour & (neighbour - u16(1))) == 0u) // TODO: try getting rid of all instances of u8(1) etc.
                {
                    if (neighbour == 0u)
                    {
                        mContradiction = true;
                        return;
                    }

                    mDirtyCells.Push(neighbourNo);
                }
            }

            mState.SetCell(neighbourNo, neighbour);
        }
    }

    static bool CellIsPair(u16 cell) // cell != 0 is assumed
    {
        cell &= (cell - u16(1));

        if (cell == 0)
            return false;

        cell &= (cell - u16(1));

        return (cell == 0);
    }

    void LockedPairsInGroup(const std::array<u8, 9>& group)
    {
        u16 lockedPair = 511;

        u8 i = 0u;
        for (; i != 9u; ++i)
        {
            u16 cell = mState.GetCell(group[i]);

            if (CellIsPair(cell))
            {
                lockedPair = cell;
                break;
            }
        }

        if (lockedPair == 511)
            return;

        u8 count = 0u;
        for (++i; i != 9u; ++i)
        {
            u16 cell = mState.GetCell(group[i]);
            count += (cell == lockedPair);
        }

        if (count != 1)
        {
            mContradiction |= (count > 1);
            return;
        }

        for (auto cellNo : group)
        {
            u16 cell = mState.GetCell(cellNo);

            if ((cell & lockedPair) != 0u)
            {
                if (cell == lockedPair)
                    continue; // TODO: duplicating counter here?

                cell &= ~lockedPair;
                if ((cell & (cell - u16(1))) == 0u)
                {
                    if (cell == 0u)
                    {
                        mContradiction = true;
                        return;
                    }

                    mDirtyCells.Push(cellNo); // TODO: try going back to normal strategy at first occurrence here
                }
            }

            mState.SetCell(cellNo, cell);
        }
    }

    void LockedPairs()
    {
        for (auto& group : GetGroups())
        {
            LockedPairsInGroup(group);
        }
    }

    std::string GetDirtyCellsInBinary() const
    {
        std::string result(81, '0');
        auto dirtyCells = mDirtyCells;

        while (true)
        {
            u8 cellNo = dirtyCells.Pop();

            if (cellNo == u8(255))
                break;

            result[cellNo] = '1';
        }

        return result;
    }

    void ProcessCurrState()
    {
        while (!mDirtyCells.Empty())
        {
            while (!mDirtyCells.Empty())
            {
                u8 cellNo = mDirtyCells.Pop();
                ProcessCell(cellNo);

                if (mContradiction)
                {
                    return;
                }
            }

            LockedPairs();
        }
    }

    void MarkFinalCellsDirty()
    {
        for (u8 cellNo = 0u; cellNo != 81u; ++cellNo)
        {
            u16 cell = mState.GetCell(cellNo);
            if ((cell & (cell - u16(1))) == 0u)
            {
                mDirtyCells.Push(cellNo);
            }
        }
    }

    void Guess(u8 cellNo, u16 cell)
    {
        mState.SetCell(cellNo, cell);
        mDirtyCells.Push(cellNo);
    }

    void SolveImpl()
    {
        ProcessCurrState();
        ProcessingExhausted();
    }

    void ProcessingExhausted()
    {
        if (mContradiction)
        {
            mContradiction = false;
            return;
        }

        u8 guessCellNo = mState.PickNonFinalisedCell();

        if (guessCellNo == u8(255))
        {
            mCurrSolutions->push_back(mState);
            return;
        }

        u16 cell = mState.GetCell(guessCellNo);
        u16 newCell = u16(1) << u16(8);

        State backupState = mState;

        while (newCell > u16(0))
        {
            if ((newCell & cell) != u16(0))
            {
                Guess(guessCellNo, newCell);
                SolveImpl();
                mState = backupState;
                mDirtyCells.Clear();
            }

            newCell >>= u16(1);
        }
    }

public:
    State ShallowSolve(const State& state)
    {
        mState = state;

        MarkFinalCellsDirty();
        ProcessCurrState();

        return mState;
    }

    std::vector<State> Solve(const State& state)
    {
        std::vector<State> solutions;
        mCurrSolutions = &solutions;

        mState = state;

        MarkFinalCellsDirty();
        SolveImpl();

        mCurrSolutions = nullptr;

        return solutions;
    }
};
<commit_msg>Increased work in LockedPairs but +1% performance assumedly due to vectorization.<commit_after>#pragma once

#include <cassert>
#include <cstdint>
#include <functional>
#include <sstream>
#include <vector>

#include "callbackQueue.hpp"
#include "state.hpp"
#include "staticData.hpp"

class Solver
{
private:
    using u8 = std::uint8_t;
    using u16 = std::uint16_t;
    using u64 = std::uint64_t;

    State mState;
    std::vector<State>* mCurrSolutions = nullptr;
    CallbackQueue mDirtyCells;
    bool mContradiction = false;

    void ProcessCell(u8 cellNo)
    {
        u16 cell = mState.GetCell(cellNo);

        for (u8 neighbourNo : GetCellNeighbours(cellNo))
        {
            u16 neighbour = mState.GetCell(neighbourNo);

            if ((neighbour & cell) != 0u)
            {
                neighbour &= ~cell;
                if ((neighbour & (neighbour - u16(1))) == 0u) // TODO: try getting rid of all instances of u8(1) etc.
                {
                    if (neighbour == 0u)
                    {
                        mContradiction = true;
                        return;
                    }

                    mDirtyCells.Push(neighbourNo);
                }
            }

            mState.SetCell(neighbourNo, neighbour);
        }
    }

    static bool CellIsPair(u16 cell) // cell != 0 is assumed
    {
        cell &= (cell - u16(1));

        if (cell == 0)
            return false;

        cell &= (cell - u16(1));

        return (cell == 0);
    }

    void LockedPairsInGroup(const std::array<u8, 9>& group)
    {
        u16 lockedPair = 511;

        for (u8 i = 0u; i != 9u; ++i)
        {
            u16 cell = mState.GetCell(group[i]);

            if (CellIsPair(cell))
            {
                lockedPair = cell;
                break;
            }
        }

        if (lockedPair == 511)
            return;

        u8 count = 0u;
        for (u8 i = 0u; i != 9u; ++i)
        {
            u16 cell = mState.GetCell(group[i]);
            count += (cell == lockedPair);
        }

        if (count != 2)
        {
            mContradiction |= (count > 2);
            return;
        }

        for (auto cellNo : group)
        {
            u16 cell = mState.GetCell(cellNo);

            if ((cell & lockedPair) != 0u)
            {
                if (cell == lockedPair)
                    continue; // TODO: duplicating counter here?

                cell &= ~lockedPair;
                if ((cell & (cell - u16(1))) == 0u)
                {
                    if (cell == 0u)
                    {
                        mContradiction = true;
                        return;
                    }

                    mDirtyCells.Push(cellNo); // TODO: try going back to normal strategy at first occurrence here
                }
            }

            mState.SetCell(cellNo, cell);
        }
    }

    void LockedPairs()
    {
        for (auto& group : GetGroups())
        {
            LockedPairsInGroup(group);
        }
    }

    std::string GetDirtyCellsInBinary() const
    {
        std::string result(81, '0');
        auto dirtyCells = mDirtyCells;

        while (true)
        {
            u8 cellNo = dirtyCells.Pop();

            if (cellNo == u8(255))
                break;

            result[cellNo] = '1';
        }

        return result;
    }

    void ProcessCurrState()
    {
        while (!mDirtyCells.Empty())
        {
            while (!mDirtyCells.Empty())
            {
                u8 cellNo = mDirtyCells.Pop();
                ProcessCell(cellNo);

                if (mContradiction)
                {
                    return;
                }
            }

            LockedPairs();
        }
    }

    void MarkFinalCellsDirty()
    {
        for (u8 cellNo = 0u; cellNo != 81u; ++cellNo)
        {
            u16 cell = mState.GetCell(cellNo);
            if ((cell & (cell - u16(1))) == 0u)
            {
                mDirtyCells.Push(cellNo);
            }
        }
    }

    void Guess(u8 cellNo, u16 cell)
    {
        mState.SetCell(cellNo, cell);
        mDirtyCells.Push(cellNo);
    }

    void SolveImpl()
    {
        ProcessCurrState();
        ProcessingExhausted();
    }

    void ProcessingExhausted()
    {
        if (mContradiction)
        {
            mContradiction = false;
            return;
        }

        u8 guessCellNo = mState.PickNonFinalisedCell();

        if (guessCellNo == u8(255))
        {
            mCurrSolutions->push_back(mState);
            return;
        }

        u16 cell = mState.GetCell(guessCellNo);
        u16 newCell = u16(1) << u16(8);

        State backupState = mState;

        while (newCell > u16(0))
        {
            if ((newCell & cell) != u16(0))
            {
                Guess(guessCellNo, newCell);
                SolveImpl();
                mState = backupState;
                mDirtyCells.Clear();
            }

            newCell >>= u16(1);
        }
    }

public:
    State ShallowSolve(const State& state)
    {
        mState = state;

        MarkFinalCellsDirty();
        ProcessCurrState();

        return mState;
    }

    std::vector<State> Solve(const State& state)
    {
        std::vector<State> solutions;
        mCurrSolutions = &solutions;

        mState = state;

        MarkFinalCellsDirty();
        SolveImpl();

        mCurrSolutions = nullptr;

        return solutions;
    }
};
<|endoftext|>