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

/**
 * DARC InboundLink class
 *
 * \author Morten Kjaergaard
 */

#pragma once

#include <boost/shared_ptr.hpp>
#include <darc/peer/peer.hpp>
#include <darc/buffer/shared_buffer.hpp>
#include <darc/network/link_header_packet.hpp>
#include <darc/network/discover_packet.hpp>
#include <darc/network/discover_reply_packet.hpp>
#include <darc/network/outbound_data.hpp>
#include <darc/network/inbound_data.hpp>
#include <darc/serializer/boost.hpp>
#include <darc/buffer/const_size_buffer.hpp>
#include <darc/id_arg.hpp>
#include <iris/static_scope.hpp>

namespace darc
{
namespace network
{

class network_manager;

class inbound_link_base : public virtual iris::static_scope<iris::Info>
{
protected:
  peer& peer_;
  class network_manager * manager_;

protected:
  inbound_link_base(class network_manager * manager, peer& p) :
    manager_(manager),
    peer_(p)
  {
  }

  virtual ~inbound_link_base()
  {
  }

public:
  virtual void send_packet(const ID& outbound_id,
                          const ID& dest_peer_id,
                          const uint16_t packet_type,
                          buffer::shared_buffer data) = 0;

  virtual void send_packet_to_all(const ID& dest_peer_id,
                                  const uint16_t packet_type,
                                  buffer::shared_buffer data) = 0;

  class network_manager* network_manager()
  {
    return manager_;
  }

  void packet_received(buffer::shared_buffer header_data,
                       buffer::shared_buffer body_data);

  void handle_discover_packet(const ID& src_peer_id, buffer::shared_buffer& data)
  {
    inbound_data<darc::serializer::boost_serializer, discover_packet> dp_i(data);

    slog<iris::Debug>("Received DISCOVER",
                      "peer_id", iris::arg<ID>(src_peer_id),
                      "remote outbound_id", iris::arg<ID>(dp_i.get().outbound_id));

    discover_reply_packet drp;
    drp.outbound_id = dp_i.get().outbound_id;
    outbound_data<darc::serializer::boost_serializer, discover_reply_packet> o_drp(drp);

    buffer::shared_buffer buffer = boost::make_shared<buffer::const_size_buffer>(1024); // todo

    o_drp.pack(buffer);

    send_packet_to_all(src_peer_id, link_header_packet::DISCOVER_REPLY, buffer);
  }

  void handle_discover_reply_packet(const ID& src_peer_id, buffer::shared_buffer& data);

  void sendDiscover(const ID& outbound_id)
  {
    slog<iris::Debug>("Sending DISCOVER",
                      "Outbound ID", iris::arg<ID>(outbound_id));

    discover_packet dp;
    dp.outbound_id = outbound_id;
    outbound_data<darc::serializer::boost_serializer, discover_packet> o_dp(dp);

    buffer::shared_buffer buffer = boost::make_shared<buffer::const_size_buffer>(1024); // todo

    o_dp.pack(buffer);

    send_packet(outbound_id, ID::null(), link_header_packet::DISCOVER, buffer);
  }

/*
  void sendDiscoverReply(const ID& remote_outbound_id, const ID& remote_node_id)
  {
  // Create packet
  std::size_t data_len = 1024*32;
  SharedBuffer buffer = SharedBufferArray::create(data_len);
  network::packet::DiscoverReply discover_reply(remote_outbound_id);
  std::size_t len = discover_reply.write( buffer.data(), buffer.size() );

  // Send packet
  sendPacketToAll(network::packet::Header::DISCOVER_REPLY_PACKET, remote_node_id, buffer, len );
  }
*/
};

typedef boost::shared_ptr<inbound_link_base> inbound_link_ptr;

}
}

max_stars_repo_name: mkjaergaard/darc

max_issues_repo_name: mkjaergaard/darc

max_forks_repo_name: mkjaergaard/darc


text:
#include <boost/mpl/assert.hpp>
#include <nt2/sdk/meta/as_signed.hpp>
#include <nt2/sdk/simd/pack.hpp>
#include <boost/type_traits/is_same.hpp>

using boost::is_same;
using nt2::meta::as_signed;

using nt2::simd::pack;

int main()
{
  BOOST_MPL_ASSERT(( is_same<int,        as_signed<unsigned int>::type>         ));
  BOOST_MPL_ASSERT(( is_same<int,        as_signed<int>::type>                  ));
  BOOST_MPL_ASSERT(( is_same<float,      as_signed<float>::type>                ));
  BOOST_MPL_ASSERT(( is_same< pack<int>, as_signed< pack<unsigned int> >::type> ));
}

ext: cpp


text: #include <boost/metaparse/except.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/graph/cycle_canceling.hpp>


text:
// Copyright 2014 Jonathan Graehl - http://graehl.org/
//
// 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.
// determine whether a class has specified a print or print with writer method
#ifndef PRINT_ON_HPP
#define PRINT_ON_HPP

#include <boost/utility/enable_if.hpp>
#include <boost/ref.hpp>
//namespace boost { template <class C> class reference_wrapper; }

// usage: template <class A> void func(A &a,typename has_print_plain<A>::type* dummy = 0)

// how this works: has_print<C>::type is either defined (iff C::has_print was typedefed to void), or undefined.  this allows us to exploit SFINAE (google) for function overloads depending on whether C::has_print was typedefed void ;)

// ok - actually, as long as C::has_print is *any* type ...

namespace graehl {

template <class C, class V = void>
struct has_print;

template <class C, class V>
struct has_print {
};

template <class C>
struct has_print<C, typename C::has_print> {
  typedef void type;
};

template <class C, class V = void>
struct has_print_writer;

template <class C, class V>
struct has_print_writer {
};

template <class C>
struct has_print_writer<C, typename C::has_print_writer> {
  typedef void type;
};

template <class C, class V = void>
struct not_has_print_writer;

template <class C, class V>
struct not_has_print_writer {
  typedef void type;
};

template <class C>
struct not_has_print_writer<C, typename C::has_print_writer> {
};

template <class C, class V = void, class V2 = void>
struct has_print_plain;

template <class C, class V, class V2>
struct has_print_plain {
};

template <class C>
struct has_print_plain<C, typename not_has_print_writer<C>::type, typename has_print<C>::type> {
  typedef void type;
};

// type is defined iff you're not a pointer type and you have no print(o) or print(o,writer)
template <class C, class V = void>
struct not_has_print;

template <class C, class V>
struct not_has_print {
  typedef void type;
};

template <class C>
struct not_has_print<C, typename has_print<C>::type> {
};

template <class C>
struct not_has_print<C, typename has_print_writer<C>::type> {
};

template <class C>
struct isa_pointer;

template <class C>
struct isa_pointer {
};

template <class C>
struct isa_pointer<C *> {
  typedef void type;
};
template <class C>
struct isa_pointer<C * const> {
  typedef void type;
};
template <class C>
struct isa_pointer<C * volatile> {
  typedef void type;
};
template <class C>
struct isa_pointer<C * const volatile> {
  typedef void type;
};

template <class C>
struct true_value
{
  static const bool value = true;
};

template <class C>
struct not_has_print<C, typename isa_pointer<C>::type> {
};

template <class C, class V = void>
struct has_const_iterator
{
  static const bool value = false;
};

template <class C>
struct has_const_iterator<C, typename boost::enable_if<true_value<typename C::const_iterator> > > {
  typedef void type;
  static const bool value = true;
};

template <class C, class V = void>
struct not_has_const_iterator
{
  typedef void type;
  static const bool value = true;
};

template <class C>
struct not_has_const_iterator<C, typename boost::enable_if<true_value<typename C::const_iterator> > > {
  static const bool value = false;
};

#  ifndef DEFAULT_PRINT_ON_NO_REFERENCE_WRAPPER

template <class C>
struct has_print<boost::reference_wrapper<C> > : public has_print<C> {};
template <class C>
struct not_has_print<boost::reference_wrapper<C> > : public not_has_print<C> {};
template <class C>
struct has_print_writer<boost::reference_wrapper<C> > : public has_print_writer<C> {};
template <class C>
struct has_print_plain<boost::reference_wrapper<C> > : public has_print_plain<C> {};
template <class C>
struct not_has_print_writer<boost::reference_wrapper<C> > : public not_has_print_writer<C> {};

template <class C>
struct has_const_iterator<boost::reference_wrapper<C> > : public has_const_iterator<C> {};
template <class C>
struct not_has_const_iterator<boost::reference_wrapper<C> > : public not_has_const_iterator<C> {};

#  endif

}

#endif

max_stars_repo_name: graehl/carmel

max_issues_repo_name: graehl/carmel

max_forks_repo_name: graehl/carmel


text:
    /**
  *********************************************************************
*************************************************************************
***
*** \file  FileEventWatcher.cpp
*** \brief FileEventWatcher class body
***
*****************************************
  *****************************************
    **/

/*

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

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

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

*/

#include "FileEventWatcher.hpp"
#include "Debug.hpp"
#include "Exception.hpp"
#include "Util.hpp"
#include "UtilTime.hpp"
#include <boost/bind.hpp>
#include <boost/filesystem/operations.hpp>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>

using namespace std;
using namespace boost;
using namespace H;

////////////////////////////////////////////////////////////////////////////
// Type Defs / Defines
///////////////////////////////////////

/**
 * \def   READ_BUF_SIZE
 * \brief Default size of the read buffer for the automatic file reader
**/
#define READ_BUF_SIZE		65536

/**
 * \def   NOTIFY_EVENT_SIZE
 * \brief Human friendly size of the inotify_event struct
**/
#define NOTIFY_EVENT_SIZE	(sizeof(struct inotify_event))

/**
 * \def   NOTIFY_READ_BUF_SIZE
 * \brief Default size of the inotify read buffer for the automatic file reader
**/
#define NOTIFY_READ_BUF_SIZE	1024 * (NOTIFY_EVENT_SIZE + 16)

/**
 * \def   DEVICE_NAME_BUF_SIZE
 * \brief Default size of the device name buffer
**/
#define DEVICE_NAME_BUF_SIZE	1024

/**
 * \def   RETRY_FAIL_WAIT_NSECS
 * \brief Amount of nanoseconds to wait on an open of a new device before retrying
**/
#define RETRY_FAIL_WAIT_NSECS	100000000

/**
 * \def   MAX_RETRIES
 * \brief Maximum number of retries when opening a new device
**/
#define MAX_RETRIES		5

/**
 * \def    POLL_TIMEOUT
 * \brief  Poll timeout in milliseconds
**/
#define POLL_TIMEOUT	1000

////////////////////////////////////////////////////////////////////////////
// Construction
///////////////////////////////////////

/**
 * \brief DeviceInfo Default Constructor
**/
DeviceInfo::DeviceInfo() {
	DeviceIDBusType = -1;
	DeviceIDProduct = -1;
	DeviceIDVendor = -1;
	DeviceIDVersion = -1;
}

/**
 * \brief DeviceInfo Init Constructor
**/
DeviceInfo::DeviceInfo(std::string deviceName, std::string fileName, int deviceIDBusType, int deviceIDVendor, int deviceIDProduct, int deviceIDVersion, int fileDescriptor) {
	DeviceName = deviceName;
	FileName = fileName;
	DeviceIDBusType = deviceIDBusType;
	DeviceIDVendor = deviceIDVendor;
	DeviceIDProduct = deviceIDProduct;
	DeviceIDVersion = deviceIDVersion;
	FileDescriptor = fileDescriptor;
}

/**
 * \brief DeviceInfo Init Constructor
**/
DeviceInfo::DeviceInfo(const DeviceInfo & DeviceInformation) {
	DeviceName = DeviceInformation.DeviceName;
	FileName = DeviceInformation.FileName;
	DeviceIDBusType = DeviceInformation.DeviceIDBusType;
	DeviceIDVendor = DeviceInformation.DeviceIDVendor;
	DeviceIDProduct = DeviceInformation.DeviceIDProduct;
	DeviceIDVersion = DeviceInformation.DeviceIDVersion;
	FileDescriptor = DeviceInformation.FileDescriptor;
}

/**
 * \brief DeviceInfo Destructor
**/
DeviceInfo::~DeviceInfo() {
}

/**
 * \brief FileEventWatcher Default Constructor
**/
FileEventWatcher::FileEventWatcher() {
	mPolling = false;
	if ((mInotifyFD = inotify_init()) < 0)
		throw H::Exception("Failed to Initialize Inotify!\n    - Inotify must be compiled into the kernel, or installed as a kernel module\n    - Set kernel options CONFIG_INOTIFY, and CONFIG_INOTIFY_USER to yes", __FILE__, __FUNCTION__, __LINE__);
}

/**
 * \brief FileEventWatcher Destructor
**/
FileEventWatcher::~FileEventWatcher() {
	removeAllWatchDescriptors();
	if (mInotifyFD != -1)
		close(mInotifyFD);
}

/**
 * \brief FileWatchee Default Constructor
**/
FileWatchee::FileWatchee() {
	WatchType = WATCH_IN;
	fd = -1;
	Events = POLLIN;
}

/**
 * \brief FileWatchee Init Constructor
**/
FileWatchee::FileWatchee(std::string fileName, FileWatchType watchType, short events, int fileDescriptor, int watchDescriptor, std::string deviceName, int deviceIDBusType, int deviceIDVendor, int deviceIDProduct, int deviceIDVersion) :
	DeviceInfo(deviceName, fileName, deviceIDBusType, deviceIDVendor, deviceIDProduct, deviceIDVersion, fileDescriptor)
{
	WatchType = watchType;
	Events = events;
	fd = fileDescriptor;
	wd = watchDescriptor;
	if (fd < 0)
		DeviceType = WATCH_INOTIFY;
	else
		DeviceType = WATCH_POLL;
}

/**
 * \brief FileWatchee Destructor
**/
FileWatchee::~FileWatchee() {
	if (fd > -1)
		close(fd);
}

////////////////////////////////////////////////////////////////////////////
// Class Body
///////////////////////////////////////

/**
 * \brief Add a file to watch for events
 * \param FileName Absolute path of the file to watch
 * \param WatchType Type of watch to perform on the file
 * \param DefaultDeviceName Default device name if the device does not support having a name
**/
boost::shared_ptr<FileWatchee> FileEventWatcher::addFileToWatch(std::string FileName, FileWatchType WatchType, std::string DefaultDeviceName) {
	// make sure we're not already watching this file
	shared_ptr<FileWatchee> pDupWatchee = getWatcheeByPath(FileName);
	if (pDupWatchee) {
		//if (H::Debug::testPrint(dbg0))
		//	H::dbg0 << "Already Watching File [" << FileName << "]" << endl;
		cdbg << "Already Watching File [" << FileName << "]" << endl;
		return shared_ptr<FileWatchee>();
	}
	pDupWatchee.reset();
	cdbg1 << "Adding File [" << FileName << "] to Watch List with Mode [" << WatchType << "]" << endl;

	// get mode mask
	int 	flags = 0;
	string 	ModeString;
	short	events = 0;
	switch (WatchType) {
	case WATCH_IN:
		flags = O_RDONLY;
		events = POLLIN;
		ModeString = "Read";
		break;
	case WATCH_OUT:
		flags = O_WRONLY;
		events = POLLOUT;
		ModeString = "Write";
		break;
	case WATCH_INOUT:
		flags = O_RDWR;
		events = POLLIN | POLLOUT;
		ModeString = "Read / Write";
		break;
	case WATCH_INVALID:
		throw H::Exception("Invalid Watch Type specified on [" + FileName + "]", __FILE__, __FUNCTION__, __LINE__);
	}

	// make sure it exists
	filesystem::path FilePath(FileName);
	if (!filesystem::exists(FilePath))
		throw H::Exception("Path [" + FileName + "] does not exist, or cannot open (perms?) with Mode [" + ModeString + "]", __FILE__, __FUNCTION__, __LINE__);

	// if it's a directory, then watch with inotify, otherwise use poll
	int fd = -1;
	int wd = -1;
	char DeviceName[DEVICE_NAME_BUF_SIZE] = {'\0'};
	unsigned short DeviceIDs[4] = {-1, -1, -1, -1};
	if (filesystem::is_directory(FilePath)) {
		// directory, add watch
		if ((wd = inotify_add_watch(mInotifyFD, FileName.c_str(), IN_CREATE | IN_DELETE | IN_DELETE_SELF)) == -1)
			throw H::Exception("Failed to add Watch on Directory [" + FileName + "]", __FILE__, __FUNCTION__, __LINE__);
		fd = -wd;
		mInotifyWDs.push_back(wd);
		strcpy(DeviceName, "Directory");
	} else {
		// not a directory, open the device
		int retry;
		for (retry = 0; retry < MAX_RETRIES; retry ++) {
			if ((fd = open(FileName.c_str(), flags)) == -1) {
				cdbg1 << "New Device [" << FileName << "] Open Failed -- Retrying" << endl;
				UtilTime::nanoSleep(RETRY_FAIL_WAIT_NSECS);
				continue;
			}
			break;
		}
		if (retry == MAX_RETRIES) {
			//throw H::Exception("Failed to Open file [" + FileName + "] with Mode [" + ModeString + "]", __FILE__, __FUNCTION__, __LINE__);
			cerr << "Failed to Open [" << FileName << "] for [" << ModeString + "] -- Check Permissions!" << endl;
			return shared_ptr<FileWatchee>();
		}

		// get the device name
		if (ioctl(fd, EVIOCGNAME(sizeof(DeviceName)), DeviceName) < 0) {
			cdbg3 << "Failed to Get Device Name for [" + FileName + "]" << endl;
			strcpy(DeviceName, DefaultDeviceName.c_str());
		}

		// get the device id information
		if (ioctl(fd, EVIOCGID, DeviceIDs) < 0)
			cdbg3 << "Failed to Get Device IDs for [" + FileName + "]" << endl;
	}

	cdbg1 << "Watching Device [" << FileName << "]: " << DeviceName << endl;
	shared_ptr<FileWatchee> pWatchee(new FileWatchee(FileName, WatchType, events, fd, wd, DeviceName, DeviceIDs[0], DeviceIDs[1], DeviceIDs[2], DeviceIDs[3]));
	mWatchees.insert(make_pair(fd, pWatchee));
	buildPollFDArrayFromWatchees();
	onFileEventRegister(pWatchee);

	return pWatchee;
}

/**
 * \brief Add a unix socket to watch for events
 * \param FileName Absolute path of the file to watch
 * \param DeviceName Device name
**/
boost::shared_ptr<FileWatchee> FileEventWatcher::addUnixSocketToWatch(std::string FileName, std::string DeviceName) {
	// get mode mask
	string	 	ModeString = "Read";
	short		events = POLLIN;
	FileWatchType 	WatchType = WATCH_IN;

	// make sure it exists
	filesystem::path FilePath(FileName);
	if (!filesystem::exists(FilePath))
		throw H::Exception("Path [" + FileName + "] does not exist, or cannot open (perms?) with Mode [" + ModeString + "]", __FILE__, __FUNCTION__, __LINE__);

	// set up the datastructure
	struct sockaddr_un Addr;
	Addr.sun_family = AF_UNIX;
	strcpy(Addr.sun_path, FileName.c_str());

	// open the unix socket
	int fd;
	if ((fd = socket(AF_UNIX,SOCK_STREAM, 0)) == -1) {
		cdbg1 << "Failed to Creat Socket for [" << FileName << "] for [" << ModeString + "] -- Check Permissions!" << endl;
		return shared_ptr<FileWatchee>();
	}

	// connect to the socket
	if (connect(fd,(struct sockaddr *) &Addr,sizeof(Addr)) == -1)  {
		cdbg1 << "Failed to Connect to [" << FileName << "] for [" << ModeString + "] -- Check Permissions!" << endl;
		close(fd);
		return shared_ptr<FileWatchee>();
	}

	cdbg1 << "Watching Unix Socket [" << FileName << "]: " << DeviceName << endl;
	shared_ptr<FileWatchee> pWatchee(new FileWatchee(FileName, WatchType, events, fd, -1, DeviceName, -1, -1, -1, -1));
	mWatchees.insert(make_pair(fd, pWatchee));
	buildPollFDArrayFromWatchees();
	onFileEventRegister(pWatchee);

	return pWatchee;
}

/**
 * \brief  Build the mPollFDs array from the list of watchees
**/
void FileEventWatcher::buildPollFDArrayFromWatchees() {
	// clear out the pollfsd
	mPollFDs.clear();

	// put in the inotify pollfd
	struct pollfd PollFD;
	PollFD.fd = mInotifyFD;
	PollFD.events = POLLIN | POLLOUT;
	PollFD.revents = 0;
	mPollFDs.push_back(PollFD);

	// build the rest of the pollfds via the functor
	apply_func(mWatchees, &FileEventWatcher::buildPollFDArrayFunctor, this);
}

/**
 * \brief Functor for building the array of mPollFDs
 * \param pWatchee The Watchee
**/
void FileEventWatcher::buildPollFDArrayFunctor(std::pair< int, boost::shared_ptr<FileWatchee> > WatcheePair) {
	boost::shared_ptr<FileWatchee> pWatchee = WatcheePair.second;
	if ( (!pWatchee) || (pWatchee->fd < 0) )
		return;

	// Add the new watchee to the list
	struct pollfd PollFD;
	PollFD.fd = pWatchee->fd;
	PollFD.events = pWatchee->Events;
	PollFD.revents = 0;
	mPollFDs.push_back(PollFD);
}

/**
 * \brief  Get the type of the file event
 * \param  Index The index of the file to check
 * \return Type of the event (FileWatchType)
**/
FileWatchType FileEventWatcher::getType(int Index) {
	if (mPollFDs[Index].revents & POLLIN)
		return WATCH_IN;
	else if (mPollFDs[Index].revents & POLLOUT)
		return WATCH_OUT;
	else if (mPollFDs[Index].revents & POLLOUT & POLLIN)
		return WATCH_INOUT;
	else
		return WATCH_INVALID;
}

/**
 * \brief  Get a Watchee by its file descriptor
 * \param  fd File Desriptor of the desired watchee
 * \return The watchee (shared_ptr to FileWatchee)
**/
boost::shared_ptr<FileWatchee> FileEventWatcher::getWatcheeByFileDescriptor(int fd) {
	return mWatchees[fd];
}

/**
 * \brief  Get a Watchee by its file name
 * \param  FileName File name of watchee to get
 * \return The watchee (shared_ptr to FileWatchee)
**/
boost::shared_ptr<FileWatchee> FileEventWatcher::getWatcheeByPath(std::string FileName) {
	map< int, shared_ptr<FileWatchee> >::iterator iter;
	for (iter = mWatchees.begin(); iter != mWatchees.end(); iter ++) {
		shared_ptr<FileWatchee> pWatchee = iter->second;
		if (!pWatchee) {
			mWatchees.erase(iter);
			continue;
		}
		if (pWatchee->FileName == FileName)
			return pWatchee;
	}

	// not found, return null shared pointer
	return shared_ptr<FileWatchee>();
}

/**
 * \brief  Get a Watchee by its watch descriptor
 * \param  wd Watch Desriptor of the desired watchee
 * \return The watchee (shared_ptr to FileWatchee)
**/
boost::shared_ptr<FileWatchee> FileEventWatcher::getWatcheeByWatchDescriptor(int wd) {
	return mWatchees[-wd];
}

/**
 * \brief  Read the input event waiting on a file descriptor
 * \param  fd The file descriptor
 * \param  Buffer The buffer to place contents into
**/
void FileEventWatcher::readFromFile(int fd, DynamicBuffer<char> & Buffer) {
	char ReadBuffer[READ_BUF_SIZE];
	ssize_t BytesRead;
	do {
		if ((BytesRead = read(fd, ReadBuffer, READ_BUF_SIZE)) <= 0)
			throw H::DeviceDisconnectException();
		Buffer.addToBuffer(ReadBuffer, BytesRead);
	} while (BytesRead == READ_BUF_SIZE);
}

/**
 * \brief Functor that checks for and handles events on a pollfd object
 * \param item The item to check and handle events for
**/
void FileEventWatcher::handleEventsOnFile(struct pollfd & item) {
	if (item.fd == mInotifyFD) {
		if (item.revents & POLLERR) {
			cdbg << "Error detected on inotify device" << endl;
		} else if ( (item.revents & POLLIN) || (item.revents & POLLPRI) ) {
			// read from the inotify device
			char ReadBuffer[NOTIFY_READ_BUF_SIZE];
			int BytesRead = read(mInotifyFD, ReadBuffer, NOTIFY_READ_BUF_SIZE);
			if (BytesRead < 0) {
				if (errno == EINTR)
					return;
				else
					throw H::Exception("Failed to Read from Inotify Device!", __FILE__, __FUNCTION__, __LINE__);
                        }

			// loop through all of the returned inotify_event structures and produce events
			int BytesHandled = 0;
			while (BytesHandled < BytesRead) {
				struct inotify_event * event;
				event = (struct inotify_event *) &ReadBuffer[BytesHandled];
				BytesHandled += NOTIFY_EVENT_SIZE + event->len;

				shared_ptr<FileWatchee> pWatchee = getWatcheeByWatchDescriptor(event->wd);
				if (!pWatchee) {
					cerr << "Unhandled inotify event: " << event->name << endl;
					continue;
				}

				if (event->mask & IN_ACCESS)
					cout << "Access" << endl;
				if (event->mask & IN_ATTRIB)
					cout << "Attrib" << endl;
				if (event->mask & IN_CLOSE_WRITE)
					cout << "CloseWrite" << endl;
				if (event->mask & IN_CLOSE_NOWRITE)
					cout << "CloseNoWrite" << endl;
				if (event->mask & IN_CREATE)
					onFileEventCreate(pWatchee, pWatchee->FileName + "/" + event->name, event->name);
				if ( (event->mask & IN_DELETE) || (event->mask & IN_DELETE_SELF) ) {
					// pass in the actual watchee rather than the directory watchee
					shared_ptr<FileWatchee> pActualWatchee = getWatcheeByPath(pWatchee->FileName + "/" + event->name);
					if (!pActualWatchee) {
						cdbg2 << "Delete inotify event on unhandled file: " << event->name << endl;
						continue;
					}
					onFileEventDelete(pActualWatchee, pActualWatchee->FileName, event->name);
				}
				if (event->mask & IN_MODIFY)
					cout << "Modify" << endl;
				if (event->mask & IN_MOVE_SELF)
					cout << "MoveSelf" << endl;
				if (event->mask & IN_MOVED_FROM)
					cout << "MovedFrom" << endl;
				if (event->mask & IN_MOVED_TO)
					cout << "MovedTo" << endl;
				if (event->mask & IN_OPEN)
					cout << "Open" << endl;
				if (event->mask & IN_UNMOUNT)
					cout << "Unmount" << endl;
			}
		}
	} else if (item.fd >= 0) {
		if (item.revents & POLLERR) {
			shared_ptr<FileWatchee> pWatchee = getWatcheeByFileDescriptor(item.fd);
			if (pWatchee) {
				cdbg5 << "Error detected on poll device: " << item.fd << " -- " << pWatchee->FileName << endl;
				onFileEventDisconnect(pWatchee);
				removeWatchee(pWatchee);
			} else {
				cdbg5 << "Error detected on poll device: " << item.fd << endl;
				buildPollFDArrayFromWatchees();
			}
		} else if ( (item.revents & POLLIN) || (item.revents & POLLPRI) ) {
			// poll device, try to read from it
			shared_ptr<FileWatchee> pWatchee = getWatcheeByFileDescriptor(item.fd);
			if (!pWatchee) {
				cdbg5 << "Unhandled file event on fd [" << item.fd << "]" << endl;
				buildPollFDArrayFromWatchees();
				return;
			}
			try {
				DynamicBuffer<char> Buffer;
				readFromFile(item.fd, Buffer);
				if (pWatchee)
					onFileEventRead(pWatchee, Buffer);
			} catch (H::DeviceDisconnectException & e) {
				if ( (pWatchee) && (pWatchee->DeviceType == WATCH_POLL) ) {
					onFileEventDisconnect(pWatchee);
					removeWatchee(pWatchee);
				} else
					cout << "Disconnect from Unknown Device" << endl;
			}
		}
	}
}

/**
 * \brief Event triggered when a new file is created
 * \param pWatchee The Watchee that triggered the event
 * \param FullPath The full (absolute) path of the new file
 * \param FileName The file name (relative ) of the new file
**/
void FileEventWatcher::onFileEventCreate(boost::shared_ptr<FileWatchee> pWatchee, std::string FullPath, std::string FileName) {
	// override me
}

/**
 * \brief Event triggered when a file is deleted
 * \param pWatchee The Watchee that triggered the event
 * \param FullPath The full (absolute) path of the new file
 * \param FileName The file name (relative ) of the new file
**/
void FileEventWatcher::onFileEventDelete(boost::shared_ptr<FileWatchee> pWatchee, std::string FullPath, std::string FileName) {
	// override me
}

/**
 * \brief Event triggered when a file is disconnected
 * \param pWatchee The Watchee that triggered the event
**/
void FileEventWatcher::onFileEventDisconnect(boost::shared_ptr<FileWatchee> pWatchee) {
	// override me
}

/**
 * \brief Event triggered when data is waiting on a device
 * \param pWatchee The Watchee that triggered the event
 * \param ReadBuffer The data that was waiting on the device
**/
void FileEventWatcher::onFileEventRead(boost::shared_ptr<FileWatchee> pWatchee, DynamicBuffer<char> const & ReadBuffer) {
	// override me
}

/**
 * \brief Event triggered when a new device is registered
 * \param pWatchee The Watchee that triggered the event
**/
void FileEventWatcher::onFileEventRegister(boost::shared_ptr<FileWatchee> pWatchee) {
	// override me
}

/**
 * \brief Event called when the class will begin watching for events (and blocking)
**/
void FileEventWatcher::onFileEventWatchBegin() {
	// override me
}

/**
 * \brief Event called when the class has ended watching for events (and done blocking)
**/
void FileEventWatcher::onFileEventWatchEnd() {
	// override me
}

/**
 * \brief Unregister a watch descriptor with inotify
 * \param wd The watch descriptor
**/
void FileEventWatcher::removeWatchDescriptor(int wd) {
	inotify_rm_watch(mInotifyFD, wd);
}

/**
 * \brief Remove all watch descriptors
**/
void FileEventWatcher::removeAllWatchDescriptors() {
	apply_func(mInotifyWDs, &FileEventWatcher::removeWatchDescriptor, this);
}

/**
 * \brief Remove a watchee from the watch list
 * \param pWatchee The watchee to remove
**/
void FileEventWatcher::removeWatchee(boost::shared_ptr<FileWatchee> pWatchee) {
	if (!pWatchee)
		return;
	map< int, shared_ptr<FileWatchee> >::iterator iter;
	bool removed = false;
	for (iter = mWatchees.begin(); iter != mWatchees.end(); iter ++) {
		if (!iter->second)
			continue;
		if (iter->second->fd == pWatchee->fd) {
			cdbg4 << "Removed Watchee [" << pWatchee->FileName << "]" << endl;
			mWatchees.erase(iter);
			removed = true;
			break;
		}
	}
	if (removed)
		buildPollFDArrayFromWatchees();
}

/**
 * \brief Stop watching for file events
 *
 * This does not interrupt a current call to poll, so watchForFileEvents will only
 * exit after this function is called, and then the next event is received
**/
void FileEventWatcher::shutdown() {
	mPolling = false;
}

/**
 * \brief Watch for file events on already specified files
 *
 * Note: Blocking
**/
void FileEventWatcher::watchForFileEvents() {
	if (mPollFDs.size() == 0) {
		cdbg << "FileEventWatcher :: watchForFileEvents -- No file to watch!" << endl;
		return;
	}

	// fire notification of blocking
	onFileEventWatchBegin();

	cdbg1 << "FileEventWatcher :: Watching [" << (int) mPollFDs.size() << " Files] for Events..." << endl;
	mPolling = true;
	int ret;
	do {
		// poll the open files
		if ((ret = poll(&mPollFDs[0], mPollFDs.size(), POLL_TIMEOUT)) == -1) {
			// error
			cdbg1 << "Poll error: " << strerror(errno) << endl;
			//continue; // <-- for debugging, since the debugger fires signals and causes poll to abort

			// fire notification of end of blocking
			onFileEventWatchEnd();
			return;
		}

		if (!ret)
			// timeout
			continue;

		// file events have happened, check for them and dispatch
		cdbg5 << "Processing File Events..." << endl;
		apply_func(mPollFDs, &FileEventWatcher::handleEventsOnFile, this);
	} while (mPolling);
	cdbg1 << "FileEventWatcher :: Done Watching for File Events" << endl;

	// fire notification of end of blocking
	onFileEventWatchEnd();
}

max_stars_repo_name: pauljeremyturner/gizmod

max_issues_repo_name: pauljeremyturner/gizmod

max_forks_repo_name: pauljeremyturner/gizmod


text:
// Copyright (c) 2015-2018 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#ifndef coalescent_model_hpp
#define coalescent_model_hpp

#include <vector>
#include <unordered_map>
#include <functional>
#include <utility>
#include <functional>
#include <iterator>
#include <algorithm>
#include <cstddef>
#include <tuple>
#include <cassert>

#include <boost/functional/hash.hpp>
#include <boost/optional.hpp>

#include "core/types/haplotype.hpp"
#include "core/types/variant.hpp"
#include "indel_mutation_model.hpp"

namespace octopus {

class CoalescentModel
{
public:
    using LogProbability = double;

    struct Parameters
    {
        double snp_heterozygosity   = 0.001;
        double indel_heterozygosity = 0.0001;
    };

    enum class CachingStrategy { none, value, address };

    CoalescentModel() = delete;

    CoalescentModel(Haplotype reference,
                    Parameters parameters,
                    std::size_t num_haplotyes_hint = 1024,
                    CachingStrategy caching = CachingStrategy::value);

    CoalescentModel(const CoalescentModel&)            = default;
    CoalescentModel& operator=(const CoalescentModel&) = default;
    CoalescentModel(CoalescentModel&&)                 = default;
    CoalescentModel& operator=(CoalescentModel&&)      = default;

    ~CoalescentModel() = default;

    void set_reference(Haplotype reference);

    void prime(std::vector<Haplotype> haplotypes);
    void unprime() noexcept;
    bool is_primed() const noexcept;

    // ln p(haplotype(s))
    LogProbability evaluate(const Haplotype& haplotype) const;
    template <typename Container> double evaluate(const Container& haplotypes) const;
    LogProbability evaluate(const std::vector<unsigned>& haplotype_indices) const;

private:
    using VariantReference = std::reference_wrapper<const Variant>;
    using SiteCountTuple = std::tuple<unsigned, unsigned, unsigned>;
    using SiteCountIndelTuple = std::tuple<unsigned, unsigned, unsigned, double>;

    struct SiteCountTupleHash
    {
        std::size_t operator()(const SiteCountIndelTuple& t) const noexcept
        {
            return boost::hash_value(t);
        }
    };

    Haplotype reference_;
    IndelMutationModel::ContextIndelModel indel_heterozygosity_model_;
    Parameters params_;
    std::vector<Haplotype> haplotypes_;
    CachingStrategy caching_;

    mutable std::vector<VariantReference> site_buffer1_, site_buffer2_;
    mutable std::unordered_map<Haplotype, std::vector<Variant>> difference_value_cache_;
    mutable std::unordered_map<const Haplotype*, std::vector<Variant>> difference_address_cache_;
    mutable std::vector<boost::optional<std::vector<Variant>>> index_cache_;
    mutable std::vector<bool> index_flag_buffer_;
    mutable std::vector<std::vector<boost::optional<LogProbability>>> k_indel_zero_result_cache_;
    mutable std::unordered_map<SiteCountIndelTuple, LogProbability, SiteCountTupleHash> k_indel_pos_result_cache_;

    LogProbability evaluate(const SiteCountTuple& t) const;
    LogProbability evaluate(unsigned k_snp, unsigned n) const;
    LogProbability evaluate(unsigned k_snp, unsigned k_indel, unsigned n) const;

    void fill_site_buffer(const Haplotype& haplotype) const;
    template <typename Container> void fill_site_buffer(const Container& haplotypes) const;
    void fill_site_buffer(const std::vector<unsigned>& haplotype_indices) const;
    void fill_site_buffer_uncached(const Haplotype& haplotype) const;
    void fill_site_buffer_from_value_cache(const Haplotype& haplotype) const;
    void fill_site_buffer_from_address_cache(const Haplotype& haplotype) const;

    SiteCountTuple count_segregating_sites(const Haplotype& haplotype) const;
    template <typename Container> SiteCountTuple count_segregating_sites(const Container& haplotypes) const;
    SiteCountTuple count_segregating_sites_in_buffer(unsigned num_haplotypes) const;
    double calculate_buffered_indel_heterozygosity() const;
    double calculate_heterozygosity(const Variant& indel) const;
};

template <typename Container>
CoalescentModel::LogProbability CoalescentModel::evaluate(const Container& haplotypes) const
{
    return evaluate(count_segregating_sites(haplotypes));
}

// private methods

template <typename Container>
void CoalescentModel::fill_site_buffer(const Container& haplotypes) const
{
    assert(site_buffer2_.empty());
    site_buffer1_.clear();
    for (const Haplotype& haplotype : haplotypes) {
        switch (caching_) {
            case CachingStrategy::address: fill_site_buffer_from_address_cache(haplotype); break;
            case CachingStrategy::value: fill_site_buffer_from_value_cache(haplotype); break;
            default: fill_site_buffer_uncached(haplotype);
        }
        site_buffer1_ = std::move(site_buffer2_);
        site_buffer2_.clear();
    }
}

namespace detail {

template <typename Container>
auto size(const Container& haplotypes) noexcept
{
    // Use this because Genotype template does not have a size member method (uses ploidy instead).
    return std::distance(std::cbegin(haplotypes), std::cend(haplotypes));
}

} // namespace detail

template <typename Container>
CoalescentModel::SiteCountTuple
CoalescentModel::count_segregating_sites(const Container& haplotypes) const
{
    fill_site_buffer(haplotypes);
    return count_segregating_sites_in_buffer(detail::size(haplotypes));
}

struct CoalescentProbabilityGreater
{
    CoalescentProbabilityGreater(CoalescentModel model);

    bool operator()(const Haplotype& lhs, const Haplotype& rhs) const;

private:
    CoalescentModel model_;
    mutable std::vector<Haplotype> buffer_;
    mutable std::unordered_map<Haplotype, CoalescentModel::LogProbability, std::hash<Haplotype>, HaveSameAlleles> cache_;
};

} // namespace octopus

#endif

max_stars_repo_name: gmagoon/octopus

max_issues_repo_name: gmagoon/octopus

max_forks_repo_name: gmagoon/octopus


text:
//
// Copyright (c) 2021 Richard Hodges (hodges.r@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/madmongo1/boost_channels
//
#include <boost/channels/channel.hpp>
#include <boost/channels/channel_consumer.hpp>
#include <boost/channels/channel_producer.hpp>
#include <boost/channels/tie.hpp>

#include <boost/asio/co_spawn.hpp>
#include <boost/asio/redirect_error.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/use_future.hpp>

#include <iostream>
#include <string>

#include <string_view>

using namespace boost;
using namespace std::literals;

auto
produce(channels::channel< std::string > &c) -> asio::awaitable< void >
{
    auto [rng, dist] = [] {
        std::random_device rd;
        std::mt19937       g(rd());
        return std::make_tuple(g, std::uniform_int_distribution< int >(0, 100));
    }();
    constexpr auto wait = asio::use_awaitable;
    auto           t = asio::steady_timer(co_await asio::this_coro::executor);
    std::string    words[] = { "The", "cat", "sat", "on", "the", "mat" };
    for (auto &word : words)
    {
        co_await(word >> c).async_wait(wait);
        t.expires_after(std::chrono::milliseconds(50 + dist(rng)));
        co_await t.async_wait(wait);
    }
    c.close();
}

auto
consume(channels::channel< std::string > &c1,
        channels::channel< std::string > &c2,
        channels::channel< std::string > &c3) -> asio::awaitable< void >
{
    auto [rng, dist] = [] {
        std::random_device rd;
        std::mt19937       g(rd());
        return std::make_tuple(g, std::uniform_int_distribution< int >(0, 100));
    }();
    auto t        = asio::steady_timer(co_await asio::this_coro::executor);
    auto ec       = channels::error_code();
    auto tok      = asio::redirect_error(asio::use_awaitable, ec);
    bool done[]   = { false, false, false };
    auto not_done = [](bool done) { return !done; };

    std::string s;
    // consume as fast as we can until one of the channels is closed
    while (std::all_of(std::begin(done), std::end(done), not_done))
    {
        t.expires_after(std::chrono::milliseconds(50 + dist(rng)));
        co_await t.async_wait(asio::use_awaitable);
        auto which =
            co_await channels::tie(s << c1, s << c2, s << c3).async_wait(tok);
        if (ec)
        {
            std::cout << which << " : " << ec.message() << "\n";
            done[which] = true;
            break;
        }
        else
            std::cout << which << " : " << s << "\n";
    }

    // now clean up remaining channels
    channels::channel< std::string > *chans[] = { &c1, &c2, &c3 };
    for (int i = 0; i < 3; ++i)
    {
        while (!done[i])
        {
            ec.clear();
            s = co_await chans[i]->async_consume(tok);
            if (ec)
            {
                std::cout << i << " : " << ec.message() << "\n";
                done[i] = true;
            }
            else
                std::cout << i << " : " << s << "\n";
        }
    }
}

int
main()
{
    auto e = asio::system_executor();

    auto c1 = channels::channel< std::string >(e),
         c2 = channels::channel< std::string >(e),
         c3 = channels::channel< std::string >(e);

    auto fc  = asio::co_spawn(e, consume(c1, c2, c3), asio::use_future);
    auto fp1 = asio::co_spawn(e, produce(c1), asio::use_future);
    auto fp2 = asio::co_spawn(e, produce(c2), asio::use_future);
    auto fp3 = asio::co_spawn(e, produce(c3), asio::use_future);

    fc.get();
    fp1.get();
    fp2.get();
    fp3.get();
}


text:
/*
 * simd_sys_crm.cpp
 *
 *  Description:
 *    Clock and reset manager: channel and interface to the clocked modules
 */

#include <map>
#include <boost/container/throw_exception.hpp>

// temporarily disable pedantic warning for GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#include <boost/spirit/include/qi.hpp>
#pragma GCC diagnostic pop

#include <boost/lexical_cast.hpp>
#include "simd_sys_crm.h"

namespace boost_cn = boost::container;
namespace boost_qi = boost::spirit::qi;

namespace simd {

SC_HAS_PROCESS( simd::simd_sys_crm_c );
simd_sys_crm_c::simd_sys_crm_c(
      sc_core::sc_module_name nm ) : sc_core::sc_module( nm ) {
   // Initialisations
   clock_p = NULL;

   // Internal Channel allocations

   // Submodule allocations

   // Submodule Connections

   // Process registrations
   SC_THREAD( clock_thrd );   // thread for clock signal assignment to the output port
   SC_THREAD( reset_thrd );   // Reset generator
}

void simd_sys_crm_c::init(
      boost::optional<const boost_pt::ptree&> pref_p ) {

   const boost_pt::ptree& pref = pref_p.get();

   // Set resolution
   boost::optional<std::string> freq_p = pref.get_optional<std::string>("freq");

   if(( !freq_p ) || ( freq_p.get().length() == 0 )) {
      SIMD_REPORT_FATAL( "simd::sys_crm" ) << "Operating frequency is not set";
   }
   else {
      period = to_period( freq_p.get() );
      SIMD_REPORT_INFO( "simd::sys_crm" ) << "Operating frequency is set to <" << freq_p.get() << ">";
   }

   clock_p = new sc_core::sc_clock(
         /*name_         */ "clk",
         /*period_       */ period,
         /*duty_cycle_   */ 0.5,
         /*start_time_   */ sc_core::SC_ZERO_TIME,
         /*posedge_first_*/ true );
}

void simd_sys_crm_c::clock_thrd(
      void ) {
   clock_o->write( false );

   for(;;) {
      sc_core::wait( clock_p->value_changed_event());
      clock_o->write( clock_p->read());
   }
}

void simd_sys_crm_c::reset_thrd(
      void ) {
   reset_o->write( false );
   sc_core::wait( sc_core::SC_ZERO_TIME );

   reset_o->write( false );
   for( int cyc = 0; cyc < 2; cyc ++ ) { // Wait for 2 clock cycles
      sc_core::wait( clock_p->posedge_event());
   }

   reset_o->write( true );
   for( int cyc = 0; cyc < 2; cyc ++ ) { // Wait for 2 clock cycles
      sc_core::wait( clock_p->posedge_event());
   }

   reset_o->write( false );
   for(;;) {    // Wait forever;
      sc_core::wait(); // Static sensitivity with no events in the sensitivity list
   }
}

std::map<std::string, sc_core::sc_time_unit> known_units_freq = {
   { "Hz" , sc_core::SC_SEC},
   { "kHz", sc_core::SC_MS },
   { "MHz", sc_core::SC_US },
   { "GHz", sc_core::SC_NS },
   { "THz", sc_core::SC_PS }
};

sc_core::sc_time simd_sys_crm_c::to_period(
      const std::string& str ) {
   double                val;
   std::string           unit_str;

   bool done = boost_qi::phrase_parse(
         str.begin(),
         str.end(),
         boost_qi::double_ >> ( boost_qi::string("Hz")  |
                                boost_qi::string("kHz") |
                                boost_qi::string("MHz") |
                                boost_qi::string("GHz") |
                                boost_qi::string("THz") ),
         boost_qi::space,
         val,
         unit_str );

   if( !done ) {
      SIMD_REPORT_ERROR( "simd::sys_crm" ) << "Incorrect format: " << str;
   }
   else if( val <= 0 ) {
      SIMD_REPORT_FATAL( "simd::sys_crm" ) << "Incorrect frequency value";
   }

   return sc_core::sc_time( 1./val, known_units_freq[unit_str] );
} // simd_sys_crm_c::to_period(...)

} // namespace simd

max_stars_repo_name: timurkelin/simsimd

max_issues_repo_name: timurkelin/simsimd

max_forks_repo_name: timurkelin/simsimd


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

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <string>

#include <boost/test/minimal.hpp>

#include "utils.h"
#include "xmpconsts.h"
#include "xmp.h"

using boost::unit_test::test_suite;

//void test_write_new_property()
int test_main(int argc, char *argv[])
{
	prepare_test(argc, argv, "test1.xmp");

	size_t len;
	char * buffer;

	FILE * f = fopen(g_testfile.c_str(), "rb");

	BOOST_CHECK(f != NULL);
	if (f == NULL) {
		exit(128);
	}
 	fseek(f, 0, SEEK_END);
	len = ftell(f);
 	fseek(f, 0, SEEK_SET);

	buffer = (char*)malloc(len + 1);
	size_t rlen = fread(buffer, 1, len, f);

	BOOST_CHECK(rlen == len);
	BOOST_CHECK(len != 0);

	BOOST_CHECK(xmp_init());
	BOOST_CHECK(xmp_get_error() == 0);

	XmpPtr xmp = xmp_new_empty();
	BOOST_CHECK(xmp_get_error() == 0);

	BOOST_CHECK(xmp_parse(xmp, buffer, len));
	BOOST_CHECK(xmp_get_error() == 0);

	BOOST_CHECK(xmp != NULL);

	XmpStringPtr reg_prefix = xmp_string_new();
	BOOST_CHECK(xmp_register_namespace(NS_CC, "cc", reg_prefix));
	BOOST_CHECK(xmp_get_error() == 0);
	BOOST_CHECK(strcmp("cc:", xmp_string_cstr(reg_prefix)) == 0);

	BOOST_CHECK(xmp_prefix_namespace_uri("cc", reg_prefix));
	BOOST_CHECK(xmp_get_error() == 0);
	BOOST_CHECK(strcmp(NS_CC, xmp_string_cstr(reg_prefix)) == 0);

	BOOST_CHECK(xmp_namespace_prefix(NS_CC, reg_prefix));
	BOOST_CHECK(xmp_get_error() == 0);
	BOOST_CHECK(strcmp("cc:", xmp_string_cstr(reg_prefix)) == 0);

	xmp_string_free(reg_prefix);

	BOOST_CHECK(xmp_set_property(xmp, NS_CC, "License", "Foo", 0));
	BOOST_CHECK(xmp_get_error() == 0);

	XmpStringPtr the_prop = xmp_string_new();
	BOOST_CHECK(xmp_get_property(xmp, NS_CC, "License", the_prop, NULL));
	BOOST_CHECK(xmp_get_error() == 0);
	BOOST_CHECK(strcmp("Foo", xmp_string_cstr(the_prop)) == 0);

	XmpDateTime the_dt;
	the_dt.year = 2005;
	the_dt.month = 12;
	the_dt.day = 25;
	the_dt.hour = 12;
	the_dt.minute = 42;
	the_dt.second = 42;
	the_dt.tzSign = XMP_TZ_UTC;
	the_dt.tzHour = 0;
	the_dt.tzMinute = 0;
	the_dt.nanoSecond = 0;
	BOOST_CHECK(xmp_set_property_date(xmp, NS_EXIF, "DateTimeOriginal",
									  &the_dt, 0));
	BOOST_CHECK(xmp_get_error() == 0);

	BOOST_CHECK(xmp_get_property(xmp, NS_EXIF, "DateTimeOriginal",
								 the_prop, NULL));
	BOOST_CHECK(xmp_get_error() == 0);
	BOOST_CHECK(strcmp("2005-12-25T12:42:42",
							 xmp_string_cstr(the_prop)) == 0);

	XmpDateTime the_dt2;
	BOOST_CHECK(xmp_get_property_date(xmp, NS_EXIF, "DateTimeOriginal",
									  &the_dt2, NULL));
	BOOST_CHECK(xmp_get_error() == 0);

	BOOST_CHECK(the_dt2.year == 2005);
	BOOST_CHECK(the_dt2.minute == 42);
	BOOST_CHECK(the_dt2.tzSign == XMP_TZ_UTC);

	xmp_string_free(the_prop);

	BOOST_CHECK(xmp_free(xmp));

	free(buffer);
	fclose(f);

	xmp_terminate();

	BOOST_CHECK(!g_lt->check_leaks());
	BOOST_CHECK(!g_lt->check_errors());
	return 0;
}

max_stars_repo_name: freedesktop-unofficial-mirror/exempi

max_issues_repo_name: freedesktop-unofficial-mirror/exempi

max_forks_repo_name: freedesktop-unofficial-mirror/exempi


text: #include <boost/compute/algorithm/stable_sort.hpp>


text:
#ifndef SUPERGENIUS_SRC_API_TRANSPORT_SESSION_HPP
#define SUPERGENIUS_SRC_API_TRANSPORT_SESSION_HPP

#include <boost/asio/buffer.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/write.hpp>
#include <boost/signals2/signal.hpp>

#include "api/transport/rpc_io_context.hpp"

namespace sgns::api {
  enum struct SessionType {
    kHttp = 1,
    kWs,
  };

  /**
   * @brief rpc session
   */
  class Session {
    template <class T>
    using Signal = boost::signals2::signal<T>;

    using OnRequestSignature = void(std::string_view,
                                    std::shared_ptr<Session> session);
    using OnRequest = Signal<OnRequestSignature>;

   public:
    using Context = RpcContext;
    using Socket = boost::asio::ip::tcp::socket;
    using ErrorCode = boost::system::error_code;
    using Streambuf = boost::asio::streambuf;
    using Timer = boost::asio::steady_timer;
    using Connection = boost::signals2::connection;
    using Duration = Timer::duration;
    using SessionId = uint64_t;

    /// Event handlers.
    using OnCloseHandler = std::function<void(SessionId, SessionType)>;

    virtual ~Session() = default;

    /**
     * @brief starts listening on socket
     */
    virtual void start() = 0;

    virtual Socket &socket() = 0;

    /**
     * @brief connects `on request` callback
     * @param callback `on request` callback
     */
    void connectOnRequest(std::function<OnRequestSignature> callback) {
      on_request_ = std::move(callback);
    }

    /**
     * @brief connects `on close` callback
     * @param handler `on close` event handler
     */
    void connectOnCloseHandler(OnCloseHandler &&handler) {
      on_close_ = std::move(handler);
    }

    /**
     * @brief process request message
     * @param request message to process
     */
    void processRequest(std::string_view request,
                        std::shared_ptr<Session> session) {
      on_request_(request, std::move(session));
    }

    /**
     * @brief send response message
     * @param message response message
     */
    virtual void respond(std::string_view message) = 0;

    /**
     * @brief makes `on close` notification to listener
     * @param id session id
     * @param type type of the closed session
     */
    void notifyOnClose(SessionId id, SessionType type) {
      if (nullptr != on_close_) on_close_(id, type);
    }

    /**
     * @brief method to get id of the session
     * @return id of the session
     */
    virtual SessionId id() const = 0;

    /**
     * @brief method to get type of the session
     * @return type of the session
     */
    virtual SessionType type() const = 0;

   private:
    std::function<OnRequestSignature> on_request_;  ///< `on request` callback
    OnCloseHandler on_close_;
  };

}  // namespace sgns::api

#endif  // SUPERGENIUS_SRC_API_TRANSPORT_SESSION_HPP

max_stars_repo_name: GeniusVentures/SuperGenius

max_issues_repo_name: GeniusVentures/SuperGenius

max_forks_repo_name: GeniusVentures/SuperGenius


text:
#include <boost/test/unit_test.hpp>

#include <scorum/chain/data_service_factory.hpp>
#include <scorum/chain/services/account.hpp>
#include <scorum/chain/services/dev_pool.hpp>
#include <scorum/chain/services/dynamic_global_property.hpp>

#include <scorum/chain/evaluators/proposal_evaluators.hpp>

#include <scorum/chain/schema/account_objects.hpp>
#include <scorum/chain/schema/dynamic_global_property_object.hpp>

#include "defines.hpp"

#include "object_wrapper.hpp"

#include <hippomocks.h>

namespace development_committee_transfer_evaluator_tests {

using namespace scorum::chain;
using namespace scorum::protocol;

struct fixture : public shared_memory_fixture
{
    MockRepository mocks;

    data_service_factory_i* services = mocks.Mock<data_service_factory_i>();

    account_service_i* account_service = mocks.Mock<account_service_i>();
    dev_pool_service_i* dev_pool_service = mocks.Mock<dev_pool_service_i>();

    using dgps_t = dynamic_global_property_service_i;

    fixture()
        : shared_memory_fixture()
    {
        mocks.ExpectCall(services, data_service_factory_i::account_service).ReturnByRef(*account_service);
        mocks.ExpectCall(services, data_service_factory_i::dev_pool_service).ReturnByRef(*dev_pool_service);
    }
};

BOOST_FIXTURE_TEST_CASE(throw_when_amount_gt_balance, fixture)
{
    mocks.ExpectCall(dev_pool_service, dev_pool_service_i::get_scr_balace).Return(asset(10, SCORUM_SYMBOL));

    development_committee_transfer_evaluator::operation_type op;
    op.amount = asset(20, SCORUM_SYMBOL);

    development_committee_transfer_evaluator evaluator(*services);

    SCORUM_CHECK_EXCEPTION(evaluator.do_apply(op), fc::assert_exception, "Not enough SCR in dev pool.");
}

BOOST_FIXTURE_TEST_CASE(decrease_dev_pool_scr_balance, fixture)
{
    development_committee_transfer_evaluator::operation_type op;
    op.amount = asset(20, SCORUM_SYMBOL);

    development_committee_transfer_evaluator evaluator(*services);

    mocks.OnCall(dev_pool_service, dev_pool_service_i::get_scr_balace).Return(asset(30, SCORUM_SYMBOL));

    mocks.ExpectCall(dev_pool_service, dev_pool_service_i::decrease_scr_balance).With(op.amount);

    account_object account = create_object<account_object>(shm);

    mocks.OnCall(account_service, account_service_i::get_account).With(_).ReturnByRef(account);
    mocks
        .OnCallOverload(account_service,
                        (void (account_service_i::*)(const account_object&, const asset&))
                            & account_service_i::increase_balance)
        .With(_, _);

    BOOST_CHECK_NO_THROW(evaluator.do_apply(op));
}

BOOST_FIXTURE_TEST_CASE(increase_account_balance, fixture)
{
    development_committee_transfer_evaluator::operation_type op;
    op.amount = asset(20, SCORUM_SYMBOL);
    op.to_account = "jim";

    development_committee_transfer_evaluator evaluator(*services);

    mocks.OnCall(dev_pool_service, dev_pool_service_i::get_scr_balace).Return(asset(30, SCORUM_SYMBOL));

    mocks.OnCall(dev_pool_service, dev_pool_service_i::decrease_scr_balance).With(_);

    account_object account = create_object<account_object>(shm);

    mocks.ExpectCall(account_service, account_service_i::get_account).With("jim").ReturnByRef(account);
    mocks
        .ExpectCallOverload(account_service,
                            (void (account_service_i::*)(const account_object&, const asset&))
                                & account_service_i::increase_balance)
        .With(_, op.amount);

    BOOST_CHECK_NO_THROW(evaluator.do_apply(op));
}

} // namespace development_committee_transfer_evaluator_tests

max_stars_repo_name: scorum/scorum

max_issues_repo_name: Scorum/Scorum

max_forks_repo_name: Scorum/Scorum