text:
#include "stdafx.h"
#include "keyboard_shortcuts.h"
#include "key_mapper_fake.h"

#ifdef UNIT_TEST

#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE( KeyboardShortcutsLoadTest )

	using namespace shortcuts ;

	BOOST_AUTO_TEST_CASE(test_load_simple)
	{
		KeyMapperFake mapper ;
		shortcuts::KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		string text = "<shortcuts>"
			"<shortcut>"
			"<type>CTRL</type>"
			"<first>k</first>"
			"<second />"
			"<command>GetAndNext</command>"
			"</shortcut>"
			"</shortcuts>" ;
		keyboard_shortcuts.load(text) ;
		BOOST_CHECK_EQUAL(1u, keyboard_shortcuts.m_ctrl_shortcuts.size()) ;
		KeyboardShortcuts::shortcut_map_ptr cut = keyboard_shortcuts.m_ctrl_shortcuts[L'K'] ;
		shortcut_ptr keyboard_shortcut = (*cut)[0] ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_type, shortcuts::SHORTCUT_CTRL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_firstkey, L'K') ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_secondkey, 0) ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_command, "GetAndNext") ;
	}
	BOOST_AUTO_TEST_CASE(test_load_twice)
	{
		KeyMapperFake mapper ;
		shortcuts::KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		string text = "<shortcuts>"
			"<shortcut>"
			"<type>CTRL</type>"
			"<first>k</first>"
			"<second />"
			"<command>GetAndNext</command>"
			"</shortcut>"
			"</shortcuts>" ;
		keyboard_shortcuts.load(text) ;
		text = "<shortcuts>"
			"<shortcut>"
			"<type>ALT</type>"
			"<first>k</first>"
			"<second />"
			"<command>DoSomeFoo</command>"
			"</shortcut>"
			"</shortcuts>" ;
		keyboard_shortcuts.load(text) ;
		BOOST_CHECK_EQUAL(0u, keyboard_shortcuts.m_ctrl_shortcuts.size()) ;
		BOOST_CHECK_EQUAL(1u, keyboard_shortcuts.m_alt_shortcuts.size()) ;
		KeyboardShortcuts::shortcut_map_ptr cut = keyboard_shortcuts.m_alt_shortcuts[L'K'] ;
		shortcut_ptr keyboard_shortcut = (*cut)[0] ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_type, shortcuts::SHORTCUT_ALT) ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_firstkey, L'K') ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_secondkey, 0) ;
	}
	BOOST_AUTO_TEST_CASE(test_load_alt)
	{
		KeyMapperFake mapper ;
		shortcuts::KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		string text = "<shortcuts>"
			"<shortcut>"
			"<type>alt</type>"
			"<first>k</first>"
			"<second />"
			"<command>GetAndNext</command>"
			"</shortcut>"
			"</shortcuts>";
		keyboard_shortcuts.load(text) ;
		BOOST_CHECK_EQUAL(1u, keyboard_shortcuts.m_alt_shortcuts.size()) ;
		KeyboardShortcuts::shortcut_map_ptr cut = keyboard_shortcuts.m_alt_shortcuts[L'K'] ;
		shortcut_ptr keyboard_shortcut = (*cut)[0] ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_type, shortcuts::SHORTCUT_ALT) ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_firstkey, L'K') ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_secondkey, 0) ;
	}
	BOOST_AUTO_TEST_CASE(test_load_ctrl_alt)
	{
		KeyMapperFake mapper ;
		shortcuts::KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		string text = "<shortcuts>"
			"<shortcut>"
			"<type>CTRL+ALT</type>"
			"<first>k</first>"
			"<second />"
			"<command>GetAndNext</command>"
			"</shortcut>"
			"</shortcuts>" ;
		keyboard_shortcuts.load(text) ;
		BOOST_CHECK_EQUAL(1u, keyboard_shortcuts.m_ctrl_alt_shortcuts.size()) ;
		KeyboardShortcuts::shortcut_map_ptr cut = keyboard_shortcuts.m_ctrl_alt_shortcuts[L'K'] ;
		shortcut_ptr keyboard_shortcut = (*cut)[0] ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_type, shortcuts::SHORTCUT_CTRL_ALT) ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_firstkey, L'K') ;
		BOOST_CHECK_EQUAL(keyboard_shortcut->m_secondkey, 0) ;
	}

	BOOST_AUTO_TEST_CASE(test_load_two)
	{
		KeyMapperFake mapper ;
		shortcuts::KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		string text = "<?xml version=\"1.0\"?>"
			"<shortcuts>"
			"<shortcut>"
			"<type>CTRL</type>"
			"<first>k</first>"
			"<second />"
			"<command>GetAndNext</command>"
			"</shortcut>"
			"<shortcut>"
			"<type>CTRL</type>"
			"<first>p</first>"
			"<second />"
			"<command>SetAndNext</command>"
			"</shortcut>"
			"</shortcuts>" ;
		keyboard_shortcuts.load(text) ;
		BOOST_CHECK_EQUAL(2u, keyboard_shortcuts.m_ctrl_shortcuts.size()) ;
		KeyboardShortcuts::shortcut_map_ptr cut = keyboard_shortcuts.m_ctrl_shortcuts[L'K'] ;
		BOOST_CHECK_EQUAL((*cut)[0]->m_firstkey, L'K') ;
		cut = keyboard_shortcuts.m_ctrl_shortcuts[L'P'] ;
		BOOST_CHECK_EQUAL((*cut)[0]->m_firstkey, L'P') ;
	}

	BOOST_AUTO_TEST_CASE(test_load_secondkey)
	{
		KeyMapperFake mapper ;
		shortcuts::KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		string text = "<shortcuts>"
			"<shortcut>"
			"<type>CTRL</type>"
			"<first>k</first>"
			"<second>m</second>"
			"<command>GetAndNext</command>"
			"</shortcut>"
			"</shortcuts>" ;
		keyboard_shortcuts.load(text) ;
		BOOST_CHECK_EQUAL(1u, keyboard_shortcuts.m_ctrl_shortcuts.size()) ;
		KeyboardShortcuts::shortcut_map_ptr cut = keyboard_shortcuts.m_ctrl_shortcuts[L'K'] ;
		BOOST_CHECK_EQUAL((*cut)[L'M']->m_type, shortcuts::SHORTCUT_CTRL) ;
		BOOST_CHECK_EQUAL((*cut)[L'M']->m_firstkey, L'K') ;
		BOOST_CHECK_EQUAL((*cut)[L'M']->m_secondkey, L'M') ;
	}
BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( KeyboardShortcutsMapperTest )

	using namespace shortcuts ;

	BOOST_AUTO_TEST_CASE(test_ctrl_m)
	{
		KeyMapperFake mapper ;
		KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		keyboard_shortcuts.add_shortcut(shortcut_ptr(new KeyboardShortcut(SHORTCUT_CTRL, L'M', 0, "FooBar"))) ;

		keyboard_shortcuts.receive_keypress(true, false, L'M') ;

		BOOST_CHECK_EQUAL(1u, mapper.m_sensing_variable.size());
		BOOST_CHECK_EQUAL("FooBar", mapper.m_sensing_variable[0]);
	}
	BOOST_AUTO_TEST_CASE(test_toggle)
	{
		KeyMapperFake mapper ;
		KeyboardShortcuts keyboard_shortcuts(&mapper) ;

		keyboard_shortcuts.add_shortcut(shortcut_ptr(new KeyboardShortcut(SHORTCUT_CTRL, L'M', 0, "FooBar"))) ;
		keyboard_shortcuts.add_shortcut(shortcut_ptr(new KeyboardShortcut(SHORTCUT_CTRL, VK_F1, 0, "ToggleShortcuts"))) ;

		BOOST_CHECK(keyboard_shortcuts.receive_keypress(true, false, VK_F1)) ;
		BOOST_CHECK(! keyboard_shortcuts.receive_keypress(true, false, L'M')) ;

		BOOST_CHECK_EQUAL(false, keyboard_shortcuts.m_shortcuts_enabled);
		BOOST_CHECK_EQUAL(0u, mapper.m_sensing_variable.size());
	}
	BOOST_AUTO_TEST_CASE(test_toggle_back)
	{
		KeyMapperFake mapper ;
		KeyboardShortcuts keyboard_shortcuts(&mapper) ;

		keyboard_shortcuts.add_shortcut(shortcut_ptr(new KeyboardShortcut(SHORTCUT_CTRL, L'M', 0, "FooBar"))) ;
		keyboard_shortcuts.add_shortcut(shortcut_ptr(new KeyboardShortcut(SHORTCUT_CTRL, VK_F1, 0, "ToggleShortcuts"))) ;

		BOOST_CHECK(keyboard_shortcuts.receive_keypress(true, false, VK_F1)) ;
		BOOST_CHECK(keyboard_shortcuts.receive_keypress(true, false, VK_F1)) ;
		BOOST_CHECK(keyboard_shortcuts.receive_keypress(true, false, L'M')) ;

		BOOST_CHECK_EQUAL(true, keyboard_shortcuts.m_shortcuts_enabled);
		BOOST_CHECK_EQUAL(1u, mapper.m_sensing_variable.size());
		BOOST_CHECK_EQUAL("FooBar", mapper.m_sensing_variable[0]);
	}
	BOOST_AUTO_TEST_CASE(test_ctrl_m_missed)
	{
		KeyMapperFake mapper ;
		KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		keyboard_shortcuts.add_shortcut(shortcut_ptr(new KeyboardShortcut(SHORTCUT_CTRL, L'K', 0, "FooBar"))) ;

		BOOST_CHECK(! keyboard_shortcuts.receive_keypress(true, false, L'M')) ;

		BOOST_CHECK_EQUAL(0u, mapper.m_sensing_variable.size());
	}

	BOOST_AUTO_TEST_CASE(test_second_key_first_hit)
	{
		KeyMapperFake mapper ;
		KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		shortcut_ptr cut(new KeyboardShortcut(SHORTCUT_CTRL, L'M', L'X', "FooBar")) ;
		keyboard_shortcuts.add_shortcut(cut) ;

		BOOST_CHECK(keyboard_shortcuts.receive_keypress(true, false, L'M')) ;

		BOOST_CHECK_EQUAL(0u, mapper.m_sensing_variable.size());
		BOOST_CHECK_EQUAL(L'M', keyboard_shortcuts.m_second_key);
	}
	BOOST_AUTO_TEST_CASE(test_second_key_second_hit)
	{
		KeyMapperFake mapper ;
		KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		keyboard_shortcuts.add_shortcut(shortcut_ptr(new KeyboardShortcut(SHORTCUT_CTRL, L'M', L'X', "FooBar"))) ;

		BOOST_CHECK(keyboard_shortcuts.receive_keypress(true, false, L'M')) ;
		BOOST_CHECK(keyboard_shortcuts.receive_keypress(true, false, L'X')) ;

		BOOST_CHECK_EQUAL("FooBar", mapper.m_sensing_variable[0]);
		BOOST_CHECK_EQUAL(1u, mapper.m_sensing_variable.size());
		BOOST_CHECK_EQUAL(0, keyboard_shortcuts.m_second_key);
	}
	BOOST_AUTO_TEST_CASE(test_second_key_second_miss)
	{
		KeyMapperFake mapper ;
		KeyboardShortcuts keyboard_shortcuts(&mapper) ;
		shortcut_ptr cut(new KeyboardShortcut(SHORTCUT_CTRL, L'M', L'X', "FooBar")) ;
		keyboard_shortcuts.add_shortcut(cut) ;

		keyboard_shortcuts.receive_keypress(true, false, L'M') ;
		keyboard_shortcuts.receive_keypress(false, false, L'K') ;

		BOOST_CHECK_EQUAL(0u, mapper.m_sensing_variable.size());
		BOOST_CHECK_EQUAL(0, keyboard_shortcuts.m_second_key);
	}
BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( KeyboardShortcutTest )

	BOOST_AUTO_TEST_CASE(test_default)
	{
		string command("GetAndNext") ;
		shortcuts::KeyboardShortcut shortcut(shortcuts::SHORTCUT_CTRL, L'K', 0, command) ;
		BOOST_CHECK_EQUAL(shortcut.m_type, shortcuts::SHORTCUT_CTRL) ;
		BOOST_CHECK_EQUAL(shortcut.m_firstkey, L'K') ;
		BOOST_CHECK_EQUAL(shortcut.m_secondkey, 0) ;
		BOOST_CHECK_EQUAL(shortcut.m_command, command) ;
	}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( test_get_shortcut_key )

	BOOST_AUTO_TEST_CASE(test_a)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_key("a"), L'A') ;
	}
	BOOST_AUTO_TEST_CASE(test_A)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_key("A"), L'A') ;
	}
	BOOST_AUTO_TEST_CASE(test_1)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_key("1"), L'1') ;
	}
	BOOST_AUTO_TEST_CASE(test_vk_right)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_key("RIGHT"), VK_RIGHT) ;
	}
	BOOST_AUTO_TEST_CASE(test_vk_delete)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_key("delete"), VK_DELETE) ;
	}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( test_get_shortcut_type )

	BOOST_AUTO_TEST_CASE(test_ctrl)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_shortcut_type("ctrl"), shortcuts::SHORTCUT_CTRL) ;
	}
	BOOST_AUTO_TEST_CASE(test_alt)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_shortcut_type("alt"), shortcuts::SHORTCUT_ALT) ;
	}
	BOOST_AUTO_TEST_CASE(test_ctrl_alt)
	{
		shortcuts::KeyboardShortcuts keyboard_shortcuts(NULL) ;
		BOOST_CHECK_EQUAL(keyboard_shortcuts.get_shortcut_type("ctrl+alt"), shortcuts::SHORTCUT_CTRL_ALT) ;
	}

BOOST_AUTO_TEST_SUITE_END()

#endif // #ifdef _DEBUG

max_stars_repo_name: ultimatezen/felix

max_issues_repo_name: ultimatezen/felix

max_forks_repo_name: ultimatezen/felix


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.

// Use, modification and distribution is subject to 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)
//
// Multipolygon DP simplification example from the mailing list discussion
// about the DP algorithm issue:
// http://lists.osgeo.org/pipermail/ggl/2011-September/001533.html

#include <boost/geometry.hpp>
#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
using namespace boost::geometry;

int main()
{
  typedef model::d2::point_xy<double> point_xy;

  point_xy p1(0.0, 0.0);
  point_xy p2(5.0, 0.0);

  // 1) This is direct call to Pythagoras algo
  typedef strategy::distance::pythagoras<point_xy, point_xy, double> strategy1_type;
  strategy1_type strategy1;
  strategy1_type ::calculation_type d1 = strategy1.apply(p1, p2);

  // 2) This is what is effectively called by simplify
  typedef strategy::distance::comparable::pythagoras<point_xy, point_xy, double> strategy2_type;
  strategy2_type strategy2;
  strategy2_type::calculation_type d2 = strategy2.apply(p1, p2);

  return 0;
}

ext: cpp

max_forks_repo_name: olegshnitko/libboost


text:
/* Copyright 2008 (C) Nicira, Inc.
 *
 * This file is part of NOX.
 *
 * NOX is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NOX is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NOX.  If not, see <http://www.gnu.org/licenses/>.
 */
#ifndef  RULE_HH
#define  RULE_HH

#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>

namespace vigil {

template<class Expr, typename Action>
class Cnode;

template<class Expr, typename Action>
class Rule {

public:
    friend class Cnode<Expr, Action>;

    typedef Rule<Expr, Action>* Rule_ptr;

    static bool list_compare(Rule_ptr& rule1, Rule_ptr& rule2)
    {
        return rule1->priority < rule2->priority;
    }

    Rule(uint32_t id_, uint32_t priority_,
         const Expr& expr_, const Action& action_)
        : id(id_), priority(priority_), expr(expr_), action(action_), node(NULL) { }

    Rule(const Rule& r)
        : id(r.id), priority(r.priority), expr(r.expr),
          action(r.action), node(NULL) { }

    ~Rule() { }

    Cnode<Expr, Action> *get_node() const { return node; }

    const uint32_t id;
    uint32_t priority;
    const Expr expr;
    const Action action;

private:
    Cnode<Expr, Action> *node;

    Rule();
    Rule& operator=(const Rule&);
};

} // namespace vigil

#endif

ext: hh

max_stars_repo_name: ayjazz/OESS

max_issues_repo_name: ayjazz/OESS

max_forks_repo_name: ayjazz/OESS


text:
/*!
 * @file
 * Forward declares the @ref Ring typeclass.
 *
 *
 * @copyright Louis Dionne 2014
 * Distributed under the Boost Software License, Version 1.0.
 *         (See accompanying file LICENSE.md or copy at
 *             http://www.boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_MPL11_FWD_RING_HPP
#define BOOST_MPL11_FWD_RING_HPP

#include <boost/mpl11/fwd/bool.hpp>

namespace boost { namespace mpl11 {
    /*!
     * @ingroup typeclasses
     * @defgroup Ring Ring
     *
     * The `Ring` typeclass is used for `Group`s that also form a `Monoid`
     * under a second binary operation that distributes over the first.
     *
     * Instances of `Ring` must satisfy the following laws:
     *
        @code
            mult a (mult b c) == mult (mult a b) c

            mult one a == a
            mult a one == a

            mult a (plus b c) == plus (mult a b) (mult a c)
        @endcode
     *
     *
     * ### Refines
     * `Group`
     *
     * ### Methods
     * `mult` and `one`
     *
     * ### Minimal complete definition
     * All the methods.
     *
     * @{
     */
    template <typename Left, typename Right = Left, typename = true_>
    struct Ring;

    /*!
     * `Ring` operation.
     *
     * `mult` can be invoked with more than two arguments. Specifically,
     * `mult<x1, x2, xn...>` is equivalent to `mult<mult<x1, x2>, xn...>`.
     */
    template <typename x1, typename x2, typename ...xn>
    struct mult;

    //! Multiplicative identity for the given `Datatype`.
    template <typename Datatype>
    struct one;
    //! @}
}} // end namespace boost::mpl11

#endif // !BOOST_MPL11_FWD_RING_HPP

ext: hpp


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma once
#include <fc/io/raw.hpp>

#include <eos/chain/transaction.hpp>
#include <fc/uint128.hpp>

#include <boost/multi_index/mem_fun.hpp>

#include "multi_index_includes.hpp"

namespace eosio { namespace chain {
   using boost::multi_index_container;
   using namespace boost::multi_index;
   /**
    * The purpose of this object is to store transactions generated by processing the
    * transactions included in the chain.  These transactions should be treated like
    * authentic/valid SignedTransactions for the purposes of scheduling transactions
    * in to new blocks
    */
   class generated_transaction_object : public chainbase::object<generated_transaction_object_type, generated_transaction_object>
   {
         OBJECT_CTOR(generated_transaction_object)

         enum status_type {
            PENDING = 0,
            PROCESSED
         };

         id_type                       id;
         generated_transaction          trx;
         status_type                   status;

         time_point_sec get_expiration()const { return trx.expiration; }
         generated_transaction_id_type get_id() const { return trx.id; }

         struct by_trx_id;
         struct by_expiration;
         struct by_status;
   };

   using generated_transaction_multi_index = chainbase::shared_multi_index_container<
      generated_transaction_object,
      indexed_by<
         ordered_unique<tag<by_id>, BOOST_MULTI_INDEX_MEMBER(generated_transaction_object, generated_transaction_object::id_type, id)>,
         ordered_unique<tag<generated_transaction_object::by_trx_id>, const_mem_fun<generated_transaction_object, generated_transaction_id_type, &generated_transaction_object::get_id>>,
         ordered_non_unique<tag<generated_transaction_object::by_expiration>, const_mem_fun<generated_transaction_object, time_point_sec, &generated_transaction_object::get_expiration>>,
         ordered_non_unique<tag<generated_transaction_object::by_status>, BOOST_MULTI_INDEX_MEMBER(generated_transaction_object, generated_transaction_object::status_type, status)>
      >
   >;

   typedef chainbase::generic_index<generated_transaction_multi_index> generated_transaction_index;
} }

CHAINBASE_SET_INDEX_TYPE(eosio::chain::generated_transaction_object, eosio::chain::generated_transaction_multi_index)

FC_REFLECT( eosio::chain::generated_transaction_object, (trx) )

max_stars_repo_name: brendankirby/eos


text:
#include "InstanceTracker.h"

#include <seer/Log.h>
#include <boost/filesystem.hpp>
#include <assert.h>
#include <unistd.h>

namespace seer {

InstanceTracker::InstanceTracker(std::string socketName) {
    LOGSEER_SOCKET_INIT();
    socketName = (boost::filesystem::temp_directory_path() / socketName).string();

    _socket = socket(AF_UNIX, SOCK_STREAM, 0);
    if (_socket == LOGSEER_INVALID_SOCKET) {
        log_infof("%s: failed to create AF_UNIX socket, error %d", __func__, LOGSEER_ERRNO);
        return;
    }

    sockaddr_un addr{};
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socketName.c_str(), sizeof(addr.sun_path) - 1);

    if (!connect(_socket, reinterpret_cast<sockaddr*>(&addr), sizeof addr)) {
        log_infof("%s: connected to socket %s", __func__, socketName);
        _connected = true;
        return;
    }

#if __MINGW32__
    LOGSEER_CLOSE_SOCKET(_socket);
    _socket = socket(AF_UNIX, SOCK_STREAM, 0);
    if (_socket == LOGSEER_INVALID_SOCKET) {
        log_infof("%s: failed to create AF_UNIX socket after failed connect(), error %d", __func__, LOGSEER_ERRNO);
        return;
    }
#endif

    LOGSEER_UNLINK(socketName.c_str());
    auto ret = bind(_socket, reinterpret_cast<sockaddr*>(&addr), sizeof addr);
    if (ret == -1) {
        log_infof("%s: failed to bind to socket %s, error %d", __func__, socketName, LOGSEER_ERRNO);
        stop();
        return;
    }

    ret = listen(_socket, 20);
    if (ret == -1) {
        log_infof("%s: failed to listen on socket %s", __func__, socketName);
        stop();
        return;
    }

    log_infof("%s: listening on socket %s", __func__, socketName);

    _thread = std::thread([this] {
        for (;;) {
            auto data = accept(_socket, NULL, NULL);
            if (data == LOGSEER_INVALID_SOCKET) {
                _queue.enqueue({});
                break;
            }

            std::string message;

            for (;;) {
                char ch = 0;
                auto ret = LOGSEER_SOCKET_READ(data, &ch, 1);
                if (ret == 0)
                    break;

                if (ch == '\n')
                    break;

                message += ch;
            }

            close(data);
            _queue.enqueue(message);
        }
    });
}

bool InstanceTracker::connected() const {
    return _connected;
}

void InstanceTracker::send(std::string path) {
    assert(connected());
    auto message = boost::filesystem::absolute(path).string() + '\n';
    auto ret = LOGSEER_SOCKET_WRITE(_socket, message.c_str(), message.size() + 1);
    if (ret == 0) {
        log_infof("%s: could not write to socket, error %d", __func__, LOGSEER_ERRNO);
        return;
    }
}

void InstanceTracker::stop() {
    if (_socket != LOGSEER_INVALID_SOCKET) {
        shutdown(_socket, LOGSEER_SHUTDOWN_RDWR);
        LOGSEER_CLOSE_SOCKET(_socket);
        _socket = LOGSEER_INVALID_SOCKET;
    }

    _queue.enqueue({});

    if (_thread.joinable()) {
        _thread.join();
    }
}

std::optional<std::string> InstanceTracker::waitMessage() {
    std::optional<std::string> message;
    _queue.wait_dequeue(message);
    return message;
}

}

max_stars_repo_name: nongeneric/logseer

max_issues_repo_name: nongeneric/logseer

max_forks_repo_name: nongeneric/logseer


text:
//
//  engine.cpp
//
//  Created by Anton Leuski on 10/26/12.
//  Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved.
//
//  This file is part of Jerome.
//
//  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 <jerome/scripting/scion.hpp>

//#include <jerome/async.h>
#include <boost/algorithm/string.hpp>
#include <boost/range/algorithm/transform.hpp>

#include <jerome/scripting/async_js.hpp>
#include <jerome/scripting/PlatformJSInterface.hpp>
#include <jerome/scripting/scripts.hpp>

#include "js_engine.hpp"

namespace jerome {
	namespace scripting {

		Engine::Engine()
      : mScriptingInited(false)
      , mEngineEventHandler([](const EngineEvent&){})
		{
		}

    Engine::~Engine()
    {

    }

    void Engine::loadScripts()
    {
      context()["__scionPlatform"]	=
      context().newObjectOfNativeClass<jerome::scripting::ScionPlatform>();

      evaluateScript(SCION_SCRIPT.source,
                     SCION_SCRIPT.name);

      evaluateScript(JEROME_STARTUP_SCRIPT.source,
                     JEROME_STARTUP_SCRIPT.name);

      evaluateScript(JEROME_UTTERANCE_COMPILER_SCRIPT.source,
                     JEROME_UTTERANCE_COMPILER_SCRIPT.name);
    }

		void Engine::evaluateScript(const String& script, const String& sourceURL,
                                int startingLineNumber,
									const std::function<void(const js::Value&)>& callback) {
      auto weakSelf = std::weak_ptr<Engine>(Me::shared_from_this());
			performBlock([=]() mutable {
        if (auto self = weakSelf.lock()) {
          callback(self->context().evaluateScript(script, sourceURL,
                                                  startingLineNumber));
        }
			});
		}

		void Engine::evaluateScriptWithFilePath(const String& sourcePath,
									const std::function<void(const js::Value&)>& callback) {
			String content;
			String url = "file://" + sourcePath;
			String error;
			if (ScionPlatform::stringWithContentsOfURL(url, content, error)) {
				evaluateScript(content, url, 0, callback);
			}
		}

		void Engine::performBlock(const std::function<void(void)>& block)
		{
			dispatch::queue&	theStrand(strandFromContext(context()));
			theStrand.call(block);
		}

		String Engine::argumentsDescription() {
			String	result;
			for(auto x : js::Context::currentArguments()) {
				if (result.length()) result += ", ";
				result += (String)x;
			}
			return result;
		}

    void Engine::initializeScripting()
    {
      if (mScriptingInited) return;
      mScriptingInited = true;
      context()["classifier"] = context().newObjectOfNativeClass(
        PlatformJSInterface(Me::shared_from_this()));
    }

    void Engine::setEngineEventHandler(const EngineEventHandler& eventHandler)
    {
      mEngineEventHandler = eventHandler;
    }

    void Engine::handleEngineEvent(const EngineEvent& event)
    {
      mEngineEventHandler(event);
    }

    void  Engine::postEvent(const String& inName,
                            const StringStringMap& inData,
                            const String& inMachineName)
    {
      auto weakSelf = std::weak_ptr<Engine>(Me::shared_from_this());
      performBlock([=] () {
        if (auto self = weakSelf.lock()) {
          self->initializeScripting();
          self->context()["postEventToStateMachine"] (inMachineName,
                                                      inName, inData);
        }
      });
    }

    void  Engine::loadDialogueManager(std::istream& is,
                                      const load_dialogue_manager_callback& cb)
    {
      std::string s(std::istreambuf_iterator<char>(is), {});
      auto weakSelf = std::weak_ptr<Engine>(Me::shared_from_this());
      performBlock([=] () {
        if (auto self = weakSelf.lock()) {
          self->initializeScripting();
          self->context()["initStateMachineWithString"]
          (s, [cb](const js::Value& inError, const String& inName) {
            if (js::Context::currentArguments().size() == 1) {
              cb(Error((String)inError));
            } else {
              cb(inName);
            }
          });
        }
      });
    }

	}
}

max_stars_repo_name: leuski-ict/jerome

max_issues_repo_name: leuski-ict/jerome

max_forks_repo_name: leuski-ict/jerome


text:
// Distributed under the MIT License.
// See LICENSE.txt for details.

#pragma once

#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/enum.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <memory>
#include <optional>
#include <pup.h>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>

#include "DataStructures/Tensor/Tensor.hpp"
#include "Domain/CoordinateMaps/CoordinateMap.hpp"
#include "Domain/CoordinateMaps/CoordinateMap.tpp"
#include "Domain/FunctionsOfTime/FunctionOfTime.hpp"
#include "Utilities/GenerateInstantiations.hpp"

#define INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data) \
  BOOST_PP_TUPLE_ENUM(BOOST_PP_TUPLE_ELEM(0, data))
#define INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data)                     \
  BOOST_PP_TUPLE_ELEM(BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_ELEM(0, data)), 0, \
                      BOOST_PP_TUPLE_ELEM(0, data))::dim
#define INSTANTIATE_COORD_MAP_DETAILINSERT_SIZE(z, n, _) BOOST_PP_COMMA_IF(n) n

#define INSTANTIATE_COORD_MAP_DETAIL_GET_FILLED_INDEX_SEQUENCE(data) \
  BOOST_PP_REPEAT(BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_ELEM(0, data)), \
                  INSTANTIATE_COORD_MAP_DETAILINSERT_SIZE, _)

#define INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data) \
  BOOST_PP_TUPLE_ELEM(1, data)

#define INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data) \
  BOOST_PP_TUPLE_ELEM(2, data)

#define INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data) BOOST_PP_TUPLE_ELEM(3, data)

/*!
 * \ingroup ComputationalDomainGroup
 * \brief Generate instantiations of member functions of the `CoordinateMap`
 * class template.
 *
 * Called as follows:
 *
 * \code
 *  using Affine2d =
 *      domain::CoordinateMaps::ProductOf2Maps<domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine>;
 *  using Affine3d =
 *      domain::CoordinateMaps::ProductOf3Maps<domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine>;
 *
 *  GENERATE_INSTANTIATIONS(INSTANTIATE_MAPS_SIMPLE_FUNCTIONS,
 *                          ((Affine2d), (Affine3d)), (Frame::Logical),
 *                          (Frame::Grid, Frame::Inertial))
 * \endcode
 *
 * The first tuple passed to `GENERATE_INSTANTIATIONS` has a bunch of tuples in
 * it that is the list of maps being composed. The reason for defining the type
 * aliases `Affine2d` and `Affine3d` is that otherwise the number of maps being
 * composed is calculated incorrectly. The second tuple contains the source
 * frames for the map. The third tuple passed to `GENERATE_INSTANTIATIONS`
 * contains the target frames to instantiate for, typically `Frame::Grid` and
 * `Frame::Inertial`.
 *
 * Instantiates:
 * - `get_to_grid_frame_impl`
 * - `inverse_impl`
 * - `class CoordinateMap`
 */
#define INSTANTIATE_MAPS_SIMPLE_FUNCTIONS(_, data)                           \
  template std::unique_ptr<domain::CoordinateMapBase<                        \
      INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data), Frame::Grid,      \
      INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data)>>                      \
      domain::CoordinateMap<                                                 \
          INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data),               \
          INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data),               \
          INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data)>::                     \
          get_to_grid_frame_impl(                                            \
              std::integer_sequence<                                         \
                  unsigned long,                                             \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_FILLED_INDEX_SEQUENCE(    \
                      data)>) const noexcept;                                \
  template std::optional<                                                    \
      tnsr::I<double, INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),       \
              INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data)>>          \
  domain::CoordinateMap<INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data)>::       \
      inverse_impl(                                                          \
          tnsr::I<double, INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),   \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>&&,    \
          double,                                                            \
          const std::unordered_map<                                          \
              std::string,                                                   \
              std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&,    \
          std::index_sequence<                                               \
              INSTANTIATE_COORD_MAP_DETAIL_GET_FILLED_INDEX_SEQUENCE(        \
                  data)> /*meta*/) const noexcept;                           \
  template class domain::CoordinateMap<                                      \
      INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data),                   \
      INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data),                   \
      INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data)>;

/*!
 * \ingroup ComputationalDomainGroup
 * \brief Generate instantiations of member functions of the `CoordinateMap`
 * class template.
 *
 * Called as follows:
 *
 * \code
 *  using Affine2d =
 *      domain::CoordinateMaps::ProductOf2Maps<domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine>;
 *  using Affine3d =
 *      domain::CoordinateMaps::ProductOf3Maps<domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine>;
 *
 *  GENERATE_INSTANTIATIONS(INSTANTIATE_MAPS_DATA_TYPE_FUNCTIONS,
 *                          ((Affine2d), (Affine3d)), (Frame::Logical),
 *                          (Frame::Grid, Frame::Inertial),
 *                          (double, DataVector))
 * \endcode
 *
 * The first tuple passed to `GENERATE_INSTANTIATIONS` has a bunch of tuples in
 * it that is the list of maps being composed. The reason for defining the type
 * aliases `Affine2d` and `Affine3d` is that otherwise the number of maps being
 * composed is calculated incorrectly. The second tuple contains the source
 * frames for the map. The third tuple passed to  `GENERATE_INSTANTIATIONS`
 * contains the target frames to instantiate for, typically `Frame::Grid` and
 * `Frame::Inertial`. The last tuple is the data types for which to instantiate
 * the functions, usually `double` and `DataVector`.
 *
 * Instantiates:
 * - `call_impl`
 * - `inv_jacobian_impl`
 * - `jacobian_impl`
 * - `coords_frame_velocity_jacobians_impl`
 */
#define INSTANTIATE_MAPS_DATA_TYPE_FUNCTIONS(_, data)                        \
  template tnsr::I<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                 \
                   INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),          \
                   INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>      \
  domain::CoordinateMap<INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data)>::       \
      call_impl(                                                             \
          tnsr::I<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                  \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),           \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data)>&&,    \
          double,                                                            \
          const std::unordered_map<                                          \
              std::string,                                                   \
              std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&,    \
          std::integer_sequence<                                             \
              unsigned long,                                                 \
              INSTANTIATE_COORD_MAP_DETAIL_GET_FILLED_INDEX_SEQUENCE(data)>) \
          const;                                                             \
  template InverseJacobian<                                                  \
      INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                              \
      INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),                       \
      INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data),                   \
      INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>                   \
  domain::CoordinateMap<INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data)>::       \
      inv_jacobian_impl(                                                     \
          tnsr::I<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                  \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),           \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data)>&&,    \
          double,                                                            \
          const std::unordered_map<                                          \
              std::string,                                                   \
              std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&)    \
          const;                                                             \
  template Jacobian<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                \
                    INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),         \
                    INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data),     \
                    INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>     \
  domain::CoordinateMap<INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data)>::       \
      jacobian_impl(                                                         \
          tnsr::I<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                  \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),           \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data)>&&,    \
          double,                                                            \
          const std::unordered_map<                                          \
              std::string,                                                   \
              std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&)    \
          const;                                                             \
  template std::tuple<                                                       \
      tnsr::I<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                      \
              INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),               \
              INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>,          \
      InverseJacobian<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),              \
                      INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),       \
                      INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data),   \
                      INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>,  \
      Jacobian<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                     \
               INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),              \
               INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data),          \
               INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>,         \
      tnsr::I<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                      \
              INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),               \
              INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data)>>          \
  domain::CoordinateMap<INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_TARGET_FRAME(data), \
                        INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS(data)>::       \
      coords_frame_velocity_jacobians_impl(                                  \
          tnsr::I<INSTANTIATE_COORD_MAP_DETAIL_DTYPE(data),                  \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_MAPS_DIM(data),           \
                  INSTANTIATE_COORD_MAP_DETAIL_GET_SOURCE_FRAME(data)>,      \
          double,                                                            \
          const std::unordered_map<                                          \
              std::string,                                                   \
              std::unique_ptr<domain::FunctionsOfTime::FunctionOfTime>>&)    \
          const;

/*!
 * \ingroup ComputationalDomainGroup
 * \brief Generate instantiations of member functions of the `CoordinateMap`
 * class template.
 *
 * Called as follows:
 *
 * \code
 *  using Affine2d =
 *      domain::CoordinateMaps::ProductOf2Maps<domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine>;
 *  using Affine3d =
 *      domain::CoordinateMaps::ProductOf3Maps<domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine,
 *                                             domain::CoordinateMaps::Affine>;
 *
 *  INSTANTIATE_MAPS_FUNCTIONS(((Affine2d), (Affine3d)), (Frame::Logical),
 *                             (Frame::Grid, Frame::Inertial),
 *                             (double, DataVector))
 * \endcode
 *
 * The first tuple passed to `GENERATE_INSTANTIATIONS` has a bunch of tuples in
 * it that is the list of maps being composed. The reason for defining the type
 * aliases `Affine2d` and `Affine3d` is that otherwise the number of maps being
 * composed is calculated incorrectly. The second tuple contains the source
 * frames for the map. The third tuple passed to `GENERATE_INSTANTIATIONS`
 * contains the frames to instantiate for, typically `Frame::Grid` and
 * `Frame::Inertial`.
 *
 * Instantiates:
 * - `get_to_grid_frame_impl`
 * - `inverse_impl`
 * - `class CoordinateMap`
 * - `call_impl`
 * - `inv_jacobian_impl`
 * - `jacobian_impl`
 * - `coords_frame_velocity_jacobians_impl`
 */
#define INSTANTIATE_MAPS_FUNCTIONS(MAPS_TUPLE, SOURCE_FRAME,                \
                                   TARGET_FRAMES_TUPLE, TYPES_TUPLE)        \
  GENERATE_INSTANTIATIONS(INSTANTIATE_MAPS_SIMPLE_FUNCTIONS, MAPS_TUPLE,    \
                          SOURCE_FRAME, TARGET_FRAMES_TUPLE)                \
  GENERATE_INSTANTIATIONS(INSTANTIATE_MAPS_DATA_TYPE_FUNCTIONS, MAPS_TUPLE, \
                          SOURCE_FRAME, TARGET_FRAMES_TUPLE, TYPES_TUPLE)


text:
#include "p2p_websocket_session.h"

#include <boost/asio/bind_executor.hpp>
#include <boost/beast/websocket/error.hpp>
#include <boost/beast/websocket/stream.hpp>
#include <nlohmann/json.hpp>

#include "util.h"

using json = nlohmann::json;

P2PWebsocketSession::P2PWebsocketSession(RTCManager* rtc_manager,
                                         ConnectionSettings conn_settings)
    : rtc_manager_(rtc_manager), conn_settings_(conn_settings) {
  RTC_LOG(LS_INFO) << __FUNCTION__;
}

P2PWebsocketSession::~P2PWebsocketSession() {
  RTC_LOG(LS_INFO) << __FUNCTION__;
}

std::shared_ptr<P2PWebsocketSession> P2PWebsocketSession::make_shared(
    boost::asio::ip::tcp::socket socket,
    RTCManager* rtc_manager,
    ConnectionSettings conn_settings) {
  auto p = std::make_shared<P2PWebsocketSession>(rtc_manager, conn_settings);
  p->ws_ = std::unique_ptr<Websocket>(new Websocket(std::move(socket)));
  return p;
}

void P2PWebsocketSession::run(
    boost::beast::http::request<boost::beast::http::string_body> req) {
  RTC_LOG(LS_INFO) << __FUNCTION__;
  doAccept(std::move(req));
}

void P2PWebsocketSession::doAccept(
    boost::beast::http::request<boost::beast::http::string_body> req) {
  RTC_LOG(LS_INFO) << __FUNCTION__;
  // Accept the websocket handshake
  ws_->nativeSocket().async_accept(
      req,
      boost::asio::bind_executor(
          ws_->strand(), std::bind(&P2PWebsocketSession::onAccept,
                                   shared_from_this(), std::placeholders::_1)));
}

void P2PWebsocketSession::onAccept(boost::system::error_code ec) {
  RTC_LOG(LS_INFO) << __FUNCTION__ << ": " << ec;

  if (ec)
    return MOMO_BOOST_ERROR(ec, "Accept");

  // WebSocket での読み込みを開始
  ws_->startToRead(std::bind(&P2PWebsocketSession::onRead, shared_from_this(),
                             std::placeholders::_1, std::placeholders::_2,
                             std::placeholders::_3));
}

void P2PWebsocketSession::onRead(boost::system::error_code ec,
                                 std::size_t bytes_transferred,
                                 std::string recv_string) {
  RTC_LOG(LS_INFO) << __FUNCTION__ << ": " << ec;

  boost::ignore_unused(bytes_transferred);

  if (ec == boost::beast::websocket::error::closed)
    return;

  if (ec)
    return MOMO_BOOST_ERROR(ec, "Read");

  json recv_message;

  RTC_LOG(LS_INFO) << __FUNCTION__ << ": recv_string=" << recv_string;

  try {
    recv_message = json::parse(recv_string);
  } catch (json::parse_error& e) {
    return;
  }

  std::string type;
  try {
    type = recv_message["type"];
  } catch (json::type_error& e) {
    return;
  }

  if (type == "offer") {
    std::string sdp;
    try {
      sdp = recv_message["sdp"];
    } catch (json::type_error& e) {
      return;
    }

    auto send = std::bind([](P2PWebsocketSession* session,
                             std::string str) { session->ws_->sendText(str); },
                          this, std::placeholders::_1);
    connection_ = std::make_shared<P2PConnection>(rtc_manager_, send);
    std::shared_ptr<RTCConnection> rtc_conn = connection_->getRTCConnection();
    rtc_conn->setOffer(sdp);
  } else if (type == "answer") {
    std::shared_ptr<P2PConnection> p2p_conn = connection_;
    if (!p2p_conn) {
      return;
    }
    std::string sdp;
    try {
      sdp = recv_message["sdp"];
    } catch (json::type_error& e) {
      return;
    }
    std::shared_ptr<RTCConnection> rtc_conn = p2p_conn->getRTCConnection();
    rtc_conn->setAnswer(sdp);
  } else if (type == "candidate") {
    std::shared_ptr<P2PConnection> p2p_conn = connection_;
    if (!p2p_conn) {
      return;
    }
    int sdp_mlineindex = 0;
    std::string sdp_mid, candidate;
    try {
      json ice = recv_message["ice"];
      sdp_mid = ice["sdpMid"];
      sdp_mlineindex = ice["sdpMLineIndex"];
      candidate = ice["candidate"];
    } catch (json::type_error& e) {
      return;
    }
    std::shared_ptr<RTCConnection> rtc_conn = p2p_conn->getRTCConnection();
    rtc_conn->addIceCandidate(sdp_mid, sdp_mlineindex, candidate);
  } else if (type == "close") {
    connection_ = nullptr;
  } else {
    return;
  }
}

max_stars_repo_name: kadoshita/momo

max_issues_repo_name: tnoho/webrtc-robot-arm

max_forks_repo_name: tnoho/webrtc-robot-arm


text:
#pragma once

#ifndef _node_node_locker_hpp
#define _node_node_locker_hpp

#include <boost/thread/recursive_mutex.hpp>
#include <boost/core/noncopyable.hpp>

namespace prologcoin { namespace node {

class self_node;

class node_locker : public boost::noncopyable {
public:
    node_locker(self_node &node);
    node_locker(node_locker &&other);
    ~node_locker();

private:
    boost::recursive_mutex *lock_;
};

}}

#endif

max_stars_repo_name: datavetaren/prologcoin

max_issues_repo_name: datavetaren/prologcoin

max_forks_repo_name: datavetaren/prologcoin


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

namespace chain_kv = b1::chain_kv;

struct kv_values {
   std::vector<std::pair<chain_kv::bytes, chain_kv::bytes>> values;

   friend bool operator==(const kv_values& a, const kv_values& b) { return a.values == b.values; }
};

template <typename S>
S& operator<<(S& s, const kv_values& v) {
   s << "{\n";
   for (auto& kv : v.values) {
      s << "    {{";
      bool first = true;
      for (auto b : kv.first) {
         if (!first)
            s << ", ";
         first = false;
         char x[10];
         sprintf(x, "0x%02x", (uint8_t)b);
         s << x;
      }
      s << "}, {";
      first = true;
      for (auto b : kv.second) {
         if (!first)
            s << ", ";
         first = false;
         char x[10];
         sprintf(x, "0x%02x", (uint8_t)b);
         s << x;
      }
      s << "}},\n";
   }
   s << "}";
   return s;
}

#define KV_REQUIRE_EXCEPTION(expr, msg)                                                                                \
   BOOST_REQUIRE_EXCEPTION(expr, chain_kv::exception, [](auto& e) {                                                    \
      if (!strcmp(e.what(), msg))                                                                                \
         return true;                                                                                \
      std::cerr << "expected: '"                                                                                \
                << "\033[33m" << msg << "\033[0m'\ngot:      '\033[33m" << e.what() << "'\033[0m\n";                   \
      return false;                                                                                \
   });

inline kv_values get_all(chain_kv::database& db, const chain_kv::bytes& prefix) {
   kv_values                          result;
   std::unique_ptr<rocksdb::Iterator> rocks_it{ db.rdb->NewIterator(rocksdb::ReadOptions()) };
   rocks_it->Seek(chain_kv::to_slice(prefix));
   while (rocks_it->Valid()) {
      auto k = rocks_it->key();
      if (k.size() < prefix.size() || memcmp(k.data(), prefix.data(), prefix.size()))
         break;
      auto v = rocks_it->value();
      result.values.push_back({ chain_kv::to_bytes(k), chain_kv::to_bytes(v) });
      rocks_it->Next();
   }
   if (!rocks_it->status().IsNotFound())
      chain_kv::check(rocks_it->status(), "iterate: ");
   return result;
}

inline kv_values get_values(chain_kv::write_session& session, const std::vector<chain_kv::bytes>& keys) {
   kv_values result;
   for (auto& key : keys) {
      chain_kv::bytes value;
      if (auto value = session.get(chain_kv::bytes{ key }))
         result.values.push_back({ key, *value });
   }
   return result;
}

inline kv_values get_matching(chain_kv::view& view, uint64_t contract, const chain_kv::bytes& prefix = {}) {
   kv_values                result;
   chain_kv::view::iterator it{ view, contract, chain_kv::to_slice(prefix) };
   ++it;
   while (!it.is_end()) {
      auto kv = it.get_kv();
      if (!kv)
         throw chain_kv::exception("iterator read failure");
      result.values.push_back({ chain_kv::to_bytes(kv->key), chain_kv::to_bytes(kv->value) });
      ++it;
   }
   return result;
}

inline kv_values get_matching2(chain_kv::view& view, uint64_t contract, const chain_kv::bytes& prefix = {}) {
   kv_values                result;
   chain_kv::view::iterator it{ view, contract, chain_kv::to_slice(prefix) };
   --it;
   while (!it.is_end()) {
      auto kv = it.get_kv();
      if (!kv)
         throw chain_kv::exception("iterator read failure");
      result.values.push_back({ chain_kv::to_bytes(kv->key), chain_kv::to_bytes(kv->value) });
      --it;
   }
   std::reverse(result.values.begin(), result.values.end());
   return result;
}

inline kv_values get_it(const chain_kv::view::iterator& it) {
   kv_values result;
   auto      kv = it.get_kv();
   if (!kv)
      throw chain_kv::exception("iterator read failure");
   result.values.push_back({ chain_kv::to_bytes(kv->key), chain_kv::to_bytes(kv->value) });
   return result;
}

max_stars_repo_name: SuperBladeMaster/EOS

max_issues_repo_name: SuperBladeMaster/EOS

max_forks_repo_name: SuperBladeMaster/EOS


text:
// Copyright (C) 2011  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.

#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <dlib/bridge.h>
#include <dlib/type_safe_union.h>

#include "tester.h"

namespace
{
    using namespace test;
    using namespace dlib;
    using namespace std;

    logger dlog("test.bridge");

    const unsigned short testing_port = 41238;

    void do_test1()
    {
        dlib::pipe<int> in(0), out(0);

        bridge b1(connect_to_ip_and_port("127.0.0.1",testing_port), receive(in));
        bridge b2(listen_on_port(testing_port), transmit(out));

        for (int i = 0; i < 100; ++i)
        {
            int val = i;
            out.enqueue(val);
            val = 0;
            in.dequeue(val);
            DLIB_TEST(val == i);
        }
    }

    void do_test2()
    {
        dlib::pipe<int> in(0), out(0), echo_pipe(0);

        bridge b2(listen_on_port(testing_port), transmit(out), receive(in));
        bridge echo(connect_to_ip_and_port("127.0.0.1",testing_port), receive(echo_pipe), transmit(echo_pipe));

        for (int i = 0; i < 100; ++i)
        {
            int val = i;
            out.enqueue(val);
            val = 0;
            in.dequeue(val);
            DLIB_TEST(val == i);
        }
    }

    void do_test3()
    {
        dlib::pipe<int> in(10), out(10), echo_pipe(10);

        bridge b2(listen_on_port(testing_port), transmit(out), receive(in));
        bridge echo(connect_to_ip_and_port("127.0.0.1",testing_port), receive(echo_pipe), transmit(echo_pipe));

        b2.reconfigure(listen_on_port(testing_port), transmit(out), receive(in));

        for (int i = 0; i < 100; ++i)
        {
            int val = i;
            out.enqueue(val);
            val = 0;
            in.dequeue(val);
            DLIB_TEST(val == i);
        }
    }

    void do_test4()
    {
        dlib::pipe<int> in(0), out(0), echo_pipe(0);

        bridge b2, echo;
        b2.reconfigure(listen_on_port(testing_port), receive(in), transmit(out));
        echo.reconfigure(connect_to_ip_and_port("127.0.0.1",testing_port), transmit(echo_pipe), receive(echo_pipe));

        for (int i = 0; i < 100; ++i)
        {
            int val = i;
            out.enqueue(val);
            val = 0;
            in.dequeue(val);
            DLIB_TEST(val == i);
        }
    }

    void do_test5(int pipe_size)
    {
        typedef type_safe_union<int, bridge_status> tsu_type;

        dlib::pipe<tsu_type> out(pipe_size);
        dlib::pipe<tsu_type> in(pipe_size);
        dlib::pipe<bridge_status> out_status(pipe_size);

        bridge b1(connect_to_ip_and_port("127.0.0.1",testing_port), receive(in));
        tsu_type msg;

        msg = b1.get_bridge_status();
        DLIB_TEST(msg.contains<bridge_status>() == true);
        DLIB_TEST(msg.get<bridge_status>().is_connected == false);
        DLIB_TEST(msg.get<bridge_status>().foreign_ip == "");
        DLIB_TEST(msg.get<bridge_status>().foreign_port == 0);

        {
            bridge b2(listen_on_port(testing_port), transmit(out), receive(out_status));

            in.dequeue(msg);
            DLIB_TEST(msg.contains<bridge_status>() == true);
            DLIB_TEST(msg.get<bridge_status>().is_connected == true);
            DLIB_TEST(msg.get<bridge_status>().foreign_ip == "127.0.0.1");
            DLIB_TEST(msg.get<bridge_status>().foreign_port == testing_port);
            msg = b1.get_bridge_status();
            DLIB_TEST(msg.contains<bridge_status>() == true);
            DLIB_TEST(msg.get<bridge_status>().is_connected == true);
            DLIB_TEST(msg.get<bridge_status>().foreign_ip == "127.0.0.1");
            DLIB_TEST(msg.get<bridge_status>().foreign_port == testing_port);

            bridge_status temp;
            out_status.dequeue(temp);
            DLIB_TEST(temp.is_connected == true);
            DLIB_TEST(temp.foreign_ip == "127.0.0.1");

            for (int i = 0; i < 100; ++i)
            {
                msg = i;
                out.enqueue(msg);

                msg.get<int>() = 0;

                in.dequeue(msg);
                DLIB_TEST(msg.contains<int>() == true);
                DLIB_TEST(msg.get<int>() == i);
            }

        }

        in.dequeue(msg);
        DLIB_TEST(msg.contains<bridge_status>() == true);
        DLIB_TEST(msg.get<bridge_status>().is_connected == false);
        DLIB_TEST(msg.get<bridge_status>().foreign_ip == "127.0.0.1");
        DLIB_TEST(msg.get<bridge_status>().foreign_port == testing_port);
    }

    void do_test5_5(int pipe_size)
    {
        typedef type_safe_union<int, bridge_status> tsu_type;

        dlib::pipe<tsu_type> out(pipe_size);
        dlib::pipe<tsu_type> in(pipe_size);
        dlib::pipe<bridge_status> out_status(pipe_size);

        bridge b1(connect_to_ip_and_port("127.0.0.1",testing_port), receive(in));
        tsu_type msg;

        bridge b2(listen_on_port(testing_port), transmit(out), receive(out_status));

        in.dequeue(msg);
        DLIB_TEST(msg.contains<bridge_status>() == true);
        DLIB_TEST(msg.get<bridge_status>().is_connected == true);
        DLIB_TEST(msg.get<bridge_status>().foreign_ip == "127.0.0.1");
        DLIB_TEST(msg.get<bridge_status>().foreign_port == testing_port);

        bridge_status temp;
        out_status.dequeue(temp);
        DLIB_TEST(temp.is_connected == true);
        DLIB_TEST(temp.foreign_ip == "127.0.0.1");

        for (int i = 0; i < 100; ++i)
        {
            msg = i;
            out.enqueue(msg);

            msg.get<int>() = 0;

            in.dequeue(msg);
            DLIB_TEST(msg.contains<int>() == true);
            DLIB_TEST(msg.get<int>() == i);
        }

        b2.clear();
        msg = b2.get_bridge_status();
        DLIB_TEST(msg.contains<bridge_status>() == true);
        DLIB_TEST(msg.get<bridge_status>().is_connected == false);
        DLIB_TEST(msg.get<bridge_status>().foreign_ip == "");
        DLIB_TEST(msg.get<bridge_status>().foreign_port == 0);

        in.dequeue(msg);
        DLIB_TEST(msg.contains<bridge_status>() == true);
        DLIB_TEST(msg.get<bridge_status>().is_connected == false);
        DLIB_TEST(msg.get<bridge_status>().foreign_ip == "127.0.0.1");
        DLIB_TEST(msg.get<bridge_status>().foreign_port == testing_port);
    }

    void do_test6()
    {
        dlib::pipe<int> in(0), out(300);

        bridge b1(connect_to_ip_and_port("127.0.0.1",testing_port), receive(in));
        bridge b2(listen_on_port(testing_port), transmit(out));

        for (int i = 0; i < 100; ++i)
        {
            int val = i;
            out.enqueue(val);
        }

        int val = 10;
        in.dequeue(val);
        DLIB_TEST(val == 0);
        dlib::sleep(100);
        in.dequeue(val);
        DLIB_TEST(val == 1);
        dlib::sleep(100);
    }

    class test_bridge : public tester
    {
    public:
        test_bridge (
        ) :
            tester ("test_bridge",
                    "Runs tests on the bridge component.")
        {}

        void perform_test (
        )
        {
            dlog << LINFO << "testing bridge, using local port number of " << testing_port;

            print_spinner();
            do_test1();
            print_spinner();
            do_test2();
            print_spinner();
            do_test3();
            print_spinner();
            do_test4();
            print_spinner();
            for (int i = 0; i < 5; ++i)
                do_test5(i);
            do_test5_5(1);
            print_spinner();
            do_test6();
        }
    } a;

}


text:
// Copyright (c) 2011 by Raytheon BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h" // This must be the first #include
#include "Generic/common/SessionLogger.h"
#include "Generic/patterns/PropPattern.h"
#include "Generic/patterns/RegexPattern.h"
#include "Generic/patterns/ShortcutPattern.h"
#include "Generic/patterns/ArgumentPattern.h"
#include "Generic/patterns/CombinationPattern.h"
#include "Generic/patterns/PatternMatcher.h"
#include "Generic/patterns/features/PatternFeatureSet.h"
#include "Generic/patterns/features/ReturnPFeature.h"
#include "Generic/patterns/features/PropPFeature.h"
#include "Generic/theories/DocTheory.h"
#include "Generic/theories/SentenceTheory.h"
#include "Generic/theories/PropositionSet.h"
#include "Generic/theories/Proposition.h"
#include "Generic/theories/TokenSequence.h"
#include "Generic/theories/Parse.h"
#include "Generic/theories/SynNode.h"
#include "Generic/common/ParamReader.h"
#include <boost/foreach.hpp>
#include "Generic/common/Sexp.h"
#include "Generic/wordnet/xx_WordNet.h"

// Private symbols
namespace {
	Symbol nounPropSym(L"nprop");
	Symbol verbPropSym(L"vprop");
	Symbol modifierPropSym(L"mprop");
	Symbol setPropSym(L"sprop");
	Symbol compoundPropSym(L"cprop");
	Symbol anyPropSym(L"anyprop");
	Symbol blockSym(L"block_args");
	Symbol argsSym(L"args");
	Symbol optArgSym(L"opt_args");
	Symbol adjectiveSym(L"adj");
	Symbol blockAdjectiveSym(L"block_adj");
	Symbol adverbParticleSym(L"adverb_or_particle");
	Symbol blockAdverbParticleSym(L"block_adv_part");
	Symbol predicateSym(L"predicate");
	Symbol alignedPredicateSym(L"aligned_predicate");
	Symbol blockPredicateSym(L"block_predicate");
	Symbol predTypeSym(L"predicate_type");
	Symbol definiteSym(L"DEFINITE");
	Symbol negativeSym(L"NEGATIVE");
	Symbol matchAllArgsSym(L"MATCH_ALL_ARGS");
	Symbol stemPredicateSym(L"STEM_PREDICATE");
	Symbol blockFTSym(L"BLOCK_FALL_THROUGH");
	Symbol particleSym(L"particle");
	Symbol propModifierSym(L"propmod");
	Symbol regexSym(L"regex");
	Symbol oneToOneSym(L"ONE_TO_ONE");
	Symbol manyToManySym(L"MANY_TO_MANY");
	Symbol negationSym(L"negation");
	Symbol blockNegationSym(L"block_negation");
	Symbol modalSym(L"modal");
	Symbol blockModalSym(L"block_modal");
}

PropPattern::PropPattern(Sexp *sexp, const Symbol::HashSet &entityLabels, const PatternWordSetMap& wordSets)
: _require_one_to_one_argument_mapping(false),
  _allow_many_to_many_mapping(false),
  _require_all_arguments_to_match_some_pattern(false),
  _propStatusManager(boost::make_shared<PropStatusManager>()),
  _psm_manually_initialized(false),
  _stem_predicate(false),
  _block_fall_through(false)
{
	// Initialize our predicate type.
	Symbol pred = sexp->getFirstChild()->getValue();
	if (pred == nounPropSym) {
		_predicateType = Proposition::NOUN_PRED;
	} else if (pred == verbPropSym) {
		_predicateType = Proposition::VERB_PRED;
	} else if (pred == modifierPropSym) {
		_predicateType = Proposition::MODIFIER_PRED;
	} else if (pred == setPropSym) {
		_predicateType = Proposition::SET_PRED;
	} else if (pred == compoundPropSym) {
		_predicateType = Proposition::COMP_PRED;
	} else if (pred == anyPropSym) {
		_predicateType = Proposition::ANY_PRED;
	} else throwError(sexp, "unrecognized PropPattern type");

	// Parse the s-expression
	initializeFromSexp(sexp, entityLabels, wordSets);
}

bool PropPattern::initializeFromAtom(Sexp *childSexp, const Symbol::HashSet &entityLabels, const PatternWordSetMap& wordSets)
{
	Symbol atom = childSexp->getValue();
	if (LanguageVariantSwitchingPattern::initializeFromAtom(childSexp, entityLabels, wordSets)) {
		return true;
	} else if (atom == negativeSym) {
		// This is to maintain backwards compatibility
		if (_psm_manually_initialized)
			throwError(childSexp, "cannot initialize PropStatusManager twice; note that 'NEGATIVE' counts as a psm");
		_propStatusManager = boost::make_shared<PropStatusManager>(true);
		_psm_manually_initialized = true;
		return true;
	} else if (childSexp->getValue() == blockFTSym) {
		_block_fall_through = true;
		return true;
	} else if (childSexp->getValue() == oneToOneSym) {
		_require_one_to_one_argument_mapping = true;
		return true;
	} else if (childSexp->getValue() == manyToManySym) {
		_allow_many_to_many_mapping = true;
		return true;
	} else if (childSexp->getValue() == matchAllArgsSym) {
		_require_all_arguments_to_match_some_pattern = true;
		return true;
	} else if (childSexp->getValue() == stemPredicateSym) {
		_stem_predicate = true;
		return true;
	} else {
		logFailureToInitializeFromAtom(childSexp);
		return false;
	}
}

bool PropPattern::initializeFromSubexpression(Sexp *childSexp, const Symbol::HashSet &entityLabels, const PatternWordSetMap& wordSets)
{
	Symbol constraintType = childSexp->getFirstChild()->getValue();
	if (LanguageVariantSwitchingPattern::initializeFromSubexpression(childSexp, entityLabels, wordSets)) {
		return true;
	} else if (constraintType == predicateSym) {
		fillListOfWordsWithWildcards(childSexp, wordSets, _predicates, _predicatePrefixes);
	} else if (constraintType == alignedPredicateSym) {
		fillListOfWords(childSexp, wordSets, _alignedPredicates);
	} else if (constraintType == blockPredicateSym) {
		fillListOfWordsWithWildcards(childSexp, wordSets, _blockedPredicates, _blockedPredicatePrefixes);
	} else if (constraintType == particleSym) {
		fillListOfWords(childSexp, wordSets, _particles);
	} else if (constraintType == adjectiveSym) {
		fillListOfWords(childSexp, wordSets, _adjectives);
	} else if (constraintType == blockAdjectiveSym) {
		fillListOfWords(childSexp, wordSets, _blockedAdjectives);
	} else if (constraintType == blockAdverbParticleSym) {
		fillListOfWords(childSexp, wordSets, _blockedAdverbsOrParticles);
	} else if (constraintType == adverbParticleSym) {
		fillListOfWords(childSexp, wordSets, _adverbOrParticles);
	} else if (constraintType == negationSym) {
		fillListOfWordsWithWildcards(childSexp, wordSets, _negations, _negationPrefixes);
	} else if (constraintType == blockNegationSym) {
		fillListOfWordsWithWildcards(childSexp, wordSets, _blockedNegations, _blockedNegationPrefixes);
	} else if (constraintType == modalSym) {
		fillListOfWordsWithWildcards(childSexp, wordSets, _modals, _modalPrefixes);
	} else if (constraintType == blockModalSym) {
		fillListOfWordsWithWildcards(childSexp, wordSets, _blockedModals, _blockedModalPrefixes);
	} else if (constraintType == regexSym) {
		if (_regexPattern != 0)
			throwError(childSexp, "more than one regex in PropPattern");
		_regexPattern = parseSexp(childSexp->getSecondChild(), entityLabels, wordSets);
	} else if (constraintType == blockSym) {
		int n_blocked_args = childSexp->getNumChildren() - 1;
		for (int j = 0; j < n_blocked_args; j++) {
			_blockedArgs.push_back(parseSexp(childSexp->getNthChild(j+1), entityLabels, wordSets));
		}
	} else if (constraintType == argsSym) {
		int n_args = childSexp->getNumChildren() - 1;
		for (int j = 0; j < n_args; j++) {
			_args.push_back(parseSexp(childSexp->getNthChild(j+1), entityLabels, wordSets));
		}
	} else if (constraintType == optArgSym) {
		int n_opt_args = childSexp->getNumChildren() -1;
		for(int j = 0; j < n_opt_args; j++) {
			_optArgs.push_back(parseSexp(childSexp->getNthChild(j+1), entityLabels, wordSets));
		}
	} else if (PropStatusManager::isPropStatusManagerSym(constraintType)) {
		if (_psm_manually_initialized)
			throwError(childSexp, "cannot initialize PropStatusManager twice; note that 'NEGATIVE' counts as a psm");
		_propStatusManager = boost::make_shared<PropStatusManager>(childSexp);
		_psm_manually_initialized = true;
	} else if (constraintType == propModifierSym) {
		if (_propModifierPattern != 0)
			throwError(childSexp, "only one propmod is allowed per pattern");
		if (childSexp->getNumChildren() < 3)
			throwError(childSexp, "propmod format invalid... must be (propMod (role ...) PATTERN)");
		Sexp *roles = childSexp->getSecondChild();
		if (!roles->isList()) throwError(childSexp, "propmod format invalid... must be (propmod (role ...) PATTERN)");
		for (int r = 1; r < roles->getNumChildren(); r++) {
			Sexp *role = roles->getNthChild(r);
			if (!role->isAtom()) throwError(childSexp, "propmod format invalid... must be (propmod (role ...) PATTERN)");
			_propModifierRoles.insert(roles->getNthChild(r)->getValue());
		}
		_propModifierPattern = parseSexp(childSexp->getThirdChild(), entityLabels, wordSets);
	} else {
		logFailureToInitializeFromChildSexp(childSexp);
		return false;
	}

	return true;
}

Pattern_ptr PropPattern::replaceShortcuts(const SymbolToPatternMap &refPatterns) {
	replaceShortcut<RegexPattern>(_regexPattern, refPatterns);
	replaceShortcut<Pattern>(_propModifierPattern, refPatterns);
	for (size_t i=0; i<_blockedArgs.size(); ++i) {
		replaceShortcut<ArgumentMatchingPattern>(_blockedArgs[i], refPatterns);
		if (ArgumentPattern_ptr pat = boost::dynamic_pointer_cast<ArgumentPattern>(_blockedArgs[i]))
			pat->disallowCapitalizedRoles();
	}
	for (size_t i=0; i<_args.size(); ++i) {
		replaceShortcut<ArgumentMatchingPattern>(_args[i], refPatterns);
		if (ArgumentPattern_ptr pat = boost::dynamic_pointer_cast<ArgumentPattern>(_args[i]))
			pat->disallowCapitalizedRoles();
	}
	for(size_t i=0; i<_optArgs.size(); ++i) {
		replaceShortcut<ArgumentMatchingPattern>(_optArgs[i], refPatterns);
		if (ArgumentPattern_ptr pat = boost::dynamic_pointer_cast<ArgumentPattern>(_optArgs[i]))
			pat->disallowCapitalizedRoles();
	}

	if (_allow_many_to_many_mapping && _require_one_to_one_argument_mapping)
		throw UnexpectedInputException("PropPattern::replaceShortcuts()", "ONE_TO_ONE and MANY_TO_MANY defined for same PropPattern");

	//Now that shortcuts have been replaced,
	//separate optional and required arguments into their respective vectors.
	std::vector<Pattern_ptr> tempArgs;
	for(size_t i = 0; i < _args.size(); ++i) {
		ArgumentPattern_ptr pat = boost::dynamic_pointer_cast<ArgumentPattern>(_args[i]);
		if (!_allow_many_to_many_mapping) {
			if (pat && pat->hasFallThroughRoles())
				throw UnexpectedInputException("PropPattern::replaceShortcuts()", "argument with allow_fall_through defined for PropPattern that isn't MANY_TO_MANY");
			CombinationPattern_ptr pat2 = boost::dynamic_pointer_cast<CombinationPattern>(_args[i]);
			if (pat2 && pat2->hasFallThroughRoles())
				throw UnexpectedInputException("PropPattern::replaceShortcuts()", "argument with allow_fall_through defined for PropPattern that isn't MANY_TO_MANY");
		}

		if (pat && pat->isOptional()) {
			_optArgs.push_back(_args[i]);
		} else {
			tempArgs.push_back(_args[i]);
		}
	}
	_args.resize(0);
	std::copy(tempArgs.begin(), tempArgs.end(), std::back_inserter(_args));
	return shared_from_this();
}

// returns all proposition matches in the sentence
PatternFeatureSet_ptr PropPattern::matchesSentence(PatternMatcher_ptr patternMatcher, SentenceTheory *sTheory, UTF8OutputStream *debug) {
	if (_languageVariant && !patternMatcher->getActiveLanguageVariant()->matchesConstraint(*_languageVariant)) {
		return matchesAlignedSentence(patternMatcher, sTheory, _languageVariant);
	}

	PatternFeatureSet_ptr allSentenceProps = boost::make_shared<PatternFeatureSet>();
	bool matched = false;

	PropositionSet *propSet = sTheory->getPropositionSet();
	std::vector<float> scores;
	for (int i = 0; i < propSet->getNPropositions(); i++) {
		//if (i != 4) { continue; }
		if (debug != 0) {
			//*debug << "      prop " << (i + 1) << "\n";
			//*debug << propSet->getProposition(i)->toString() << "\n";
		}
		PatternFeatureSet_ptr sfs = matchesProp(patternMatcher,
			sTheory->getTokenSequence()->getSentenceNumber(),
			propSet->getProposition(i), false, PropStatusManager_ptr());
		if (sfs != 0) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " PropPattern matches prop# " << i << "\n";
			if (debug != 0) {
				//*debug << "        match!\n";
			}
			allSentenceProps->addFeatures(sfs);
			scores.push_back(sfs->getScore());
			matched = true;
		}
	}
	if (matched) {
		// just want the best one from this sentence, no fancy combination
		allSentenceProps->setScore(ScoringFactory::scoreMax(scores, Pattern::UNSPECIFIED_SCORE));
		return allSentenceProps;
	} else {
		return PatternFeatureSet_ptr();
	}
}

std::vector<PatternFeatureSet_ptr> PropPattern::multiMatchesSentence(PatternMatcher_ptr patternMatcher, SentenceTheory *sTheory, UTF8OutputStream *debug) {
	std::vector<PatternFeatureSet_ptr> return_vector;

	if (_languageVariant && !patternMatcher->getActiveLanguageVariant()->matchesConstraint(*_languageVariant)) {
		return multiMatchesAlignedSentence(patternMatcher, sTheory, _languageVariant);
	}

	//TODO: parameterize this check
	//if (!patternMatcher->patternQuickCheck(toIRQuery())) {
	//	return return_vector;
	//}

	if (_force_single_match_sentence) {
		PatternFeatureSet_ptr result = matchesSentence(patternMatcher, sTheory, debug);
		if (result.get() != 0) {
			return_vector.push_back(result);
		}
		return return_vector;
	}

	PropositionSet *propSet = sTheory->getPropositionSet();
	for (int i = 0; i < propSet->getNPropositions(); i++) {
		//if (i != 6) { continue; }
		if (debug != 0) {
			//*debug << "      prop " << (i + 1) << "\n";
			//*debug << propSet->getProposition(i)->toString() << "\n";
		}

		PatternFeatureSet_ptr sfs = matchesProp(patternMatcher,
			sTheory->getTokenSequence()->getSentenceNumber(),
			propSet->getProposition(i), false, PropStatusManager_ptr());
		if (sfs != 0) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " PropPattern multi-matches prop# " << i << "\n";
			if (debug != 0) {
				//*debug << "        match!\n";
			}
			return_vector.push_back(sfs);
		}
	}
	return return_vector;
}

PatternFeatureSet_ptr PropPattern::matchesArgumentValue(PatternMatcher_ptr patternMatcher, int sent_no, const Argument *arg, bool fall_through_children, PropStatusManager_ptr statusOverrides) {
	if (arg->getType() == Argument::PROPOSITION_ARG) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " matchesArgumentValue() matching against a proposition arg.\n";
		return matchesProp(patternMatcher, sent_no, arg->getProposition(), fall_through_children, statusOverrides);
	} else if (arg->getType() == Argument::MENTION_ARG) {
		if (SessionLogger::dbg_or_msg_enabled("BRANDY"))
			SessionLogger::dbg("BRANDY") << getDebugID() << " matchesArgumentValue() trying to find a definitional prop for a mention argument: " << arg->toDebugString() << ".\n";
		Proposition *defProp = patternMatcher->getDocTheory()->getSentenceTheory(sent_no)->getPropositionSet()->getDefinition(arg->getMentionIndex());
		if (defProp != 0) {
			if (SessionLogger::dbg_or_msg_enabled("BRANDY"))
				SessionLogger::dbg("BRANDY") << getDebugID() << " matchesArgumentValue() found a definitional prop: '" << defProp->toDebugString() << "'\n";
			// Don't fall through if this is a <ref> argument (this is an implicit all-of with a proposition, typically)
			if (arg->getRoleSym() == Argument::REF_ROLE)
				return matchesProp(patternMatcher, sent_no, defProp, false, statusOverrides);
			else return matchesProp(patternMatcher, sent_no, defProp, fall_through_children, statusOverrides);
		} else {
			SessionLogger::dbg("BRANDY") << getDebugID() << " matchesArgumentValue() failed to find a definitional prop for a mention argument with index " << arg->getMentionIndex() << "!\n";
		}
	}
	SessionLogger::dbg("BRANDY") << getDebugID() << " matchesArgumentValue() returning an empty feature set.\n";
	return PatternFeatureSet_ptr();
}

PatternFeatureSet_ptr  PropPattern::matchesProp(PatternMatcher_ptr patternMatcher, int sent_no, const Proposition *prop, bool fall_through_children, PropStatusManager_ptr statusOverrides) {
	if (SessionLogger::dbg_or_msg_enabled("BRANDY"))
		SessionLogger::dbg("BRANDY") << getDebugID() << " Matching against prop '" << prop->toDebugString() << "'\n";

	if (!_block_fall_through && fall_through_children) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " In if (fall_through_children)\n";

		// First, see if this proposition matches as-is (no fall-through necessary)
		PatternFeatureSet_ptr sfs = matchesProp(patternMatcher, sent_no, prop, false, statusOverrides);
		if (sfs) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning the result of matchesProp(patternMatcher, sent_no, prop, false, statusOverrides)\n";
			return sfs;
		}
		if (SessionLogger::dbg_or_msg_enabled("BRANDY"))
			SessionLogger::dbg("BRANDY") << getDebugID() << " Didn't match, now exploring children for " << prop->toDebugString() << "'\n";

		if (prop->getPredType() == Proposition::COMP_PRED || prop->getPredType() == Proposition::SET_PRED)	{
			// See if any of its children match
			// Just pile up matching features into a single set and return, if so
			std::vector<float> scores;
			PatternFeatureSet_ptr sfs = boost::make_shared<PatternFeatureSet>();
			bool matched = false;
			for (int i = 0; i < prop->getNArgs(); i++) {
				PatternFeatureSet_ptr member_sfs;
				if( prop->getArg(i)->getRoleSym() == Argument::MEMBER_ROLE &&
					(member_sfs = matchesArgumentValue(patternMatcher, sent_no, prop->getArg(i), fall_through_children, statusOverrides)) )
				{
					sfs->addFeatures(member_sfs);
					scores.push_back(member_sfs->getScore());
					matched = true;
				}
			}
			if (matched) {
				// just want the best one from shared_from_this() list, no fancy combination [currently will always =_score anyway]
				sfs->setScore(ScoringFactory::scoreMax(scores, Pattern::UNSPECIFIED_SCORE));
				SessionLogger::dbg("BRANDY") << getDebugID() << " Returning the result of matching a comp or set child.\n";
				return sfs;
			} else {
				SessionLogger::dbg("BRANDY") << getDebugID() << " Didn't match a comp or set child, returning the empty set.\n";
				return PatternFeatureSet_ptr();
			}
		} else {
			// Fall through to the partitive child
			if (prop->getNArgs() > 0) {
				Argument *arg = prop->getArg(0);
				if (arg->getRoleSym() == Argument::REF_ROLE && arg->getType() == Argument::MENTION_ARG) {
					const Mention *refMention = arg->getMention(patternMatcher->getDocTheory()->getSentenceTheory(sent_no)->getMentionSet());
					if (refMention->getMentionType() == Mention::PART && refMention->getChild() != 0) {
						Proposition *defProp = patternMatcher->getDocTheory()->getSentenceTheory(sent_no)->getPropositionSet()->getDefinition(refMention->getChild()->getIndex());
						if (defProp != 0) {
							SessionLogger::dbg("BRANDY") << getDebugID() << " About to return the result of matching a partitive child.\n";
							return matchesProp(patternMatcher, sent_no, defProp, fall_through_children, statusOverrides);
						}
					}
				}
			}
		}
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set from falls_through_children.\n";
		return PatternFeatureSet_ptr();
	}

	if (statusOverrides) {
		if (!statusOverrides->propositionIsValid(patternMatcher, prop)) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because !statusOverrides->propositionIsValid(patternMatcher, prop)\n";
			return PatternFeatureSet_ptr();
		}
	} else if (!_propStatusManager->propositionIsValid(patternMatcher, prop)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because !_propStatusManager->propositionIsValid(patternMatcher, prop)\n";
		return PatternFeatureSet_ptr();
	}

	if (prop->getPredType() != _predicateType) {
		if (prop->getPredType() == Proposition::COPULA_PRED && _predicateType == Proposition::VERB_PRED) {
			// then that's OK
		} else if (prop->getPredType() == Proposition::NAME_PRED && _predicateType == Proposition::NOUN_PRED) {
			// this is OK too
		} else if (prop->getPredType() == Proposition::PRONOUN_PRED && _predicateType == Proposition::NOUN_PRED) {
			// this is OK too
		} else if (prop->getPredType() == Proposition::COMP_PRED && _predicateType == Proposition::COMP_PRED) {
			// this is OK too
		} else if (_predicateType == Proposition::ANY_PRED) {
			// It is OK if this prop pattern should match "any" proposition
		} else if (prop->getPredType() == Proposition::POSS_PRED && _predicateType == Proposition::MODIFIER_PRED) {
			// this is OK too
		} else {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because pred types don't match (" << Proposition::getPredTypeString(_predicateType) << " != " << Proposition::getPredTypeString(prop->getPredType()) << ")\n";
			return PatternFeatureSet_ptr();
		}
	}

	Symbol predSym = prop->getPredSymbol();
	if (_stem_predicate && !predSym.is_null()) {
		if (prop->getPredType() == Proposition::VERB_PRED) {
			predSym = WordNet::getInstance()->stem_verb(prop->getPredSymbol());
		} else if (prop->getPredType() == Proposition::NOUN_PRED) {
			predSym = WordNet::getInstance()->stem_noun(prop->getPredSymbol());
		} else if (prop->getPredType() == Proposition::MODIFIER_PRED) {
			predSym = WordNet::getInstance()->stem_verb(prop->getPredSymbol());
		}
	}

	if (!wordMatchesWithPrefix(predSym, _predicates, _predicatePrefixes, true)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because invalid predicate\n";
		return PatternFeatureSet_ptr();
	}

	if (_alignedPredicates.size() != 0) {
		if (predSym.is_null()) {
			return PatternFeatureSet_ptr();
		}

		bool matchesOne = false;
		for (std::set<Symbol>::iterator it = _alignedPredicates.begin(); it != _alignedPredicates.end(); ++it) {

			std::vector<LanguageVariant_ptr> alignedLVs = patternMatcher->getDocumentSet()->getAlignedLanguageVariants(
					patternMatcher->getActiveLanguageVariant());
			for (std::size_t lvi=0;lvi<alignedLVs.size();lvi++) {
				LanguageVariant_ptr lv = alignedLVs[lvi];

				SentenceTheory* alignedSentTheory = patternMatcher->getDocumentSet()
						->getDocTheory(lv)->getSentenceTheory(sent_no);

				if (!prop->getPredHead()) break;
				//SessionLogger::info("BRANDY") << boost::lexical_cast<std::wstring>(prop->getPredHead()->getStartToken());
				std::vector<int> alignedTokens = patternMatcher->getDocumentSet()->getAlignedTokens(
						patternMatcher->getActiveLanguageVariant(), lv, sent_no,
						prop->getPredHead()->getStartToken());
				for (std::size_t vectorInd = 0;vectorInd<alignedTokens.size();vectorInd++) {
					int i=alignedTokens[vectorInd];

					if (i >= 0 && i < alignedSentTheory->getTokenSequence()->getNTokens()) {
						Symbol alignedSymbol = alignedSentTheory->getTokenSequence()->getToken(i)->getSymbol();

						//SessionLogger::info("BRANDY") << L"Is: " << predSym.to_string()
						//	<< L" aligned to " << s.to_string()  << L"? "
						//	<< alignedSymbol.to_string() << L"\n";

						if (alignedSymbol == *it) {
							matchesOne = true;
							break;
						}
					}
				}
				if (matchesOne) break;
			}
			if (matchesOne) break;
		}

		if (!matchesOne) {
			return PatternFeatureSet_ptr();
		}
	}
	/*
	SentenceTheory* sTheory = patternMatcher->getDocTheory()->getSentenceTheory(sent_no);
	SessionLogger::info("BRANDY") << sTheory->getTokenSequence()->toString() << L"\n";
	SessionLogger::info("BRANDY") << sTheory->getFullParse()->toTreebankString(true) << L"\n";
	for (int i=0;i<sTheory->getPropositionSet()->getNPropositions();i++) {
		SessionLogger::info("BRANDY") << sTheory->getPropositionSet()->getProposition(i)->toString() << L"\n";
	}
	for (int i=0;i<sTheory->getEntitySet()->getNEntities();i++) {
		Entity* ent = sTheory->getEntitySet()->getEntity(i);
		std::wstring str = L"";
		str += ent->getType().getName().to_string();
		str += L" Entity " + boost::lexical_cast<std::wstring>(ent->getID()) + L": ";
		for (int j=0;j<ent->getNMentions();j++) {
			MentionUID uid = ent->getMention(j);
			if (Mention::getSentenceNumberFromUID(uid) == sTheory->getSentNumber()) {
				str += L"(S)";
			}
			if (patternMatcher->getDocTheory()->getMention(uid)->getMentionType() == Mention::NAME) {
				str += L"(N)";
			}
			str += patternMatcher->getDocTheory()->getMention(uid)->toCasedTextString() + L", ";
		}
		SessionLogger::info("BRANDY") << str << L"\n";
	}
	*/

	if (_particles.size() != 0 && (prop->getParticle() == 0 || _particles.find(prop->getParticle()->getHeadWord()) == _particles.end())) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of particles\n";
		return PatternFeatureSet_ptr();
	}
	if (_adverbOrParticles.size() != 0) {
		bool found = false;
		if (prop->getAdverb() != 0 && _adverbOrParticles.find(prop->getAdverb()->getHeadWord()) != _adverbOrParticles.end())
			found = true;
		// allow particles to count as adverbs... because who the heck really knows which is which!
		if (prop->getParticle() != 0 && _adverbOrParticles.find(prop->getParticle()->getHeadWord()) != _adverbOrParticles.end())
			found = true;
		if (!found) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because adverb or particle was not found\n";
			return PatternFeatureSet_ptr();
		}
	}
	if (_blockedAdverbsOrParticles.size() != 0) {
		if (prop->getAdverb() != 0 && _blockedAdverbsOrParticles.find(prop->getAdverb()->getHeadWord()) != _blockedAdverbsOrParticles.end()) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of blocked adverb\n";
			return PatternFeatureSet_ptr();
		}
		if (prop->getParticle() != 0 && _blockedAdverbsOrParticles.find(prop->getParticle()->getHeadWord()) != _blockedAdverbsOrParticles.end()) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of blocked particle\n";
			return PatternFeatureSet_ptr();
		}
	}
	if (_adjectives.size() != 0 && !matchesAdjective(_adjectives, patternMatcher, sent_no, prop)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of missing adj\n";
		return PatternFeatureSet_ptr();
	}
	if (_blockedAdjectives.size() != 0 && matchesAdjective(_blockedAdjectives, patternMatcher, sent_no, prop)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of blocked adj\n";
		return PatternFeatureSet_ptr();
	}
	if (wordMatchesWithPrefix(predSym, _blockedPredicates, _blockedPredicatePrefixes, false)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of blocked predicate\n";
		return PatternFeatureSet_ptr();
	}

	// Negations
	Symbol negation = (prop->getNegation() ? prop->getNegation()->getHeadWord() : Symbol());
	if (!wordMatchesWithPrefix(negation, _negations, _negationPrefixes, true)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because !wordMatchesWithPrefix(negation, _negations, _negationPrefixes, true)\n";
		return PatternFeatureSet_ptr();
	}
	if (wordMatchesWithPrefix(negation, _blockedNegations, _blockedNegationPrefixes, false)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because wordMatchesWithPrefix(negation, _blockedNegations, _blockedNegationPrefixes, false)\n";
		return PatternFeatureSet_ptr();
	}

	// Modals
	Symbol modal = (prop->getModal() ? prop->getModal()->getHeadWord() : Symbol());
	if (!wordMatchesWithPrefix(modal, _modals, _modalPrefixes, true)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because !wordMatchesWithPrefix(modal, _modals, _modalPrefixes, true)\n";
		return PatternFeatureSet_ptr();
	}
	if (wordMatchesWithPrefix(modal, _blockedModals, _blockedModalPrefixes, false)) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because wordMatchesWithPrefix(modal, _blockedModals, _blockedModalPrefixes, false)\n";
		return PatternFeatureSet_ptr();
	}

	// these don't count for scoring, because if they fire, we aren't matching!
	for (size_t i = 0; i < _blockedArgs.size(); i++) {
		ArgumentMatchingPattern_ptr blockedArgPattern = _blockedArgs[i]->castTo<ArgumentMatchingPattern>();
		for (int j = 0; j < prop->getNArgs(); j++) {
			PatternFeatureSet_ptr sfs = blockedArgPattern->matchesArgument(patternMatcher, sent_no, prop->getArg(j), true);
			if (sfs) {
				SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of blocked args\n";
				return PatternFeatureSet_ptr();
			}
		}
	}

	// Try every matching from pattern argument (i) to this prop argument (j).
	// Take the one with the highest score if it's greater than 0.
	std::vector<std::vector<PatternFeatureSet_ptr> > req_i_j_to_sfs;
	for (size_t i = 0; i < _args.size(); i++) {
		ArgumentMatchingPattern_ptr argMatchingPattern = _args[i]->castTo<ArgumentMatchingPattern>();
		std::vector<PatternFeatureSet_ptr> empty_vector;
		req_i_j_to_sfs.push_back(empty_vector);
		bool matched = false;
		for (int j = 0; j < prop->getNArgs(); j++) {
			if (SessionLogger::dbg_or_msg_enabled("BRANDY"))
				SessionLogger::dbg("BRANDY") << getDebugID() << " Trying to match pattern's arg '" << _args[i]->toDebugString(0) << "' to prop's arg '" << prop->getArg(j)->toDebugString() << "'\n";
			PatternFeatureSet_ptr sfs = argMatchingPattern->matchesArgument(patternMatcher, sent_no, prop->getArg(j), true);
			req_i_j_to_sfs[i].push_back(sfs);
			if (sfs) {
				matched = true;
			}
		}
		// if we fail at a non-optional argument, which should be any argument in this vector, might as well bail now
		if (!matched) {
			//ArgumentPattern_ptr argPattern = boost::dynamic_pointer_cast<ArgumentPattern>(_args[i]);
			//if (argPattern && !argPattern->isOptional()) {
			if (SessionLogger::dbg_or_msg_enabled("BRANDY"))
				SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because missing req arg: " << _args[i]->toDebugString(0) << "\n";
			return PatternFeatureSet_ptr();
			//}
		}
	}
	SessionLogger::dbg("BRANDY") << getDebugID() << " All " << _args.size() << " args matched\n";

	//Do the same with the optional arguments
	std::vector<std::vector<PatternFeatureSet_ptr> > opt_i_j_to_sfs;
	for(size_t i = 0; i < _optArgs.size(); ++i) {
		//SessionLogger::logger->reportInfoMessage() << "On optional argument pattern " << i << "\n";
		ArgumentMatchingPattern_ptr optArgMatchingPattern = _optArgs[i]->castTo<ArgumentMatchingPattern>();
		std::vector<PatternFeatureSet_ptr>empty_vector;
		opt_i_j_to_sfs.push_back(empty_vector);
		for(int j = 0; j < prop->getNArgs(); j++) {
			PatternFeatureSet_ptr sfs = optArgMatchingPattern->matchesArgument(patternMatcher, sent_no, prop->getArg(j), true);
			opt_i_j_to_sfs[i].push_back(sfs);
		}
	}

	PatternFeatureSet_ptr allFeatures = boost::make_shared<PatternFeatureSet>();
	// Add a feature for the return value (if we have one)
	if (getReturn())
		allFeatures->addFeature(boost::make_shared<PropositionReturnPFeature>(shared_from_this(), prop, sent_no, patternMatcher->getActiveLanguageVariant()));
	// Add a feature for the pattern itself
	allFeatures->addFeature(boost::make_shared<PropPFeature>(shared_from_this(), prop, sent_no, patternMatcher->getActiveLanguageVariant()));
	// Add a feature for the ID (if we have one)
	addID(allFeatures);
	// Initialize our score.
	allFeatures->setScore(this->getScore());

	if (_regexPattern != 0) {
		if (prop->getPredHead() == 0) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of bad pred head\n";
			return PatternFeatureSet_ptr();
		}
		RegexPattern_ptr regexPattern = _regexPattern->castTo<RegexPattern>();
		PatternFeatureSet_ptr regexSFS = regexPattern->matchesParseNode(patternMatcher, sent_no, prop->getPredHead()->getHeadPreterm());
		if (regexSFS == 0) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because of regexSFS\n";
			return PatternFeatureSet_ptr();
		}
		allFeatures->addFeatures(regexSFS);
	}

	if (_propModifierPattern != 0) {
		PatternFeatureSet_ptr propModifierSFS = matchesPropModifier(patternMatcher, sent_no, prop);
		if (propModifierSFS == 0) {
			SessionLogger::dbg("BRANDY") << getDebugID() << " Returning empty set because prop modifier SFS\n";
			return PatternFeatureSet_ptr();
		}
		allFeatures->addFeatures(propModifierSFS);
	}

	// fillAllFeatures() will delete elements of i_j_to_sfs and deletes allFeatures if it fails
	allFeatures = fillAllFeatures(req_i_j_to_sfs, opt_i_j_to_sfs, allFeatures, _args, _optArgs,
		_require_one_to_one_argument_mapping, _require_all_arguments_to_match_some_pattern, _allow_many_to_many_mapping);
	if (allFeatures) {
		SessionLogger::dbg("BRANDY") << getDebugID() << " allFeatures score = " << allFeatures->getScore() << " features = " << allFeatures->getNFeatures() << "\n";
	} else {
		SessionLogger::dbg("BRANDY") << getDebugID() << " allFeatures is null\n";
	}
	return allFeatures;

}

PatternFeatureSet_ptr PropPattern::matchesPropModifier(PatternMatcher_ptr patternMatcher, int sent_no, const Proposition *prop) {

	if (_propModifierPattern == 0)
		return PatternFeatureSet_ptr();

	const PropositionSet *ps = patternMatcher->getDocTheory()->getSentenceTheory(sent_no)->getPropositionSet();

	// Get the index of the Mention of this Proposition's <ref> Argument, falling up through sprops
	const Proposition* searchProp = prop;
	int reference_index = -1;
	for (int j = 0; j < searchProp->getNArgs(); j++) {
		Argument *arg = searchProp->getArg(j);
		if (arg->getRoleSym() == Argument::REF_ROLE && arg->getType() == Argument::MENTION_ARG) {
			reference_index = arg->getMentionIndex();
			break;
		}
	}
	if (reference_index < 0)
		return PatternFeatureSet_ptr();
	bool fallThrough = true;
	while (fallThrough) {
		fallThrough = false;
		for (int i = 0; i < ps->getNPropositions(); i++) {
			int new_reference_index = -1;
			const Proposition *newProp = ps->getProposition(i);
			if (newProp == searchProp || newProp == prop)
				// Avoid prop graph cycles as we follow <ref>s
				continue;
			if (newProp->getPredType() != Proposition::SET_PRED)
				// Only fall up through sprops
				continue;

			// Sweep through the arguments of this sprop, retrieving its <ref> Mention and checking
			// if one of its members is the current <ref> Mention
			for (int k = 0; k < newProp->getNArgs(); k++) {
				Argument *arg = newProp->getArg(k);
				if (arg->getRoleSym() == Argument::REF_ROLE && arg->getType() == Argument::MENTION_ARG) {
					new_reference_index = arg->getMentionIndex();
				} else if (arg->getRoleSym() == Argument::MEMBER_ROLE && arg->getType() == Argument::MENTION_ARG && arg->getMentionIndex() == reference_index) {
					searchProp = newProp;
				}
			}

			// If we found a new sprop to fall through, update our <ref> Mention and keep falling up
			if (searchProp == newProp && new_reference_index >= 0) {
				reference_index = new_reference_index;
				fallThrough = true;
				break;
			}
		}
	}

	// Now that we've fallen up to the <ref> Mention, actually run the pattern against props that contain it in an arg
	PatternFeatureSet_ptr bestSFS;
	PropMatchingPattern_ptr propModifierPattern = _propModifierPattern->castTo<PropMatchingPattern>();
	for (int i = 0; i < ps->getNPropositions(); i++) {
		const Proposition *newProp = ps->getProposition(i);
		if (newProp == prop)
			continue;
		for (int k = 0; k < newProp->getNArgs(); k++) {
			Argument *arg = newProp->getArg(k);
			if (arg->getType() == Argument::MENTION_ARG && arg->getMentionIndex() == reference_index &&
				_propModifierRoles.find(arg->getRoleSym()) != _propModifierRoles.end())
			{
				PatternFeatureSet_ptr sfs = propModifierPattern->matchesProp(patternMatcher, sent_no, newProp, true, PropStatusManager_ptr());
				if (sfs) {
					if (bestSFS == 0 || sfs->getScore() > bestSFS->getScore())
						bestSFS = sfs;
				}
			}
		}
	}
	return bestSFS;
}

bool PropPattern::matchesNegation(const std::set<Symbol>& negations, const Proposition *prop) {
	Symbol head = prop->getNegation()->getHeadWord();
	return (negations.find(head) != negations.end());
}

bool PropPattern::matchesAdjective(const std::set<Symbol>& adjectives, PatternMatcher_ptr patternMatcher, int sent_no, const Proposition *prop) {

	// Adjective matching only makes sense for noun propositions
	if (prop->getPredType() != Proposition::NOUN_PRED || prop->getNArgs() == 0)
		return false;

	// The first argument should be the <ref> argument; if it's not, bail
	Argument *firstArg = prop->getArg(0);
	if (firstArg->getRoleSym() != Argument::REF_ROLE || firstArg->getType() != Argument::MENTION_ARG)
		return false;
	int ref_ment_index = firstArg->getMentionIndex();

	// Find all modifier propositions in the set that modify the same mention as the noun prop
	const PropositionSet *ps = patternMatcher->getDocTheory()->getSentenceTheory(sent_no)->getPropositionSet();
	for (int i = 0; i < ps->getNPropositions(); i++) {
		const Proposition *newProp = ps->getProposition(i);
		if (newProp->getPredType() == Proposition::MODIFIER_PRED && newProp->getNArgs() != 0) {
			Argument *newPropFirstArg = newProp->getArg(0);
			if (newPropFirstArg->getMentionIndex() == ref_ment_index &&
				newPropFirstArg->getRoleSym() == Argument::REF_ROLE)
			{
				Symbol prop_adj = newProp->getPredHead()->getHeadWord();
				if (adjectives.find(prop_adj) != adjectives.end())
					return true;
			}
		}
	}

	for (int i = 0; i < prop->getNArgs(); i++) {
		if (prop->getArg(i)->getRoleSym() == Argument::UNKNOWN_ROLE && prop->getArg(i)->getType() == Argument::MENTION_ARG) {
			const Mention *ment = prop->getArg(i)->getMention(patternMatcher->getDocTheory()->getSentenceTheory(sent_no)->getMentionSet());
			Symbol premod_headword = ment->getNode()->getHeadWord();
			if (adjectives.find(premod_headword) != adjectives.end())
				return true;
		}
	}

	return false;
}

void PropPattern::dump(std::ostream &out, int indent) const {
	for (int i = 0; i < indent; i++) out << " ";
	out << "PropPattern (" << Proposition::getPredTypeString(_predicateType) << "):";
	if (!getID().is_null()) out << getID();
	out << std::endl;
	for (int i = 0; i < indent; i++) out << " ";
	out << "  Score: " << _score << "\n";

	std::set<Symbol> emptySet;
	typedef std::pair<const std::set<Symbol>*, const std::set<Symbol>*> WordList;
	typedef std::pair<std::string, WordList> WordListPair;
	std::vector<std::pair<std::string, WordList> > wordLists;
	if (_stem_predicate) {
		wordLists.push_back(std::make_pair("stemmed predicates", std::make_pair(&_predicates, &_predicatePrefixes)));
		wordLists.push_back(std::make_pair("blocked stemmed predicates", std::make_pair(&_blockedPredicates, &_blockedPredicatePrefixes)));
	} else {
		wordLists.push_back(std::make_pair("predicates", std::make_pair(&_predicates, &_predicatePrefixes)));
		wordLists.push_back(std::make_pair("blocked predicates", std::make_pair(&_blockedPredicates, &_blockedPredicatePrefixes)));
	}
	wordLists.push_back(std::make_pair("particles", std::make_pair(&_particles, &emptySet)));
	wordLists.push_back(std::make_pair("adjectives", std::make_pair(&_adjectives, &emptySet)));
	wordLists.push_back(std::make_pair("blocked adjectives", std::make_pair(&_blockedAdjectives, &emptySet)));
	wordLists.push_back(std::make_pair("adverbs or particles", std::make_pair(&_adverbOrParticles, &emptySet)));
	wordLists.push_back(std::make_pair("blocked adverbs or particles", std::make_pair(&_blockedAdverbsOrParticles, &emptySet)));
	wordLists.push_back(std::make_pair("prop modifier roles", std::make_pair(&_propModifierRoles, &emptySet)));
	wordLists.push_back(std::make_pair("negations", std::make_pair(&_negations, &_negationPrefixes)));
	wordLists.push_back(std::make_pair("blocked neagations", std::make_pair(&_blockedNegations, &_blockedNegationPrefixes)));
	wordLists.push_back(std::make_pair("modals", std::make_pair(&_modals, &_modalPrefixes)));
	wordLists.push_back(std::make_pair("blocked modals", std::make_pair(&_blockedModals, &_blockedModalPrefixes)));
	BOOST_FOREACH(const WordListPair &wordListPair, wordLists) {
		const std::string& name = wordListPair.first;
		const std::set<Symbol>* words = wordListPair.second.first;
		const std::set<Symbol>* prefixes = wordListPair.second.second;
		if ((words->size()>0) | (prefixes->size()>0)) {
			for (int i = 0; i < indent; i++) out << " ";
			out << "  " << name << " = {";
			BOOST_FOREACH(Symbol sym, *words) {
				out << sym << " ";
			}
			BOOST_FOREACH(Symbol sym, *prefixes) {
				out << sym << "* ";
			}
			out << "}\n";
		}
	}

	if (!_blockedArgs.empty()) {
		for (int i = 0; i < indent; i++) out << " ";
		out << "  blocked_args = {\n";
		for (size_t j = 0; j < _blockedArgs.size(); j++)
			_blockedArgs[j]->dump(out, indent+4);
		for (int i = 0; i < indent; i++) out << " ";
		out << "}\n";
	}

	if (!_args.empty()) {
		for (int i = 0; i < indent; i++) out << " ";
		out << "  args = {\n";
		for (size_t j = 0; j < _args.size(); j++)
			_args[j]->dump(out, indent+4);
		for (int i = 0; i < indent; i++) out << " ";
		out << "}\n";
	}

	if(!_optArgs.empty()) {
		for(int i =0; i < indent; i++) out << " ";
		out << " opt args = {\n";
		for(size_t j = 0; j < _optArgs.size(); j++)
			_optArgs[j]->dump(out, indent+4);
		for(int i = 0; i < indent; i++) out << " ";
		out << "}\n";
	}
}

/**
 * Redefinition of parent class's virtual method that returns a vector of
 * pointers to PatternReturn objects for a given pattern.
 *
 * @param pointer to vector of pointers to PatternReturn objects for a given pattern
 *
 * @author afrankel@bbn.com
 * @date 2010.10.20
 **/
void PropPattern::getReturns(PatternReturnVecSeq & output) const {
	// Note: this currently does *not* recurse into _regexpPattern.  It is unclear
	// whether that is intentional or not.
	Pattern::getReturns(output);
	for (size_t n = 0; n < _args.size(); ++n) {
		if (_args[n]) {
			_args[n]->getReturns(output);
		}
	}
	for (size_t n = 0; n < _optArgs.size(); ++n) {
		if (_optArgs[n]) {
			_optArgs[n]->getReturns(output);
		}
	}
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif