text:
import logging; log = logging.getLogger(__name__)

from . import BaseEndpointTestCase

class CouponsEndpointTestCase(BaseEndpointTestCase):
    """
    General
    """
    def test_coupons(self):
        print
        print "----------------------------------------------------------------------"
        print "Request: "
        params = {
                  "total": 1000,
                  "page": 1,
                  "per_page": 10,
                  "query": "bagel",
                  "online": 1,
                  "location": {"address":     "444 Castro St.",
                               "locality":    "Mountain View",
                               "region":      "CA",
                               "postal_code": "94041",
                               "country":     "United States",
                               "latitude":    37.390751,
                               "longitude":   -122.080953
                              },
                  "radius": 1000,
                  #"category_slugs": [], # [] means you're restricting to a 0 set and it would imply 0 results
                  #"provider_slugs": [], # [] means you're restricting to a 0 set and it would imply 0 results
                  "updated_after": "2013-11-04T16:18:04Z",
                  "order": "expires_at"
                 }
        response = self.api.coupons(params)
        print "Response: "
        print response

    def test_coupons_default(self):
        print
        print "----------------------------------------------------------------------"
        print "Request: "
        params = {
                  "location": {"address":     "444 Castro St.",
                               "locality":    "Mountain View",
                               "region":      "CA",
                               "postal_code": "94041",
                               "country":     "United States",
                               "latitude":    37.390751,
                               "longitude":   -122.080953
                              },
                 }
        response = self.api.coupons(params)
        print "Response: "
        print response

    def test_coupon(self):
        print
        print "----------------------------------------------------------------------"
        print "Request: "
        params = {
                  "user_id":1234, # Dummy user ID - helps track when commissions api is called
                  # Any other information that we want to track for this coupon
                 }
        response = self.api.coupons.coupon(9722, params)
        print "Response: "
        print response

    def test_clickTrack(self):
        print
        print "----------------------------------------------------------------------"
        print "Request: "
        response = self.api.coupons.clickTrack(9722)
        print "Response: "
        f = open('coupon.html', 'w')
        f.write(response['data'])
        f.close()
        print "Wrote response to coupon.html"
        #print response

    def test_image(self):
        print
        print "----------------------------------------------------------------------"
        print "Request: "
        params = {
                  "offer_id":9722,
                  "geometry":"400x300"
                 }
        response = self.api.coupons.image(9722, params)
        print "Response: "
        f = open('couponImage.gif', 'wb')
        f.write(response['data'])
        f.close()
        print "Wrote response to couponImage.gif"
        #print response


text:
describe LegacyFacter::Core::Suitable do
  class SuitableClass
    def initialize
      @confines = []
    end
    attr_reader :confines
    include LegacyFacter::Core::Suitable
  end

  subject(:suitable_obj) { SuitableClass.new }

  describe 'confining on facts' do
    it 'can add confines with a fact and a single value' do
      suitable_obj.confine kernel: 'Linux'
    end

    it 'creates a Facter::Util::Confine object for the confine call' do
      suitable_obj.confine kernel: 'Linux'
      conf = suitable_obj.confines.first
      expect(conf).to be_an_instance_of(LegacyFacter::Util::Confine).and(
        having_attributes(fact: :kernel, values: ['Linux'])
      )
    end
  end

  describe 'confining on blocks' do
    it 'can add a single fact with a block parameter' do
      suitable_obj.confine(:one) { true }
    end

    it 'creates a Util::Confine instance for the provided fact with block parameter' do
      block = -> { true }
      # Facter::Util::Confine.expects(:new).with("one")
      expect(LegacyFacter::Util::Confine).to receive(:new).with('one')
      suitable_obj.confine('one', &block)
    end

    it 'accepts a single block parameter' do
      suitable_obj.confine { true }
    end

    it 'creates a Util::Confine instance for the provided block parameter' do
      block = -> { true }
      expect(LegacyFacter::Util::Confine).to receive :new

      suitable_obj.confine(&block)
    end
  end

  describe 'determining weight' do
    it 'is zero if no confines are set' do
      expect(suitable_obj.weight).to eq 0
    end

    it 'defaults to the number of confines' do
      suitable_obj.confine kernel: 'Linux'
      expect(suitable_obj.weight).to eq 1
    end

    it 'can be explicitly set' do
      suitable_obj.has_weight 10
      expect(suitable_obj.weight).to eq 10
    end

    it 'prefers an explicit weight over the number of confines' do
      suitable_obj.confine kernel: 'Linux'
      suitable_obj.has_weight 11
      expect(suitable_obj.weight).to eq 11
    end

    it 'returns the class instance' do
      expect(suitable_obj.has_weight(10)).to be(suitable_obj)
    end
  end

  describe 'determining suitability' do
    it 'is true if all confines for the object evaluate to true' do
      suitable_obj.confine kernel: 'Linux'
      suitable_obj.confine operatingsystem: 'Redhat'

      suitable_obj.confines.each { |confine| allow(confine).to receive(:true?).and_return(true) }

      expect(suitable_obj).to be_suitable
    end

    it 'is false if any confines for the object evaluate to false' do
      suitable_obj.confine kernel: 'Linux'
      suitable_obj.confine operatingsystem: 'Redhat'
      allow(suitable_obj.confines.first).to receive(:true?).and_return(false)

      expect(suitable_obj).not_to be_suitable
    end

    it 'recalculates suitability on every invocation' do
      suitable_obj.confine kernel: 'Linux'

      allow(suitable_obj.confines.first).to receive(:true?).and_return(false)
      allow(suitable_obj.confines.first).to receive(:true?).and_return(true)

      expect(suitable_obj).to be_suitable
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#ifndef _CMT2_H_2006_04_13
#define _CMT2_H_2006_04_13

#ifndef _CMT_MONOLITHIC
#	include "cmt1.h"
#	include "cmtmessage.h"
#	include "xsens_fifoqueue.h"
#endif

namespace xsens {

//////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////// Support  functions ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

//! Find a valid message in the given buffer. If nothing is found, the function returns -1. Otherwise the index of the first character of the message is returned.
int32_t findValidMessage(const uint8_t* buffer, const uint16_t bufferLength);

//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// Cmt2s  /////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*! \brief Mid-level serial communication class.

	The class uses CMT level 1, but does not inherit from it. If software needs to access
	the level 1 component, it needs to be done through the getCmt1s() function.
*/
class Cmt2s {
private:
	//! This object cannot be copied, so this function is not implemented.
	Cmt2s(const Cmt2s& ref);

	/*! \brief The message received function.

		This function is automatically called every time a complete message was read from the
		connected COM port.
	*/
	CmtCallbackFunction m_onMessageReceived;
	//! Custom, user supplied parameter for the OnMessageReceived callback function, passed as the first argument
	int32_t m_onMessageReceivedInstance;
	//! Custom, user supplied parameter for the OnMessageReceived callback function, passed as the last argument
	void* m_onMessageReceivedParam;

	/*! \brief The message sent function.

		This function is automatically called every time a complete message was sent to the
		connected COM port.
	*/
	CmtCallbackFunction m_onMessageSent;
	//! Custom, user supplied parameter for the OnMessageSent callback function, passed as the first argument
	int32_t m_onMessageSentInstance;
	//! Custom, user supplied parameter for the OnMessageSent callback function, passed as the last argument
	void* m_onMessageSentParam;

protected:
		//! The baudrate that was last set to be used by the port
	uint32_t m_baudrate;
		//! The CMT level 1 object that this class operates on
	Cmt1s m_cmt1s;
		//! The last result of an operation
	mutable XsensResultValue m_lastResult;
		//! Buffer for reading data until a valid message is read. Should be rarely used.
	uint8_t m_readBuffer[CMT_DEFAULT_READ_BUFFER_SIZE];
		//! The number of valid bytes in the readBuffer.
	uint16_t m_readBufferCount;
		//! Timeout in ms for blocking operations
	uint32_t m_timeout;
		//! The timestamp at which to end an operation
	uint32_t m_toEnd;
public:
		//! Default constructor, initialize all members to their default values.
	Cmt2s();

		//! Destructor, de-initialize, free memory allocated for buffers, etc.
	~Cmt2s();

		//! Close the serial communication port.
	XsensResultValue close(void);

		//! Return the baudrate that is currently being used by the port
	uint32_t getBaudrate(void) { return (m_baudrate = m_cmt1s.getBaudrate()); }
	/*! \brief Return a reference to the embedded Cmt1s object.

		Any manipulation of the object should be done through Cmt2s. Cmt2s integrity is
		not guaranteed if the Cmt1s object is manipulated directly.
	*/
	Cmt1s* getCmt1s(void) { return &m_cmt1s; }
		//! Return the error code of the last operation.
	XsensResultValue getLastResult(void) const { return m_lastResult; }
		//! Retrieve the port that the object is connected to.
	XsensResultValue getPortNr(uint8_t& port) const;
	XsensResultValue getPortNr(int32_t& port) const;
	XsensResultValue getPortName(char *portname) const;
		//! Return the current timeout value in ms.
	uint32_t getTimeout(void) const { return m_timeout; }
		//! Return whether the communication port is open or not.
	bool isOpen (void) const { return (m_cmt1s.isOpen()); }
		//! Open a communication channel to the given serial port name.
	XsensResultValue open(const char *portName,
								const uint32_t baudRate = CMT_DEFAULT_BAUD_RATE);
#ifdef _WIN32
		//! Open a communication channel to the given COM port number.
	XsensResultValue open(const uint32_t portNumber,
								const uint32_t baudRate = CMT_DEFAULT_BAUD_RATE);
#endif
	/*! \brief Read a message from the COM port.

		The function reads data from the embedded Cmt1s object. The data is then converted
		into a Message object.
		If an error occurred, a NULL pointer is returned and the error code can be
		retrieved with getLastError().
	*/
	XsensResultValue readMessage(Message* rcv);

	//! Set the callback function for when a message has been received or sent
	XsensResultValue setCallbackFunction(CmtCallbackSelector tp, int32_t instance, CmtCallbackFunction func, void* param);

	/*! \brief Set the default timeout value to use in blocking operations.

		This function sets the level 2 timeout value. The L1 value is set to half the given
		timeout value.
	*/
	XsensResultValue setTimeout(const uint32_t ms = CMT2_DEFAULT_TIMEOUT);

	/*! \brief Wait for a message to arrive.

		The function waits for a message to arrive or until a timeout occurs.
		If the msgId parameter is set to a value other than 0, the function will wait
		until a message has arrived with that particular msgId.

		\note msgId 0 is the ReqDeviceID MID, but that is an outgoing only message. It is
		illogical to wait for a message that will never be sent to the host. So 0 is a
		safe value for the 'all' messages option.

		\note If an error message is received, the contents are stored in the m_lastResult
		field and a NULL value is returned immediately.
	*/
	XsensResultValue waitForMessage(Message* rcv, const uint8_t msgId, uint32_t timeoutOverride, bool acceptErrorMessage);
	/*! \brief Send a message over the COM port.

		The function attempts to write the message over the connected COM port.
		\param msg	The message to send.
	*/
	XsensResultValue writeMessage(Message* msg);
};

//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// Cmt2f  /////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

/*! \brief The mid-level file communication class.

	The class uses CMT level 1, but does not inherit from it. If software needs to access
	the level 1 component, it needs to be done through the getCmt1f() function.
*/
class Cmt2f {
private:
		//! This object cannot be copied, so this function is not implemented.
	Cmt2f(const Cmt2f& ref);

protected:
		//! The Cmt1f object that is used for the low-level operations
	Cmt1f m_cmt1f;
		//! The last result of an operation
	mutable XsensResultValue m_lastResult;

	bool m_readOnly;				//!< When set to true, the file is read-only and attempts to write to it will fail

public:
		//! Default constructor
	Cmt2f();
		//! Destructor.
	~Cmt2f();
		//! Close the file.
	XsensResultValue close(void);
		//! Close the file and delete it.
	XsensResultValue closeAndDelete(void);
		//! Create a new file with level 2 header
	XsensResultValue create(const char* filename);
		//! Create a new file with level 2 header
	XsensResultValue create(const wchar_t* filename);
		//! Get a reference to the embedded Cmt1f object
	Cmt1f* getCmt1f(void);

		//! Return the error code of the last operation.
	XsensResultValue getLastResult(void) const;
		//! Retrieve the filename that was last successfully opened.
	XsensResultValue getName(char* filename) const;
		//! Retrieve the filename that was last successfully opened.
	XsensResultValue getName(wchar_t* filename) const;
		//! Return whether the file is open or not.
	bool isOpen(void) const;
		//! Open a file and read the header
	XsensResultValue open(const char* filename, const bool readOnly = false);
		//! Open a file and read the header
	XsensResultValue open(const wchar_t* filename, const bool readOnly = false);
		//! Read the next message from the file, when msgId is non-zero, the first matching message will be returned
	XsensResultValue readMessage(Message* msg, const uint8_t msgId = 0);
		//! Get the current file size
	CmtFilePos getFileSize(void);
		//! Get the current read position
	CmtFilePos getReadPosition(void);
		//! Set the read position to the given position
	XsensResultValue setReadPosition(CmtFilePos pos);
		//! Write a message to the end of the file
	XsensResultValue writeMessage(const Message* msg);
};

} // end of xsens namespace

#endif	// _CMT2_H_2006_04_13


text:
#!/usr/bin/env node

/* Expects a slide number as first argument.
 * Will connect to the local pub/sub server,
 * and issue a "go to slide X" command, which
 * will be sent to all connected browsers.
 */

var io = require('socket.io-client');
var socket = io('http://localhost:3000');
socket.on('connect_error', function(){
  console.log('connection error');
  socket.close();
});
socket.emit('slide change', process.argv[2], function(){
  socket.close();
});


text:
#include "segment_container.hpp"
#include "pht_entry_container.hpp"
#include "section_contents_container.hpp"
#include "util.hpp"
#include <iomanip>
#include <sstream>

using namespace elf;

SegmentContainer::SegmentContainer(ELFFile *file, const std::pair<int, int> &interval,
    unsigned int index) : Container(file, true, interval), index(index)
{
    setName(ProgramHeaderTableContainer::getSegmentTitle(file, index));
}

std::vector<Container *> &SegmentContainer::getInnerContainers()
{
    if (innerContainers.empty())
    {
        ELFFile *efile = dynamic_cast<ELFFile *>(getFile());
#ifdef DEBUG
        assert(efile != nullptr);
#endif
        ELFIO::elfio *interpretor = efile->getELFIO();
        ELFIO::segment *segment = interpretor->segments[index];

        std::vector<Container *> &topLevel = efile->getTopLevelContainers();
        SectionContentsContainer *sectionContents =
            dynamic_cast<SectionContentsContainer *>(topLevel[4]);
#ifdef DEBUG
        assert(sectionContents != nullptr);
#endif
        std::vector<Container *> &sections = sectionContents->getInnerContainers();

        for (unsigned int i = 0; i < segment->get_sections_num(); ++i)
            addInnerContainer(sections[segment->get_section_index_at(i)]);
    }

    return innerContainers;
}

SegmentContainer::~SegmentContainer() {}


text:
require 'rails_helper'

RSpec.describe Supervisors::CommentsController, type: :routing do
  describe 'routing' do
    it 'routes to #create' do
      expect(post('supervisors/comments')).to route_to('supervisors/comments#create')
    end
  end
end

RSpec.describe CommentsController, type: :routing do
  describe 'routing' do
    it 'routes to #create' do
      expect(post('/comments')).to route_to('comments#create')
    end
  end
end


text:
#ifndef _StaticTreeBarrier_h_
#define _StaticTreeBarrier_h_

#include "atomic_ops.h"
#include <math.h>
#include <sched.h>

typedef enum bool{
	false,
	true,
}bool_t;

bool_t global_sense;

typedef struct Node{
	int children;
	int ChildCount;
	bool_t sense;
	struct Node * parent;
}Node_t;

Node_t ** Node_list;

int nodes = 0;

typedef struct StaticTreeBarrier{
	int radix;
	int leaves_num;
	Node_t*root;
	int depth;
}StaticTreeBarrier_t;

#ifdef _Barrier_TEST_
#define _Thread_data_
typedef struct thread_data{
	StaticTreeBarrier_t *barrier;
	int thread_id;
	shared_obj_t *sc;
	bool_t threadSense;
        int num_cross;
}thread_data_t;
#endif

#ifndef _Thread_data_
#define _Thread_data_
typedef struct thread_data{
	StaticTreeBarrier_t *barrier;
        barrier_def_t *barrier_def;
	struct timeval *start, *end;
	int thread_id;
	//shared_obj_t *sc;
	bool_t threadSense;
        int num_cross;
}thread_data_t;
#endif

void node_init(Node_t * node, Node_t * myParent, int count){
	node->children = count;
	node->ChildCount = node->children;
	node->parent = myParent;
}

void node_update(Node_t * node){
	node->ChildCount = node->children;
}

void node_cross(Node_t* node, thread_data_t* tdata){
	tdata->threadSense = !global_sense;
	bool_t mySense = tdata->threadSense;
	//printf("I'm  %d , having %d child(dren)\n",tdata->thread_id,node->children);
	while(node->ChildCount >0 && !stop){
	/*	if(tdata->thread_id == 1){
		printf("I'm waiting %d\n",tdata->thread_id);
		} */
	}
	node->ChildCount = node->children;
	if(node->parent != NULL){
		int temp;
/*
		while(!stop){
			temp=node->parent->ChildCount;
			if(temp == CAS_U32(&node->parent->ChildCount,temp,temp-1)){
				//printf("I'm  %d , changing parent %d child(dren)\n",tdata->thread_id,node->parent->ChildCount);
				break;
			}else{
				continue;
			}
		}
*/		temp = FAD_U32(&(node->parent->ChildCount));
		while(global_sense != mySense && !stop){
			#ifdef MORE_THREADS
				sched_yield();
			#endif
		}
	}else{
		//printf("I'm  %d , PARENT\n",tdata->thread_id);
		global_sense = !global_sense;
	}
	tdata->threadSense = !mySense;
}

void build(Node_t* parent, int depth){

	if(depth == 0){
		Node_t * leaf = (Node_t *)malloc(sizeof(Node_t));
		node_init(leaf,parent,0);
		Node_list[nodes++] = leaf;
	}else{
		Node_t * branch = (Node_t *)malloc(sizeof(Node_t));
		node_init(branch,parent,0);
		Node_list[nodes++] = branch;
		int i;
		for(i = 0; i< radix && nodes<num_thread; i++){
			branch->children++;
			build(branch,depth-1);
		}
		node_update(branch);
	}
}

void StaticTreeBarrier_init(StaticTreeBarrier_t * barrier){
	Node_list = (Node_t **)malloc(num_thread*sizeof(Node_t));
	nodes = 0;
	barrier->depth = 0;
	int n = num_thread;
	while(n>=1){
		barrier->depth++;
		n = n/radix;
	}
	int total =0;
	for(n=0;n<=barrier->depth;n++){
		total=total+pow(radix,n);
	}
	if(total<num_thread){
		barrier->depth++;
	}
	//printf("Depth: %d\n", barrier->depth);
	barrier->radix = radix;
	//barrier->root = NULL;
	//node_init(barrier->root);
	build(NULL,barrier->depth);
	global_sense = false;
}

void StaticTreeBarrier_cross(StaticTreeBarrier_t * b, thread_data_t* tdata){
	int id = tdata->thread_id;
	//printf("thread %d is at barrier\n", id);
	//printf("\n\n\n\n");
	Node_t * my_node = Node_list[id];
	node_cross(my_node,tdata);
}

void StaticTreeBarrier_destroy(){
	int i;
	for(i = 0; i<num_thread;i++){
		free(Node_list[i]);
	}
	free(Node_list);
}
#endif


text:
/**
 * **************************************************************
 * Angular JS module used to show HTML editor and toolbar on a page
 * @require:
 *  AngularJS
 *  TinyMce
 *  RcmHtmlEditor
 */
angular.module(
    'rcmAdmin',
    ['rcmApi', 'rcmAdminApi', 'RcmHtmlEditor', 'angularUtils.directives.dirPagination']
)
/**
 * rcmAdminService
 */
    .factory(
    'rcmAdminService',
    [
        function () {
            return RcmAdminService;
        }
    ]
)
/**
 * rcmAdmin.rcmAdminMenuActions
 */
    .directive(
    'rcmAdminMenuActions',
    [
        '$compile',
        'rcmAdminService',
        function ($compile, rcmAdminService) {

            var thisLink = function (scope, elm, attrs) {
                scope.rcmAdminPage = rcmAdminService.getPage(
                    $compile(elm.contents())(scope)
                );
            };

            return {
                restrict: 'A',
                link: thisLink
            }
        }
    ]
)

/**
 * rcmAdmin.post
 */
    .directive(
    'rcmMenuPost',
    [
        'rcmAdminService',
        function (rcmAdminService) {

            var thisLink = function (scope, elm, attrs) {

                elm.unbind();
                elm.bind(
                    'click', null, function (e) {
                        e.preventDefault();

                        var linkHref = '';

                        if (attrs.publishUrl === undefined) {
                            linkHref = elm.find('a').attr('href');
                        } else {
                            linkHref = attrs.publishUrl;
                        }

                        jQuery('body').append('<form id="stupidPostSubmit" method="post" action="' + linkHref + '">');
                        jQuery('#stupidPostSubmit').submit();

                        /* Ajax request.  Makes publish take Twice as long, and
                         * fails silently when problems arise.  Recommended not
                         * to use, but kept here to settle any disputes.
                         */
//                        jQuery.post(elm.find('a').attr('href'), function(data) {
//                            if (data.redirect != undefined) {
//                                window.location = data.redirect;
//                            }
//                        });
                    }
                );
            };

            return {
                restrict: 'C',
                link: thisLink
            }
        }
    ]
)
/**
 * rcmAdmin.rcmAdminEditButton rcm-admin-edit-button
 */
    .directive(
    'rcmAdminEditButton',
    [
        'rcmAdminService',
        'rcmHtmlEditorService',
        function (rcmAdminService, rcmHtmlEditorService) {

            var eventsRegistered = false;

            var safeApply = function (scope, fn) {
                var phase = scope.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    if (fn && (typeof(fn) === 'function')) {
                        fn();
                    }
                } else {
                    scope.$apply(fn);
                }
            };

            var thisLink = function (scope, elm, attrs) {

                scope.loading = false;

                if (!eventsRegistered) {

                    // @todo - Sync this in the service, not here
                    rcmHtmlEditorService.eventManager.on(
                        'rcmHtmlEditorService.loading.start',
                        function (obj) {
                            rcmLoading.setLoading(
                                'rcmHtmlEditorService.loading',
                                0,
                                {statusMessage: 'Editors Loading'}
                            );
                        }
                    );

                    rcmHtmlEditorService.eventManager.on(
                        'rcmHtmlEditorService.loading.change',
                        function (obj) {
                            rcmLoading.setLoading(
                                'rcmHtmlEditorService.loading',
                                obj.amount
                            );
                        }
                    );

                    rcmHtmlEditorService.eventManager.on(
                        'rcmHtmlEditorService.loading.end',
                        function (obj) {
                            rcmLoading.setLoading(
                                'rcmHtmlEditorService.loading',
                                1
                            );
                        }
                    );

                    rcmLoading.onLoadingStart(
                        function (loadingParams) {
                            scope.loading = true;
                            safeApply(scope);
                        },
                        'rcmAdminEditButton.onLoadingStart'
                    );

                    rcmLoading.onLoadingComplete(
                        function (loadingParams) {
                            scope.loading = false;
                            safeApply(scope);
                        },
                        'rcmAdminEditButton.onLoadingComplete'
                    );

                    eventsRegistered = true;
                }

                scope.rcmAdminPage = rcmAdminService.getPage();

                var editingState = attrs.rcmAdminEditButton;

                elm.unbind();
                elm.bind(
                    'click', null, function () {

                        rcmAdminService.rcmAdminEditButtonAction(
                            editingState,
                            function () {
                                scope.$apply();
                            }
                        );
                    }
                );
            };

            return {
                restrict: 'A',
                link: thisLink
            }
        }
    ]
)
/**
 * rcmAdmin.richedit
 */
    .directive(
    'richedit',
    [
        'rcmAdminService',
        'rcmHtmlEditorInit',
        'rcmHtmlEditorDestroy',
        function (rcmAdminService, rcmHtmlEditorInit, rcmHtmlEditorDestroy) {

            return {
                compile: rcmAdminService.getHtmlEditorLink(
                    rcmHtmlEditorInit,
                    rcmHtmlEditorDestroy,
                    'richedit'
                ),
                scope: {},
                restrict: 'A',
                require: '?ngModel'
            }
        }
    ]
)
/**
 * rcmAdmin.textedit
 */
    .directive(
    'textedit',
    [
        'rcmAdminService',
        'rcmHtmlEditorInit',
        'rcmHtmlEditorDestroy',
        function (rcmAdminService, rcmHtmlEditorInit, rcmHtmlEditorDestroy) {

            return {
                compile: rcmAdminService.getHtmlEditorLink(
                    rcmHtmlEditorInit,
                    rcmHtmlEditorDestroy,
                    'textedit'
                ),
                scope: {},
                restrict: 'A',
                require: '?ngModel'
            }
        }
    ]
);

rcm.addAngularModule('rcmAdmin');


text:
package edu.hm.hafner.analysis.parser;

import java.util.regex.Matcher;

import org.apache.commons.lang3.StringUtils;

import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.Priority;
import edu.hm.hafner.analysis.RegexpDocumentParser;

/**
 * A parser for Eclipse compiler warnings.
 *
 * @author Ullrich Hafner
 */
public class EclipseParser extends RegexpDocumentParser {
    private static final long serialVersionUID = 425883472788422955L;
    private static final String ANT_ECLIPSE_WARNING_PATTERN = "\\[?(WARNING|ERROR)\\]?" +      // group 1 'type':
            // WARNING or ERROR in optional []
            "\\s*(?:in)?" +                  // optional " in"
            "\\s*(.*)" +                     // group 2 'filename'
            "(?:\\(at line\\s*(\\d+)\\)|" +  // either group 3 'lineNumber': at line dd
            ":\\[(\\d+)).*" +                // or group 4 'rowNumber': eg :[row,col] - col ignored
            "(?:\\r?\\n[^\\^\\n]*){1,3}" +   // 1 or 3 ignored lines (no column pointer) eg source excerpt
            "\\r?\\n(.*)" +                  // newline then group 5 (indent for column pointers)
            "([\\^]+).*" +                   // group 6 column pointers (^^^^^)
            "\\r?\\n(?:\\s*\\[.*\\]\\s*)?" + // newline then optional ignored text in [] (eg [javac])
            "(.*)";                          // group 7 'message'

    /**
     * Creates a new instance of {@link EclipseParser}.
     */
    public EclipseParser() {
        super("ejc", ANT_ECLIPSE_WARNING_PATTERN, true);
    }

    @Override
    protected Issue createWarning(final Matcher matcher) {
        String type = StringUtils.capitalize(matcher.group(1));
        Priority priority;
        if ("warning".equalsIgnoreCase(type)) {
            priority = Priority.NORMAL;
        }
        else {
            priority = Priority.HIGH;
        }

        int columnStart = StringUtils.defaultString(matcher.group(5)).length();
        int columnEnd = columnStart + matcher.group(6).length();

        Issue issue = issueBuilder().setFileName(matcher.group(2)).setLineStart(parseInt(getLine(matcher)))
                                    .setColumnStart(columnStart).setColumnEnd(columnEnd).setType(getId())
                                    .setCategory(StringUtils.EMPTY).setMessage(matcher.group(7)).setPriority(priority)
                                    .build();

        return issue;
    }

    private String getLine(final Matcher matcher) {
        String eclipse34 = matcher.group(3);
        String eclipse38 = matcher.group(4);

        return StringUtils.defaultIfEmpty(eclipse34, eclipse38);
    }
}


text:
package com.gemstone.gemfire.internal;

import com.gemstone.gemfire.LogWriter;
import java.io.*;
import java.util.*;
import junit.framework.*;

/**
 * Tests the functionality of the {@link SortLogFile} program.
 *
 * @author David Whitlock
 *
 * @since 3.0
 */
public class SortLogFileTest extends TestCase {

  public SortLogFileTest(String name) {
    super(name);
  }

  /**
   * Generates a "log file" whose entry timestamps are in a random
   * order.  Then it sorts the log file and asserts that the entries
   * are sorted order.
   */
  public void testRandomLog() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter pw =
      new PrintWriter(new OutputStreamWriter(baos), true);
    LogWriter logger = new RandomLogWriter(pw);

    for (int i = 0; i < 100; i++) {
      logger.info(String.valueOf(i));
    }

    pw.flush();
    pw.close();

    byte[] bytes = baos.toByteArray();

//     System.out.println("RANDOM:");
//     System.out.println(new String(bytes));

    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

    StringWriter sw = new StringWriter();
    pw = new PrintWriter(sw, true);
    SortLogFile.sortLogFile(bais, pw);

    String sorted = sw.toString();
//     System.out.println("SORTED");
//     System.out.println(sorted);

    BufferedReader br = new BufferedReader(new StringReader(sorted));
    LogFileParser parser = new LogFileParser(null, br);
    String prevTimestamp = null;
    while (parser.hasMoreEntries()) {
      LogFileParser.LogEntry entry = parser.getNextEntry();
      String timestamp = entry.getTimestamp();
      if (prevTimestamp != null) {
        assertTrue("Prev: " + prevTimestamp + ", current: " + timestamp,
                   prevTimestamp.compareTo(timestamp) <= 0);
      }
      prevTimestamp = entry.getTimestamp();
    }
  }

  ////////////////////  Inner Classes  ////////////////////

  /**
   * A LogWriter that generates random time stamps.
   */
  static class RandomLogWriter extends LocalLogWriter {

    /** Used to generate a random date */
    private Random random = new Random();

    /**
     * Creates a new RandomLogWriter that logs to the
     * given PrintWriter.
     */
    public RandomLogWriter(PrintWriter pw) {
      super(ALL_LEVEL, pw);
    }

    /**
     * Ignores date and returns the timestamp for a
     * random date.
     */
    public String formatDate(Date date) {
      long time = date.getTime() + (random.nextInt(100000) * 1000);
      date = new Date(time);
      return super.formatDate(date);
    }

  }

}


text:
import angular from 'angular';

angular
    .module('sfinapp.home.apiCheckerSrv', [

    ])
    .factory('apiCheckerSrv', apiCheckerSrv);

function apiCheckerSrv($http) {

    var factory = {
        check: check
    };

    return factory;

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

    function check() {
        return $http.get('api/test');
    }

}


text:
$(document).ready(function(){

    // add active class to 'clicked' links from sidebar
    $(".sidebar ul > li").click(function () {
       $('ul > li').removeClass('active');
       $(this).addClass('active');

    });
    //end

});


text:
require 'spec_helper'

RSpec.describe Banzai::ReferenceParser::BaseParser do
  include ReferenceParserHelpers

  let(:user) { create(:user) }
  let(:project) { create(:project, :public) }
  let(:context) { Banzai::RenderContext.new(project, user) }
  let(:parser_class) do
    Class.new(described_class) do
      self.reference_type = :foo
    end
  end

  subject do
    parser_class.new(context)
  end

  describe '.reference_type=' do
    it 'sets the reference type' do
      dummy = Class.new(described_class)
      dummy.reference_type = :foo

      expect(dummy.reference_type).to eq(:foo)
    end
  end

  describe '#project_for_node' do
    it 'returns the Project for a node' do
      document = instance_double('document', fragment?: false)
      project = instance_double('project')
      object = instance_double('object', project: project)
      node = instance_double('node', document: document)

      context.associate_document(document, object)

      expect(subject.project_for_node(node)).to eq(project)
    end
  end

  describe '#nodes_visible_to_user' do
    let(:link) { empty_html_link }

    context 'when the link has a data-project attribute' do
      before do
        link['data-project'] = project.id.to_s
      end

      it 'includes the link if can_read_reference? returns true' do
        expect(subject).to receive(:can_read_reference?).with(user, project, link).and_return(true)

        expect(subject.nodes_visible_to_user(user, [link])).to contain_exactly(link)
      end

      it 'excludes the link if can_read_reference? returns false' do
        expect(subject).to receive(:can_read_reference?).with(user, project, link).and_return(false)

        expect(subject.nodes_visible_to_user(user, [link])).to be_empty
      end
    end

    context 'when the link does not have a data-project attribute' do
      it 'returns the nodes' do
        expect(subject.nodes_visible_to_user(user, [link])).to eq([link])
      end
    end
  end

  describe '#nodes_user_can_reference' do
    it 'returns the nodes' do
      link = double(:link)

      expect(subject.nodes_user_can_reference(user, [link])).to eq([link])
    end
  end

  describe '#referenced_by' do
    context 'when references_relation is implemented' do
      it 'returns a collection of objects' do
        links = Nokogiri::HTML.fragment("")
          .children

        expect(subject).to receive(:references_relation).and_return(User)
        expect(subject.referenced_by(links)).to eq([user])
      end
    end

    context 'when references_relation is not implemented' do
      it 'raises NotImplementedError' do
        links = Nokogiri::HTML.fragment('').children

        expect { subject.referenced_by(links) }
          .to raise_error(NotImplementedError)
      end
    end
  end

  describe '#references_relation' do
    it 'raises NotImplementedError' do
      expect { subject.references_relation }.to raise_error(NotImplementedError)
    end
  end

  describe '#gather_attributes_per_project' do
    it 'returns a Hash containing attribute values per project' do
      link = Nokogiri::HTML.fragment('')
        .children[0]

      hash = subject.gather_attributes_per_project([link], 'data-foo')

      expect(hash).to be_an_instance_of(Hash)

      expect(hash[1].to_a).to eq(['2'])
    end
  end

  describe '#grouped_objects_for_nodes' do
    it 'returns a Hash grouping objects per node' do
      link = double(:link)

      expect(link).to receive(:has_attribute?)
        .with('data-user')
        .and_return(true)

      expect(link).to receive(:attr)
        .with('data-user')
        .and_return(user.id.to_s)

      nodes = [link]

      expect(subject).to receive(:unique_attribute_values)
        .with(nodes, 'data-user')
        .and_return([user.id.to_s])

      hash = subject.grouped_objects_for_nodes(nodes, User, 'data-user')

      expect(hash).to eq({ link => user })
    end

    it 'returns an empty Hash when entry does not exist in the database', :request_store do
      link = double(:link)

      expect(link).to receive(:has_attribute?)
          .with('data-user')
          .and_return(true)

      expect(link).to receive(:attr)
          .with('data-user')
          .and_return('1')

      nodes = [link]
      bad_id = user.id + 100

      expect(subject).to receive(:unique_attribute_values)
          .with(nodes, 'data-user')
          .and_return([bad_id.to_s])

      hash = subject.grouped_objects_for_nodes(nodes, User, 'data-user')

      expect(hash).to eq({})
    end
  end

  describe '#unique_attribute_values' do
    it 'returns an Array of unique values' do
      link = double(:link)

      expect(link).to receive(:has_attribute?)
        .with('data-foo')
        .twice
        .and_return(true)

      expect(link).to receive(:attr)
        .with('data-foo')
        .twice
        .and_return('1')

      nodes = [link, link]

      expect(subject.unique_attribute_values(nodes, 'data-foo')).to eq(['1'])
    end
  end

  describe '#process' do
    it 'gathers the references for every node matching the reference type' do
      dummy = Class.new(described_class) do
        self.reference_type = :test

        def gather_references(nodes)
          nodes
        end
      end

      instance = dummy.new(context)
      document_a = Nokogiri::HTML.fragment(<<-FRAG)
      one
      two
      three
      FRAG
      document_b = Nokogiri::HTML.fragment(<<-FRAG)
      four
      FRAG
      document_c = Nokogiri::HTML.fragment('')

      expect(instance.process([document_a, document_b, document_c]))
        .to contain_exactly(document_a.css('a')[1], document_b.css('a')[0])
    end
  end

  describe '#gather_references' do
    let(:nodes) { (1..10).map { |n| double(:link, id: n) } }

    let(:parser_class) do
      Class.new(described_class) do
        def nodes_user_can_reference(_user, nodes)
          nodes.select { |n| n.id.even? }
        end

        def nodes_visible_to_user(_user, nodes)
          nodes.select { |n| n.id > 5 }
        end

        def referenced_by(nodes)
          nodes.map(&:id)
        end
      end
    end

    it 'returns referenceable and visible objects, alongside nodes that are referenceable but not visible' do
      expect(subject.gather_references(nodes)).to match(
        visible: contain_exactly(6, 8, 10),
        not_visible: match_array(nodes.select { |n| n.id.even? && n.id <= 5 })
      )
    end

    it 'is always empty if the input is empty' do
      expect(subject.gather_references([])) .to match(visible: be_empty, not_visible: be_empty)
    end
  end

  describe '#can?' do
    it 'delegates the permissions check to the Ability class' do
      user = double(:user)

      expect(Ability).to receive(:allowed?)
        .with(user, :read_project, project)

      subject.can?(user, :read_project, project)
    end
  end

  describe '#find_projects_for_hash_keys' do
    it 'returns a list of Projects' do
      expect(subject.find_projects_for_hash_keys(project.id => project))
        .to eq([project])
    end
  end

  describe '#collection_objects_for_ids' do
    context 'with RequestStore disabled' do
      it 'queries the collection directly' do
        collection = User.all

        expect(collection).to receive(:where).twice.and_call_original

        2.times do
          expect(subject.collection_objects_for_ids(collection, [user.id]))
            .to eq([user])
        end
      end
    end

    context 'with RequestStore enabled', :request_store do
      before do
        cache = Hash.new { |hash, key| hash[key] = {} }

        allow(subject).to receive(:collection_cache).and_return(cache)
      end

      it 'queries the collection on the first call' do
        expect(subject.collection_objects_for_ids(User, [user.id]))
          .to eq([user])
      end

      it 'does not query previously queried objects' do
        collection = User.all

        expect(collection).to receive(:where).once.and_call_original

        2.times do
          expect(subject.collection_objects_for_ids(collection, [user.id]))
            .to eq([user])
        end
      end

      it 'casts String based IDs to Fixnums before querying objects' do
        2.times do
          expect(subject.collection_objects_for_ids(User, [user.id.to_s]))
            .to eq([user])
        end
      end

      it 'queries any additional objects after the first call' do
        other_user = create(:user)

        expect(subject.collection_objects_for_ids(User, [user.id]))
          .to eq([user])

        expect(subject.collection_objects_for_ids(User, [user.id, other_user.id]))
          .to eq([user, other_user])
      end

      it 'caches objects on a per collection class basis' do
        expect(subject.collection_objects_for_ids(User, [user.id]))
          .to eq([user])

        expect(subject.collection_objects_for_ids(Project, [project.id]))
          .to eq([project])
      end

      it 'will not overflow the stack' do
        ids = 1.upto(1_000_000).to_a

        expect { subject.collection_objects_for_ids(User, ids) }.not_to raise_error
      end
    end
  end

  describe '#collection_cache_key' do
    it 'returns the cache key for a Class' do
      expect(subject.collection_cache_key(Project)).to eq(Project)
    end

    it 'returns the cache key for an ActiveRecord::Relation' do
      expect(subject.collection_cache_key(Project.all)).to eq(Project)
    end
  end
end


text:
<?php

namespace phpDocumentor\Descriptor\Interfaces;

use phpDocumentor\Descriptor\Collection;

/**
 * Describes the public interface for the description of a namespace.
 */
interface NamespaceInterface extends ElementInterface, ContainerInterface, ChildInterface
{
    /**
     * @return Collection
     */
    public function getChildren();
}


text:
define("appkit/utils/routeProxy",
  ["exports"],
  function(__exports__) {
    "use strict";

    var routeProxy = {

        transition: null,
        route: null,

        init: function(transition, route) {
            this.transition = transition;
            this.route = route;
        },
        getTransition: function() {
            return this.transition;
        },
        getRoute: function() {
            return this.route;
        },
        send: function() {

            var args = [].slice.call(arguments);
            var controller = this.route.controller;

            if (!args[0]) {
                throw 'routeProxy: send需要提供action, arguments[0]';
            }
            else if (controller) {
                controller.send.apply(controller, args);
            }
            else {
                return false;
            }
        }

    };

    __exports__["default"] = routeProxy;
  });


text:
<?php

namespace Jaxon\Plugin;

use Jaxon\Request\Target;
use Jaxon\Response\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

interface RequestHandlerInterface
{
    /**
     * Get the target function or class and method
     *
     * @return Target|null
     */
    public function getTarget(): ?Target;

    /**
     * @param ServerRequestInterface $xRequest
     *
     * @return void
     */
    public function setTarget(ServerRequestInterface $xRequest);

    /**
     * Check if this plugin can process the current request
     *
     * Called by the <Jaxon\Plugin\RequestManager> when a request has been received to determine
     * if the request is targeted to this request plugin.
     *
     * @param ServerRequestInterface $xRequest
     *
     * @return bool
     */
    public static function canProcessRequest(ServerRequestInterface $xRequest): bool;

    /**
     * Process the current request
     *
     * Called by the <Jaxon\Plugin\RequestManager> when a request is being processed.
     * This will only occur when <Jaxon> has determined that the current request
     * is a valid (registered) jaxon enabled function via <jaxon->canProcessRequest>.
     *
     * @return ResponseInterface|null
     */
    public function processRequest(): ?ResponseInterface;
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using Microsoft.OData.Edm;

namespace System.Web.OData.Formatter.Serialization
{
    /// <summary>
    /// Represents an <see cref="IEdmEntityObject"/> backed by a CLR object with a one-to-one mapping.
    /// </summary>
    internal class TypedEdmEntityObject : TypedEdmStructuredObject, IEdmEntityObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TypedEdmEntityObject"/> class.
        /// </summary>
        /// <param name="instance">The backing CLR instance.</param>
        /// <param name="edmType">The <see cref="IEdmEntityTypeReference"/> of this object.</param>
        /// <param name="edmModel">The <see cref="IEdmModel"/>.</param>
        public TypedEdmEntityObject(object instance, IEdmEntityTypeReference edmType, IEdmModel edmModel)
            : base(instance, edmType, edmModel)
        {
        }
    }
}


text:
package org.trifort.rootbeer.generate.opencl.fields;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.trifort.rootbeer.generate.bytecode.Constants;
import org.trifort.rootbeer.generate.opencl.OpenCLClass;
import org.trifort.rootbeer.generate.opencl.OpenCLScene;

import soot.SootClass;

public class OffsetCalculator {

  private Map<SootClass, Map<OpenCLField, Integer>> m_OffsetMap;
  private Map<OpenCLField, Integer> m_CurrOffsetSubMap;
  private int m_CurrOffset;

  public OffsetCalculator(CompositeField composite) {
    m_OffsetMap = new HashMap<SootClass, Map<OpenCLField, Integer>>();
    //classes are sorted with base at index 0, most derived at index size-1
    List<SootClass> classes = composite.getClasses();
    for(int i = classes.size()-1; i >= 0; --i){
      SootClass curr_key_class = classes.get(i);
      m_CurrOffsetSubMap = new HashMap<OpenCLField, Integer>();
      m_CurrOffset = Constants.SizeGcInfo;
      for(int j = i; j >= 0; --j){
        SootClass curr_field_class = classes.get(j);
        List<OpenCLField> fields = composite.getRefFieldsByClass(curr_field_class);
        fields = trimFields(fields, curr_field_class, true);
        calculateForSet(fields);
        alignCurrOffset();
      }
      for(int j = i; j >= 0; --j){
        SootClass curr_field_class = classes.get(j);
        List<OpenCLField> fields = composite.getNonRefFieldsByClass(curr_field_class);
        fields = trimFields(fields, curr_field_class, false);
        calculateForSet(fields);
        alignCurrOffset();
      }
      m_OffsetMap.put(curr_key_class, m_CurrOffsetSubMap);
    }
  }

  private void alignCurrOffset(){
    //non_ref starts on alignment of 8
    int mod = m_CurrOffset % 8;
    if(mod != 0)
      m_CurrOffset += (8 - mod);
  }

  private void calculateForSet(List<OpenCLField> sorted){
    if(sorted.isEmpty())
      return;

    OpenCLField first = sorted.get(0);

    int prev_size = first.getSize();

    for(OpenCLField field : sorted){

      if(field.isCloned())
        continue;

      if(prev_size != field.getSize()){
        int mod = m_CurrOffset % prev_size;
        if(mod != 0)
          m_CurrOffset += (prev_size - mod);
        prev_size = field.getSize();
      }
      m_CurrOffsetSubMap.put(field, m_CurrOffset);
      m_CurrOffset += field.getSize();
    }
  }

  public int getOffset(OpenCLField field, SootClass soot_class) {
    Map<OpenCLField, Integer> offset_map = m_OffsetMap.get(soot_class);
    if(field.isCloned()){
      if(offset_map.containsKey(field.getCloneSource())){
        return offset_map.get(field.getCloneSource());
      } else {
        return -1;
      }
    } else {
      if(offset_map.containsKey(field)){
        return offset_map.get(field);
      } else {
        return -1;
      }
    }
  }

  public int getSize(SootClass soot_class) {
    int ret = Constants.SizeGcInfo;
    Map<OpenCLField, Integer> offset_map = m_OffsetMap.get(soot_class);
    OpenCLField max_field = null;
    int max_offset = Integer.MIN_VALUE;
    Iterator<OpenCLField> iter = offset_map.keySet().iterator();
    while(iter.hasNext()){
      OpenCLField field = iter.next();
      int offset = offset_map.get(field);
      if(offset > max_offset){
        max_offset = offset;
        max_field = field;
      }
    }
    if(max_field == null)
      return ret;
    ret = max_offset;
    ret += max_field.getSize();
    int mod = ret % 16;
    if(mod != 0){
      ret += (16 - mod);
    }
    return ret;
  }

  private List<OpenCLField> trimFields(List<OpenCLField> org_fields, SootClass curr_field_class, boolean ref_fields) {
    OpenCLClass ocl_class = OpenCLScene.v().getOpenCLClass(curr_field_class);
    List<OpenCLField> used_fields;
    if(ref_fields){
      used_fields = ocl_class.getInstanceRefFields();
    } else {
      used_fields = ocl_class.getInstanceNonRefFields();
    }
    List<OpenCLField> ret = new ArrayList<OpenCLField>();
    for(OpenCLField field : org_fields){
      if(listContains(used_fields, field.getName()))
        ret.add(field);
    }
    return ret;
  }

  private boolean listContains(List<OpenCLField> lst, String name){
    for(OpenCLField field : lst){
      if(field.getName().equals(name))
        return true;
    }
    return false;
  }

}


text:
//
//  Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#ifndef _RD_EMBEDDED_FRAG_H_
#define _RD_EMBEDDED_FRAG_H_

#include <RDGeneral/types.h>
#include <Geometry/Transform2D.h>
#include <Geometry/point.h>
#include "DepictUtils.h"
#include <boost/smart_ptr.hpp>

namespace RDKit {
class ROMol;
class Bond;
}

namespace RDDepict {
typedef boost::shared_array<double> DOUBLE_SMART_PTR;

//! Class that contains the data for an atoms that has alredy been embedded
class EmbeddedAtom {
 public:
  typedef enum { UNSPECIFIED = 0, CISTRANS, RING } EAtomType;

  EmbeddedAtom()
      : aid(0),
        angle(-1.0),
        nbr1(-1),
        nbr2(-1),
        CisTransNbr(-1),
        ccw(true),
        rotDir(0),
        d_density(-1.0) {
    neighs.clear();
  }

  EmbeddedAtom(unsigned int aid, const RDGeom::Point2D &pos)
      : aid(aid),
        angle(-1.0),
        nbr1(-1),
        nbr2(-1),
        CisTransNbr(-1),
        ccw(true),
        rotDir(0),
        d_density(-1.0) {
    loc = pos;
  }

  EmbeddedAtom &operator=(const EmbeddedAtom &other) {
    loc = other.loc;
    angle = other.angle;
    nbr1 = other.nbr1;
    nbr2 = other.nbr2;
    CisTransNbr = other.CisTransNbr;
    rotDir = other.rotDir;
    normal = other.normal;
    ccw = other.ccw;
    neighs = other.neighs;
    d_density = other.d_density;
    return *this;
  }

  void Transform(const RDGeom::Transform2D &trans) {
    RDGeom::Point2D temp = loc + normal;
    trans.TransformPoint(loc);
    trans.TransformPoint(temp);
    normal = temp - loc;
  }

  void Reflect(const RDGeom::Point2D &loc1, const RDGeom::Point2D &loc2) {
    RDGeom::Point2D temp = loc + normal;
    loc = reflectPoint(loc, loc1, loc2);
    temp = reflectPoint(temp, loc1, loc2);
    normal = temp - loc;
    ccw = (!ccw);
  }

  unsigned int aid;  // the id of the atom

  //! the angle that is already takes at this atom, so any new atom attaching to
  // this
  //! atom with have to fall in the available part
  double angle;

  //! the first neighbor of this atom that form the 'angle'
  int nbr1;

  //! the second neighbor of atom that from the 'angle'
  int nbr2;

  //! is this is a cis/trans atom the neighbor of this atom that is involved in
  // the
  //! cis/trans system - defaults to -1
  int CisTransNbr;

  //! which direction do we rotate this normal to add the next bond
  //! if ccw is true we rotate counter cloack wise, otherwise rotate clock wise,
  // by an angle that is
  //! <= PI/2
  bool ccw;

  //! rotation direction around this atom when adding new atoms,
  //! we determine this for the first neighbor and stick to this direction after
  // that
  //! useful only on atoms that are degree >= 4
  int rotDir;

  RDGeom::Point2D loc;  // the current location of this atom
  //! this is a normal vector to one of the bonds that added this atom
  //! it provides the side on which we want to add a new bond to this atom,
  //! this is only relevant when we are dealing with non ring atoms. We would
  // like to draw chains in
  //! a zig-zag manner
  RDGeom::Point2D normal;

  //! and these are the atom IDs of the neighbors that still need to be embedded
  RDKit::INT_VECT neighs;

  // density of the atoms around this atoms
  // - this is sum of inverse of the square of distances to other atoms from
  // this atom
  // Used in the collision removal code - initialized to -1.0
  double d_density;
};

typedef std::map<unsigned int, EmbeddedAtom> INT_EATOM_MAP;
typedef INT_EATOM_MAP::iterator INT_EATOM_MAP_I;
typedef INT_EATOM_MAP::const_iterator INT_EATOM_MAP_CI;

//! Class containing a fragment of a molecule that has already been embedded
/*
  Here is how this class is designed to be used
  - find a set of fused rings and compte the coordinates for the atoms in those
  ring
  - them grow this sytem either by adding non ring neighbors
  - or by adding other embedded fragment
  - so at the end of the process  the whole molecule end up being one these
  embedded frag objects
*/
class EmbeddedFrag {
  // REVIEW: think about moving member functions up to global level and just
  // using
  // this class as a container

 public:
  //! Default constructor
  EmbeddedFrag() : d_done(false), dp_mol(0) {
    d_eatoms.clear();
    d_attachPts.clear();
  };

  //! Intializer from a single atom id
  /*!
    A single Embedded Atom with this atom ID is added and placed at the origin
  */
  EmbeddedFrag(unsigned int aid, const RDKit::ROMol *mol);

  //! Constructor when the coordinates have been specified for a set of atoms
  /*!
     This simply initialized a set of EmbeddedAtom to have the same coordinates
     as the
     one's specified. No testing is done to verify any kind of ocrrectlness.
     Also
     this fragment is less ready (to expand and add new neighbors) than when
     using other
     constructors. This is because:
     - the user may have specified coords for only a part of the atoms in a
     fused ring systems
       in which case we need to find these atoms and merge these ring systems to
     this fragment
     - The atoms are not yet aware of their neighbor (what is left to add etc.)
     this again
       depends on  atoms properly so that new
       neighbors can be added to them
  */
  EmbeddedFrag(const RDKit::ROMol *mol,
               const RDGeom::INT_POINT2D_MAP &coordMap);

  //! Initializer from a set of fused rings
  /*!
    ARGUMENTS:
    \param mol        the molecule of interest
    \param fusedRings a vector of rings, each ring is a list of atom ids
  */
  EmbeddedFrag(const RDKit::ROMol *mol, const RDKit::VECT_INT_VECT &fusedRings);

  //! Initializer for a cis/trans system using the double bond
  /*!
    ARGUMENTS:
    \param dblBond   the double bond that is involed in the cis/trans
    configuration
  */
  explicit EmbeddedFrag(const RDKit::Bond *dblBond);

  //! Expand this embedded system by adding negihboring atoms or other embedded
  // systems
  /*!

    Note that both nratms and efrags are modified in this function
    as we start merging them with the current fragment

  */
  void expandEfrag(RDKit::INT_LIST &nratms, std::list<EmbeddedFrag> &efrags);

  //! Add a new non-ring atom to this object
  /*
    ARGUMENTS:
    \param aid     ID of the atom to be added
    \param toAid   ID of the atom that is already in this object to which this
    atom is added
  */
  void addNonRingAtom(unsigned int aid, unsigned int toAid);

  //! Merge this embedded object with another embedded fragment
  /*!

    The transformation (rotation + translation required to attached
    the passed in object will be computed and applied. The
    coordinates of the atoms in this object will remain fixed We
    will assume that there are no common atoms between the two
    fragments to start with

    ARGUMENTS:
    \param  embObj  another EmbeddedFrag object to be merged with this object
    \param  toAid   the atom in this embedded fragment to which the new object
    will be attached
    \param  nbrAid  the atom in the other fragment to attach to
  */
  void mergeNoCommon(EmbeddedFrag &embObj, unsigned int toAid,
                     unsigned int nbrAid);

  //! Merge this embedded object with another embedded fragment
  /*!

    The transformation (rotation + translation required to attached
    the passed in object will be computed and applied. The
    coordinates of the atoms in this object will remain fixed This
    already know there are a atoms in common and we will use them to
    merge things

    ARGUMENTS:
    \param embObj    another EmbeddedFrag object to be merged with this object
    \param commAtms  a vector of ids of the common atoms

  */
  void mergeWithCommon(EmbeddedFrag &embObj, RDKit::INT_VECT &commAtms);

  void mergeFragsWithComm(std::list<EmbeddedFrag> &efrags);

  //! Mark this fragment to be done for final embedding
  void markDone() { d_done = true; }

  //! If this fragment done for the final embedding
  bool isDone() { return d_done; }

  //! Get the molecule that this embedded fragmetn blongs to
  const RDKit::ROMol *getMol() const { return dp_mol; }

  //! Find the common atom ids between this fragment and a second one
  RDKit::INT_VECT findCommonAtoms(const EmbeddedFrag &efrag2);

  //! Find a neighbor to a non-ring atom among the already embedded atoms
  /*!
    ARGUMENTS:
    \param aid  the atom id of interest

    RETURNS:
    \return the id of the atom if we found a neighbor
                 -1 otherwise

    NOTE: by definition we can have only one neighbor in the embdded system.
  */
  int findNeighbor(unsigned int aid);

  //! Tranform this object to a new coordinates system
  /*!
    ARGUMENTS:
    \param trans : the transformation that need to be applied to the atoms in
    this object
  */
  void Transform(const RDGeom::Transform2D &trans);

  void Reflect(const RDGeom::Point2D &loc1, const RDGeom::Point2D &loc2);

  const INT_EATOM_MAP &GetEmbeddedAtoms() const { return d_eatoms; }

  void Translate(const RDGeom::Point2D &shift) {
    INT_EATOM_MAP_I eari;
    for (eari = d_eatoms.begin(); eari != d_eatoms.end(); eari++) {
      eari->second.loc += shift;
    }
  }

  EmbeddedAtom GetEmbeddedAtom(unsigned int aid) const {
    INT_EATOM_MAP_CI posi = d_eatoms.find(aid);
    if (posi == d_eatoms.end()) {
      PRECONDITION(0, "Embedded atom does not contain embedded atom specified");
    }
    return posi->second;
  }

  //! the number of atoms in the embedded system
  int Size() const { return d_eatoms.size(); }

  //! \brief compute a box that encloses the fragment
  void computeBox();

  //! \brief Flip atoms on one side of a bond - used in removing colissions
  /*!
    ARGUMENTS:
    \param bondId - the bond used as the mirror to flip
    \param flipEnd - flip the atoms at the end of the bond

  */
  void flipAboutBond(unsigned int bondId, bool flipEnd = true);

  void openAngles(const double *dmat, unsigned int aid1, unsigned int aid2);

  std::vector<PAIR_I_I> findCollisions(const double *dmat,
                                       bool includeBonds = 1);

  void computeDistMat(DOUBLE_SMART_PTR &dmat);

  double mimicDistMatAndDensityCostFunc(const DOUBLE_SMART_PTR *dmat,
                                        double mimicDmatWt);

  void permuteBonds(unsigned int aid, unsigned int aid1, unsigned int aid2);

  void randomSampleFlipsAndPermutations(unsigned int nBondsPerSample = 3,
                                        unsigned int nSamples = 100,
                                        int seed = 100,
                                        const DOUBLE_SMART_PTR *dmat = 0,
                                        double mimicDmatWt = 0.0,
                                        bool permuteDeg4Nodes = false);

  //! Remove collisions in a structure by flipping rotable bonds
  //! along the shortest path between two colliding atoms
  void removeCollisionsBondFlip();

  //! Remove collision by opening angles at the offending atoms
  void removeCollisionsOpenAngles();

  //! Remove collisions by shortening bonds along the shortest path between the
  // atoms
  void removeCollisionsShortenBonds();

  //! helpers funtions to

  //! \brief make list of neighbors for each atom in the embedded system that
  //!  still need to be embedded
  void setupNewNeighs();

  //! update the  unembedded neighbor atom list for a specified atom
  void updateNewNeighs(unsigned int aid);

  //! \brief Find all atoms in this embedded system that are
  //!  within a specified distant of a point
  int findNumNeigh(const RDGeom::Point2D &pt, double radius);

  inline double getBoxPx() { return d_px; }
  inline double getBoxNx() { return d_nx; }
  inline double getBoxPy() { return d_py; }
  inline double getBoxNy() { return d_ny; }

  void canonicalizeOrientation();

 private:
  double totalDensity();

  void embedFusedRings(const RDKit::VECT_INT_VECT &fusedRings);

  //! \brief Find a transform to join a ring to the current embedded frag when
  // we
  //! have only on common atom
  /*!
    So this is the state of affairs assumed here:
    - we already have some rings in the fused system embeded and the
      coordinates for the atoms
    - the coordinates for the atoms in the new ring (with the center
      of rings at the origin) are available nringCors. we want to
      translate and rotate this ring to join with the already
      embeded rings.
    - only one atom is common between this new ring and the atoms
      that are already embedded
    - so we need to compute a transform that includes a translation
      so that the common atom overlaps and the rotation to minimize
      overalp with other atoms.

    Here's what is done:
    - we bisect the remaining sweep angle at the common atom and
      attach the new ring such that the center of the new ring falls
      on this bisecting line

    NOTE: It is assumed here that the original coordinates for the
    new ring are such that the center is at the origin (this is the
    way rings come out of embedRing)
  */
  RDGeom::Transform2D computeOneAtomTrans(unsigned int commAid,
                                          const EmbeddedFrag &other);

  RDGeom::Transform2D computeTwoAtomTrans(
      unsigned int aid1, unsigned int aid2,
      const RDGeom::INT_POINT2D_MAP &nringCor);

  //! Merge a ring with already embedded atoms
  /*!
    It is assumed that the new rings has already been oriented
    correctly etc.  This function just update all the relevant data,
    like the neighbor information and the sweep angle
  */
  void mergeRing(const EmbeddedFrag &embRing, unsigned int nCommon,
                 const RDKit::INT_VECT &pinAtoms);

  //! Reflect a fragment if necessary through a line connecting two atoms
  /*!

    We want add the new fragment such that, most of its atoms fall
    on the side opoiste to where the atoms already embedded are aid1
    and aid2 give the atoms that were used to align the new ring to
    the embedded atoms and we will assume that that process has
    already taken place (i.e. transformRing has been called)

  */
  void reflectIfNecessaryDensity(EmbeddedFrag &embFrag, unsigned int aid1,
                                 unsigned int aid2);

  //! Reflect a fragment if necessary based on the cis/trans specification
  /*!

    we want to add the new fragment such that the cis/trans
    specification on bond between aid1 and aid2 is not violated. We
    will assume that aid1 and aid2 from this fragments as well as
    embFrag are already aligned to each other.

    \param embFrag   the fragment that will be reflected if necessary
    \param ctCase    which fragment if the cis/trans dbl bond
                      - 1 means embFrag is the cis/trans fragment
                      - 2 mean "this" is the cis/trans fragment
    \param aid1      first atom that forms the plane (line) of reflection
    \param aid2      seconf atom that forms the plane of reflection
  */
  void reflectIfNecessaryCisTrans(EmbeddedFrag &embFrag, unsigned int ctCase,
                                  unsigned int aid1, unsigned int aid2);

  //! Reflect a fragment if necessary based on a thrid common point
  /*!

    we want add the new fragment such that the thrid point falls on
    the same side of aid1 and aid2. We will assume that aid1 and
    aid2 from this fragments as well as embFrag are already aligned
    to each other.

  */
  void reflectIfNecessaryThirdPt(EmbeddedFrag &embFrag, unsigned int aid1,
                                 unsigned int aid2, unsigned int aid3);

  //! \brief Initialize this fragment from a ring and coordinates for its atoms
  /*!
    ARGUMENTS:
    /param ring     a vector of atom ids in the ring; it is assumed that there
    in
                    clockwise or anti-clockwise order
    /param nringMap a map of atomId to coordinate map for the atoms in the ring
  */
  void initFromRingCoords(const RDKit::INT_VECT &ring,
                          const RDGeom::INT_POINT2D_MAP &nringMap);

  //! Helper function to addNonRingAtom to a specified atoms in the fragment
  /*
    Add an atom to this embedded fragment when the fragment already
    has a atleast two previously added neighbors to 'toAid'. In this
    case we have to choose where the the new neighbor goes based on
    the angle that is already taken around the atom.

    ARGUMENTS:
    \param aid    ID of the atom to be added
    \param toAid  ID of the atom that is already in this object to which this
    atom is added
  */
  void addAtomToAtomWithAng(unsigned int aid, unsigned int toAid);

  //! Helper function to addNonRingAtom to a specified atoms in the fragment
  /*!

    Add an atom (aid) to an atom (toAid) in this embedded fragment
    when 'toAid' has one or no neighbors previously added. In this
    case where the new atom should fall is determined by the degree
    of 'toAid' and the congestion around it.

    ARGUMENTS:
    \param  aid     ID of the atom to be added
    \param  toAid   ID of the atom that is already in this object to which this
    atom is added
    \param  mol     the molecule we are dealing with
  */
  void addAtomToAtomWithNoAng(
      unsigned int aid,
      unsigned int toAid);  //, const RDKit::ROMol *mol);

  //! Helper funtion to contructor that takes predefined coordinates
  /*!

    Given an atom with more than 2 neighbors all embedded in this
    fragment this function tries to determine

    - how much of an angle if left for any new neighbors yet to be
      added
    - which atom should we rotate when we add a new neighbor and in
      which direction (clockwise or anticlockwise

    This is how it works
    - find the pair of nbrs that have the largest angle
    - this will most likely be the angle that is available - unless
      we have fused rings and we found on of the ring angle !!!! -
      in this cae we find the next best
    - find the smallest anngle that contains one of these nbrs -
      this determined which
    - way we want to rotate

    ARGUMENTS:
    \param aid        the atom id where we are centered right now
    \param doneNbrs   list of neighbors that are already embedded around aid
  */
  void computeNbrsAndAng(unsigned int aid, const RDKit::INT_VECT &doneNbrs);
  // const RDKit::ROMol *mol);

  //! are we embedded with the final (molecule) coordinates
  bool d_done;
  double d_px, d_nx, d_py, d_ny;

  //! a map that takes one from teh atom id to the embeddedatom object for that
  // atom.
  INT_EATOM_MAP d_eatoms;

  // RDKit::INT_DEQUE d_attachPts;
  RDKit::INT_LIST d_attachPts;

  // pointer to the owning molecule
  const RDKit::ROMol *dp_mol;
};
}

#endif


text:
package org.zstack.compute.cluster;

import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.MessageSafe;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.DbEntityLister;
import org.zstack.core.defer.Deferred;
import org.zstack.header.AbstractService;
import org.zstack.header.cluster.*;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.message.APICreateMessage;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.resourceconfig.ClusterResourceConfigInitializer;
import org.zstack.search.GetQuery;
import org.zstack.search.SearchQuery;
import org.zstack.tag.TagManager;
import org.zstack.utils.ObjectUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.data.FieldPrinter;
import org.zstack.utils.logging.CLogger;

import java.util.*;

public class ClusterManagerImpl extends AbstractService implements ClusterManager {
	private static final CLogger logger = Utils.getLogger(ClusterManager.class);
	private static final FieldPrinter printer = Utils.getFieldPrinter();

	@Autowired
	private CloudBus bus;
	@Autowired
	private DatabaseFacade dbf;
	@Autowired
	private PluginRegistry pluginRgty;
	@Autowired
	private DbEntityLister dl;
	@Autowired
	private TagManager tagMgr;
	@Autowired
	private ClusterResourceConfigInitializer crci;

	private Map<String, ClusterFactory> clusterFactories = Collections.synchronizedMap(new HashMap<String, ClusterFactory>());
    private static final Set<Class> allowedMessageAfterSoftDeletion = new HashSet<Class>();

    static {
        allowedMessageAfterSoftDeletion.add(ClusterDeletionMsg.class);
    }

    private void handleApiMessage(APIMessage msg) {
        if (msg instanceof APICreateClusterMsg) {
            handle((APICreateClusterMsg) msg);
        } else if (msg instanceof ClusterMessage) {
            passThrough((ClusterMessage) msg);
        }
    }

    private void passThrough(ClusterMessage msg) {
        ClusterVO vo = dbf.findByUuid(msg.getClusterUuid(), ClusterVO.class);
        if (vo == null && allowedMessageAfterSoftDeletion.contains(msg.getClass())) {
            ClusterEO eo = dbf.findByUuid(msg.getClusterUuid(), ClusterEO.class);
            vo = ObjectUtils.newAndCopy(eo, ClusterVO.class);
        }

		if (vo == null) {
			String err = String.format("Cannot find cluster: %s, it may have been deleted", msg.getClusterUuid());
			bus.replyErrorByMessageType((Message) msg, err);
			return;
		}

		ClusterFactory factory = this.getClusterFactory(ClusterType.valueOf(vo.getType()));
		Cluster cluster = factory.getCluster(vo);
		cluster.handleMessage((Message) msg);
	}

	private void doCreateCluster(CreateClusterMessage msg, ReturnValueCompletion<ClusterInventory> completion) {
		String clusterType = msg.getType();
		if (clusterType == null) {
			clusterType = BaseClusterFactory.type.toString();
		}

		ClusterFactory factory = this.getClusterFactory(ClusterType.valueOf(clusterType));
		ClusterVO vo = new ClusterVO();

		if (msg.getResourceUuid() != null) {
			vo.setUuid(msg.getResourceUuid());
		} else {
			vo.setUuid(Platform.getUuid());
		}

		vo.setArchitecture(msg.getArchitecture());
		vo.setDescription(msg.getDescription());
		vo.setHypervisorType(msg.getHypervisorType());
		vo.setManagementNodeId(Platform.getManagementServerId());
		vo.setZoneUuid(msg.getZoneUuid());
		vo.setState(ClusterState.Enabled);
		vo.setName(msg.getClusterName());
		vo = factory.createCluster(vo, msg);

		if (msg instanceof APICreateMessage) {
			tagMgr.createTagsFromAPICreateMessage((APICreateMessage)msg, vo.getUuid(), ClusterVO.class.getSimpleName());
		} else if (msg instanceof NeedReplyMessage) {
			NeedReplyMessage m = (NeedReplyMessage) msg;
			tagMgr.createTags(m.getSystemTags(), m.getUserTags(), vo.getUuid(), ClusterVO.class.getSimpleName());
		}

		ClusterInventory inv = ClusterInventory.valueOf(vo);

		crci.initClusterResourceConfigValue(inv);
		logger.debug(String.format("Created new cluster: %s", printer.print(inv)));
		completion.success(inv);
	}

	private void handle(CreateClusterMsg msg) {
		CreateClusterReply reply = new CreateClusterReply();

		doCreateCluster(msg, new ReturnValueCompletion<ClusterInventory>(msg) {
			@Override
			public void success(ClusterInventory inv) {
				reply.setInventory(inv);
				bus.reply(msg, reply);
			}

			@Override
			public void fail(ErrorCode errorCode) {
				reply.setError(errorCode);
				bus.reply(msg, reply);
			}
		});
	}

	@Deferred
	private void handle(APICreateClusterMsg msg) {
		APICreateClusterEvent evt = new APICreateClusterEvent(msg.getId());

    	doCreateCluster(msg, new ReturnValueCompletion<ClusterInventory>(msg) {
			@Override
			public void success(ClusterInventory inv) {
				evt.setInventory(inv);
				bus.publish(evt);
			}

			@Override
			public void fail(ErrorCode errorCode) {
			    evt.setError(errorCode);
			    bus.publish(evt);
			}
		});
	}

	@Override
    @MessageSafe
	public void handleMessage(Message msg) {
		if (msg instanceof APIMessage) {
			handleApiMessage((APIMessage) msg);
		} else if (msg instanceof CreateClusterMsg) {
			handle((CreateClusterMsg) msg);
		} else if (msg instanceof ClusterMessage) {
			passThrough((ClusterMessage) msg);
		} else {
			bus.dealWithUnknownMessage(msg);
		}
	}

	@Override
	public String getId() {
		return bus.makeLocalServiceId(ClusterConstant.SERVICE_ID);
	}

    private void populateClusterFactories() {
        for (ClusterFactory ext : pluginRgty.getExtensionList(ClusterFactory.class)) {
            ClusterFactory old = clusterFactories.get(ext.getType().toString());
            if (old != null) {
                throw new CloudRuntimeException(String.format("duplicate ClusterFactory[%s, %s] for type[%s]",
                        old.getClass().getName(), ext.getClass().getName(), ext.getType()));
            }
            clusterFactories.put(ext.getType().toString(), ext);
        }
    }

	@Override
	public boolean start() {
	    populateClusterFactories();
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

    private ClusterFactory getClusterFactory(ClusterType type) {
        ClusterFactory factory = clusterFactories.get(type.toString());
        if (factory == null) {
            throw new CloudRuntimeException(String.format("No ClusterFactory of type[%s] found", type));
        }
        return factory;
    }
}


text:
# ![Actionware](assets/logo.png)

[![Build Status](https://travis-ci.org/wellguimaraes/actionware.svg?branch=master)](https://travis-ci.org/wellguimaraes/actionware)

[Redux](http://redux.js.org/) with less boilerplate, actions statuses and controlled side-effects in a single shot.

- no more **action creators** and **action types**, just **actions¹** and **reducers**
- **actions** dispatch their result automatically
- **error status** for every action with no extra code
- **busy status** for every async action (yep, no extra code!)
- **cancellable** actions

<small>**¹** With Actionware, **actions** have a different meaning: they're just functions which execution generate events.
See [usage](#usage) section to better understand.</small>

###### Extra power
Wanna have state selectors/getters in a decent way? Use it combined with **[Stateware](https://github.com/wellguimaraes/stateware)** lib.

## Setup

#### Install it
- Yarn: `yarn add actionware`
- NPM: `npm i actionware --save`

#### After creating your Redux store, let Actionware know your store instance. Optionally you
can define custom action types prefix and suffixes:
```js
import * as actionware from 'actionware';

actionware.setup({
  store,
  defaultPrefix, // default: 'actionware:'
  errorSuffix,   // default: ':error'
  cancelSuffix,  // default: ':cancel'
  busySuffix     // default: ':busy'
});
```

#### Add actionware reducer to your root reducer:
To make Redux store react to **busy** and **error** status changes,
make sure you add the Actionware reducer into your root reducer.
```js
import { combineReducers } from 'redux';
import { actionwareReducer } from 'actionware';

const rootReducer = combineReducers({
  actionware: actionwareReducer,
  // your reducers
});
```

## Usage

#### Simple actions
```js
export function incrementCounter() { }
```

#### Async actions
Whatever you return will be the action payload

```js
// Note that the store is always the last arg
export async function loadUsers(arg1, arg2, argN, store) {
  const response = await fetch('/my/api/users');
  return response.json();
}
```

#### Invoke any action
Use `call` to invoke an action and let Actionware handle
the execution lifecycle (managing error and busy statuses, notifying listeners, etc).
```js
import { call } from 'actionware';

call(loadUsers, arg1, arg2, argN);
```

#### Cancel an action execution
```js
import { call } from 'actionware';

const actionCall = call(loadUsers, arg1, arg2, argN);

actionCall.cancel()
```

To cancel inner calls or other async executions, use `setExtra` inside an async action
to keep information needed and use them on a cancellation listener:
```js
import { call, onCancel} from 'actionware';
import api from './path/to/api';

// Don't use arrow functions here,
// otherwise a context value can't be set
export async function someAction() {
  const apiCall = api.get('/some/endpoint')
  const anotherActionCall = call(anotherAction, 'someParam')

  this.setExtra({ apiCall })
  this.setExtra({ anotherActionCall }) // you can call it multiple times

  const apiResponse = await apiCall
  const anotherResponse = await anotherActionCall

  // ...

  return apiResponse.data
}

export async function anotherAction() {
  // ...
}

onCancel(someAction, ({ extras }) => {
  // Check if the action execution is still cancellable
  if (extras.anotherActionCall.canBeCancelled)
    extras.anotherActionCall.cancel()

  // Cancel the api call...
})
```

#### Clear action error
```js
import { clearError } from 'actionware'

export async function someAction() {
  // ...
}

clearError(someAction)
```

#### Reducers:
```js
import { createReducer } from 'actionware';
import { loadUsers, persistUser, incrementCounter } from 'path/to/actions';

const initialState = { users: [], count: 0 };

export default createReducer(initialState)
  .on(loadUsers,
    (state, users) => ({ ...state, users }))

  .on(incrementCounter,
    (state) => ({ ...state, counter: state.counter + 1 }))

  // Bind legacy action types
  .on('OLD_ACTION_TYPE',
    (state, payload) => { /* return new state */ })

  // Bind multiple actions to the same handler
  .on(
    someAction,
    anotherAction,
    (state, payload) => { /* return new state */ })

  // Actionware handles errors, cancellation and 'before' events,
  // but if you need to do something else

  .onError(persistUser,
    (state, error, ...args) => { /* return new state */ })

  .onCancel(loadUsers,
    (state, extras, ...args) => { /* return new state */ })

  .before(loadUsers,
    (state, ...args) => { /* return new state */ });
```

#### Busy and failure statuses for all your actions:
```js
import { getError, isBusy } from 'actionware';
import { loadUsers } from 'path/to/userActions';

// Whenever needed...
isBusy(loadUsers);
getError(loadUsers);
```

#### Use listeners to manage side effects:
Note that busy listeners are called when busy status changes.
```js
import { onSuccess, onError, onCancel, before, beforeAll } from 'actionware';
import { createUser } from 'path/to/actions';

// global success listener
onSuccess(({ action, args, payload, store }) => eventTracker.register(action.name));

// per action success listener
onSuccess(createUser, ({ args, payload, store }) => history.push(`/users/${user.id}`));

// error listeners
onError(({ action, args, error }) => { /* ... */ });
onError(createUser, ({ args, error }) => { /* ... */ });

// cancellation listeners
onCancel(({ action, args, extras }) => { /* ... */ });
onCancel(createUser, ({ args, extras }) => { /* ... */ });

// before listeners
// NOTE: 'beforeAll' is just an alias for 'before'
beforeAll(({ action, args, store}) => { /* ... */ });
before(createUser, ({ args, store }) => { /* ... */ });
```

#### Interaction-dependent flows
When you have "complex" flows that depend on some interaction to start or continue,
you can use `next` to wait for some action completion in this fashion:
```js
import { call, next } from 'actionware';
import { login, showTip, acknowledgeTip } from 'path/to/actions';

export async function appEducationFlow() {
  // Wait for the next successful login
  await next(login);

  call(showTip, 'headerButtons');
  await next(acknowledgeTip);

  history.redirect('/some/route');

  call(showTip, 'sideMenu');
  await next(acknowledgeTip);
}

// At some point, start the flow
appEducationFlow();
```

## Usage with React

#### Inject actions and status into components as props
By using `withActions` to wrap a component, actions are injected into it as props
and can be invoked without using `call`.
```js
import * as React from 'react';
import { connect } from 'react-redux';
import { withActions, isBusy, getError } from 'actionware';
import { loadUsers } from 'path/to/actions';

const actions = { loadUsers };

const mapStateToProps = ({ company }) => ({
  users   : company.users,
  loading : isBusy(loadUsers),
  error   : getError(loadUsers)
});

@connect(mapStateToProps)
@withActions(actions)
class MyConnectedComponent extends Component {
  componentDidMount() {
    this.props.loadUsers();
  }

  render() {
    const { loading, error } = this.props;

    if (loading) return (<div>Loading...</div>);
    if (error) return (<div>Failed to load users...</div>);

    return (
      <div>
        { users.map(it => <User key={it.id} {...it} />) }
      </div>
    );
  }
}

export default MyConnectedComponent
```

#### Without injecting actions as props
In case you prefer not injecting actions as props into your component, you can use `createActions` this way:
```js
import { createActions } from 'actionware'

const actions = createActions('optionalPrefix:', {
  someAction,
  anotherAction
})

const MyComponent = () => (
  <div>
    <button onClick={ actions.someAction }></button>
  </div>
)

```

## Testing

#### Mock `call` and `next` functions
While testing, you're able to replace the `call` and `next` functions by custom
spy/stub to simplify tests.
```js
import { mockCallWith, mockNextWith } from 'actionware';

const callSpy = sinon.spy();
const nextStub = sinon.stub().returns(Promise.resolve());

mockCallWith(callSpy);
mockNextWith(nextStub);

// Get back to default behavior
mockCallWith(null);
mockNextWith(null);
```

#### Reducers
For testing reducers, you can do the following:

```js
import { successType } from 'actionware';
import { loadUsers } from 'path/to/userActions';
import usersReducer from 'path/to/usersReducer';

describe('usersReducer', () => {
  describe('on loadUsers', () => {
    it('should replace the "users" array with the loaded users', () => {
      const currentState = { users: [ ] };
      const loadedUsers = [ 'John Doe', 'Joane Doe', 'Steve Gates' ];

      // Call reducer with currentState and a regular Redux action
      const newState = usersReducer(
        currentState,
        { type: successType(loadUsers), payload: loadedUsers }
      );

      expect(newState.items).to.equals(loadedUsers);
    });
  });
});
```

## API

#### Setup
- **setup**({ store, defaultPrefix?, errorSuffix?, busySuffix?, cancelSuffix? }): void

#### Most used
- **withActions**(actions: object): Function(wrappedComponent: Component)
- **createActions**(actions: object): object
- **isBusy**(action: Function): bool
- **getError**(action: Function): object
- **clearError**(action: Function): void
- **call**(action: Function, ...args)
- **next**(action: Function)
- **createReducer**(initialState: object, handlers: []): Function

#### Listeners

###### Global
- **onSuccess**(listener: ({ action, payload, args, store }) => void)
- **onError**(listener: ({ action, error, args, store }) => void)
- **beforeAll**(listener: ({ action, args, store}) => void)

###### Per action
- **onSuccess**(action: Function, listener: ({ payload, args, store }) => void)
- **onError**(action: Function, listener: ({ error, args, store }) => void)
- **before**(action: Function, listener: ({ args, store }) => void)

#### Test helpers
- **mockCallWith**(fakeCall: Function)
- **mockNextWith**(fakeNext: Function)
- **successType**(action: Function)
- **errorType**(action: Function)
- **busyType**(action: Function)

## License
[MIT](LICENSE) © Wellington Guimaraes