text:
/**
 * BCL to FASTQ file converter
 * Copyright (c) 2007-2017 Illumina, Inc.
 *
 * This software is covered by the accompanying EULA
 * and certain third party copyright/licenses, and any user of this
 * source file is bound by the terms therein.
 *
 * \file Options.hh
 *
 * \brief Declaration of the program options processing.
 *
 * \author Come Raczy
 * \author Mauricio Varea
 * \author Marek Balint
 */

#ifndef BCL2FASTQ_COMMON_OPTIONS_HH
#define BCL2FASTQ_COMMON_OPTIONS_HH

#include <boost/utility.hpp>
#include <boost/program_options.hpp>

namespace bcl2fastq {

namespace common {

/// \brief Encapsulation of the processing of the command line options.
/// \todo Features: Add config file and environment options.
class Options : private boost::noncopyable
{

public:

    /// \brief Program action.
    struct Action
    {
            enum value_type
            {
                RUN,     ///< Run.
                HELP,    ///< Display help and exit.
                VERSION, ///< Display version and exit.
                ABORT    ///< Abort.
            };
    };

public:

    /// \brief Default constructor.
    Options();

    /// \brief Virtual destructor.
    virtual ~Options() = 0;

private:

    /// \brief Initialize program options.
    void initOptions();

protected:

    /// \brief Template method: initialize named options.
    virtual void initNamedOptions(boost::program_options::options_description &options) = 0;

    /// \brief Template method: initialize unnamed options.
    virtual void initUnnamedOptions(boost::program_options::options_description &options) = 0;

    /// \brief Tmeplate method: initialize positional options.
    virtual void initPositionalOptions(boost::program_options::positional_options_description &options) = 0;

public:

    /// \brief Get program usage help.
    /// \return String containing program usage help.
    std::string usage() const;

protected:

    /// \brief Get program usage prefix.
    /// \return String containing program usage prefix.
    virtual std::string usagePrefix() const = 0;

    /// \brief Get program usage suffix.
    /// \return String containing program usage suffix.
    virtual std::string usageSuffix() const;

public:

    /// \brief Parse command line arguments.
    /// \param argc Number of command line arguments.
    /// \param argv Command line arguments.
    /// \return Action to be taked based on arguments.
    Options::Action::value_type parse(int argc, const char *argv[]);

protected:

    /// \brief Store the options from the sample sheet.
    /// \param vm Options map where the settings are stored.
    virtual void storeSampleSheetSettings(boost::program_options::variables_map &vm) = 0;

    /// \brief Post-process parsed command line arguments.
    /// \param vm Command line arguments to be post-process.
    virtual void postProcess(boost::program_options::variables_map &vm) = 0;

private:

    /// \brief Flag determining whether option description has been initialized.
    bool optionsInitialized_;

    /// \brief Named options.
    boost::program_options::options_description namedOptions_;

    /// \brief Unnamed options.
    boost::program_options::options_description unnamedOptions_;

    /// \brief Positional options.
    boost::program_options::positional_options_description positionalOptions_;
};

/// \brief Output operator for program Action.
/// \param os Output stream.
/// \param a Program action to be output.
/// \return Output stream.
std::ostream& operator<<(std::ostream& os, Options::Action::value_type a);

} // namespace common

} // namespace bcl2fastq

#endif // BCL2FASTQ_COMMON_OPTIONS_HH

ext: hh


text:
#ifndef OMG_DDS_CORE_DETAIL_REF_TRAITS_H_
#define OMG_DDS_CORE_DETAIL_REF_TRAITS_H_

/* Copyright 2010, Object Management Group, Inc.
 * Copyright 2010, PrismTech, Corp.
 * Copyright 2010, Real-Time Innovations, Inc.
 * All rights reserved.
 *
 * 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.
 */

/*
 * This file is non-normative. The implementation is
 * provided only as an example.
 */
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>

#include <dds/core/types.hpp>
#include <dds/core/Exception.hpp>

template <typename T1, typename T2>
struct dds::core::is_base_of : public boost::is_base_of<T1, T2> { };

template <typename T1, typename T2>
struct dds::core::is_same : public boost::is_same<T1, T1> { };

template <typename T>
struct dds::core::smart_ptr_traits
{
    typedef boost::shared_ptr<T> ref_type;
    typedef boost::weak_ptr<T>   weak_ref_type;
};

template <typename TO, typename FROM>
TO dds::core::polymorphic_cast(FROM& from)
{
    typename TO::DELEGATE_REF_T dr =
        boost::dynamic_pointer_cast< typename TO::DELEGATE_T>(from.delegate());
    TO to(dr);

    if(to == dds::core::null)
    {
        throw dds::core::InvalidDowncastError("Attempted invalid downcast.");
    }
    return to;
}
#endif /* OMG_DDS_CORE_DETAIL_REF_TRAITS_H_ */

ext: hpp

max_stars_repo_name: brezillon/opensplice

max_issues_repo_name: brezillon/opensplice

max_forks_repo_name: brezillon/opensplice


text:
//
// MIT License
//
// © ESI Group, 2015
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#include <inendi/PVMapped.h>             // for PVMapped
#include <inendi/PVMappingProperties.h>  // for PVMappingProperties
#include <inendi/PVPlotted.h>            // for PVPlotted, etc
#include <inendi/PVPlottingFilter.h>     // for PVPlottingFilter, etc
#include <inendi/PVPlottingProperties.h> // for PVPlottingProperties
#include <inendi/PVSelection.h>          // for PVSelection
#include <inendi/PVSource.h>             // for PVSource
#include <inendi/PVView.h>               // for PVView

#include <pvkernel/rush/PVFormat.h> // for PVFormat

#include <pvkernel/core/PVColumnIndexes.h>   // for PVColumnIndexes
#include <pvkernel/core/PVDataTreeObject.h>  // for PVDataTreeChild
#include <pvkernel/core/PVLogger.h>          // for PVLOG_DEBUG
#include <pvkernel/core/PVSerializeObject.h> // for PVSerializeObject_p, etc

#include <pvbase/types.h> // for PVCol, PVRow

#include <boost/thread/thread.hpp>

#include <QList>   // for QList
#include <QString> // for QString

#include <algorithm>  // for move, all_of
#include <cassert>    // for assert
#include <cstddef>    // for size_t
#include <cstdint>    // for uint32_t
#include <functional> // for _Mem_fn, mem_fn
#include <list>       // for _List_const_iterator, list
#include <memory>     // for allocator, __shared_ptr
#include <string>     // for string, operator+, etc
#include <vector>     // for vector

Inendi::PVPlotted::PVPlotted(PVMapped& mapped, std::string const& name)
    : PVCore::PVDataTreeChild<PVMapped, PVPlotted>(mapped), _name(name)
{
	PVRush::PVFormat const& format = get_parent<Inendi::PVSource>().get_format();

	for (PVCol i(0); i < format.get_axes().size(); i++) {
		_columns.emplace_back(format, i);
	}
	create_table();
}

Inendi::PVPlotted::PVPlotted(PVMapped& mapped,
                             std::list<Inendi::PVPlottingProperties>&& column,
                             std::string const& name)
    : PVCore::PVDataTreeChild<PVMapped, PVPlotted>(mapped), _columns(std::move(column)), _name(name)
{
	create_table();
}

Inendi::PVPlotted::~PVPlotted()
{
	PVLOG_DEBUG("In PVPlotted destructor\n");
}

int Inendi::PVPlotted::create_table()
{
	const PVCol mapped_col_count = get_nraw_column_count();

	for (size_t i = 0; i < _columns.size(); i++) {
		_plotteds.emplace_back(Inendi::plotting_type, get_row_count());
	}

	_last_updated_cols.clear();
	_minmax_values.resize(mapped_col_count);

	auto const& axes_format = get_parent<Inendi::PVSource>().get_format().get_axes();

	for (PVCol j(0); j < mapped_col_count; j++) {
		auto const& mapping_mode = get_parent<PVMapped>().get_properties_for_col(j).get_mode();
		auto usable_pt = get_properties_for_col(j).get_plotting_filter()->list_usable_type();
		if (not usable_pt.empty() and
		    usable_pt.count(
		        std::make_pair(axes_format[j].get_type().toStdString(), mapping_mode)) == 0) {
			get_properties_for_col(j).set_mode("default");
		}

		if (get_properties_for_col(j).is_uptodate()) {
			continue;
		}
		PVPlottingFilter::p_type mf = get_properties_for_col(j).get_plotting_filter();
		PVPlottingFilter::p_type plotting_filter = mf->clone<PVPlottingFilter>();

		boost::this_thread::interruption_point();

		plotting_filter->operator()(
		    get_parent().get_column(j), get_parent().get_properties_for_col(j).get_minmax(),
		    get_parent<Inendi::PVSource>().get_rushnraw().column(j).invalid_selection(),
		    _plotteds[j].to_core_array<value_type>());

		boost::this_thread::interruption_point();
		get_properties_for_col(j).set_uptodate();
		_last_updated_cols.push_back(j);

		get_col_minmax(_minmax_values[j].min, _minmax_values[j].max, j);
	}

	return 0;
}

void Inendi::PVPlotted::append_plotted()
{
	_columns.emplace_back(PVPlottingProperties("default", PVCore::PVArgumentList()));
	_plotteds.emplace_back(Inendi::plotting_type, get_row_count());

	// update minmax values
	_minmax_values.resize(_columns.size());
	PVCol col(_columns.size()-1);
	get_col_minmax(_minmax_values[col].min, _minmax_values[col].max, col);
}

void Inendi::PVPlotted::delete_plotted(PVCol col)
{
	_columns.erase(std::next(_columns.begin(), col.value()));
	_plotteds.erase(std::next(_plotteds.begin(), col.value()));
	_minmax_values.erase(std::next(_minmax_values.begin(), col.value()));
}

PVRow Inendi::PVPlotted::get_row_count() const
{
	return get_parent<PVSource>().get_row_count();
}

PVCol Inendi::PVPlotted::get_nraw_column_count() const
{
	return get_parent<PVMapped>().get_nraw_column_count();
}

QList<PVCol> Inendi::PVPlotted::get_singleton_columns_indexes()
{
	const PVRow nrows = get_row_count();
	const PVCol ncols = get_nraw_column_count();
	QList<PVCol> cols_ret;

	if (nrows == 0) {
		return cols_ret;
	}

	for (PVCol j(0); j < ncols; j++) {
		const uint32_t* cplotted = get_column_pointer(j);
		const uint32_t ref_v = cplotted[0];
		bool all_same = true;
		for (PVRow i = 1; i < nrows; i++) {
			if (cplotted[i] != ref_v) {
				all_same = false;
				break;
			}
		}
		if (all_same) {
			cols_ret << j;
		}
	}

	return cols_ret;
}

QList<PVCol>
Inendi::PVPlotted::get_columns_indexes_values_within_range(uint32_t min, uint32_t max, double rate)
{
	const PVRow nrows = get_row_count();
	const PVCol ncols = get_nraw_column_count();
	QList<PVCol> cols_ret;

	if (min > max) {
		return cols_ret;
	}

	double nrows_d = (double)nrows;
	for (PVCol j(0); j < ncols; j++) {
		PVRow nmatch = 0;
		const uint32_t* cplotted = get_column_pointer(j);
		for (PVRow i = 0; i < nrows; i++) {
			const uint32_t v = cplotted[i];
			if (v >= min && v <= max) {
				nmatch++;
			}
		}
		if ((double)nmatch / nrows_d >= rate) {
			cols_ret << j;
		}
	}

	return cols_ret;
}

QList<PVCol> Inendi::PVPlotted::get_columns_indexes_values_not_within_range(uint32_t const min,
                                                                            uint32_t const max,
                                                                            double rate)
{
	const PVRow nrows = get_row_count();
	const PVCol ncols = get_nraw_column_count();
	QList<PVCol> cols_ret;

	if (min > max) {
		return cols_ret;
	}

	double nrows_d = (double)nrows;
	for (PVCol j(0); j < ncols; j++) {
		PVRow nmatch = 0;
		const uint32_t* cplotted = get_column_pointer(j);
		for (PVRow i = 0; i < nrows; i++) {
			const uint32_t v = cplotted[i];
			if (v < min || v > max) {
				nmatch++;
			}
		}
		if ((double)nmatch / nrows_d >= rate) {
			cols_ret << j;
		}
	}

	return cols_ret;
}

void Inendi::PVPlotted::get_col_minmax(PVRow& min,
                                       PVRow& max,
                                       PVSelection const& sel,
                                       PVCol col) const
{
	PVRow local_min, local_max;
	uint32_t vmin, vmax;
	vmin = PVPlotted::MAX_VALUE;
	vmax = 0;
	local_min = 0;
	local_max = 0;
	sel.visit_selected_lines(
	    [&](PVRow i) {
		    const uint32_t v = this->get_value(i, col);
		    if (v > vmax) {
			    vmax = v;
			    local_max = i;
		    }
		    if (v < vmin) {
			    vmin = v;
			    local_min = i;
		    }
		},
	    get_row_count());

	min = local_min;
	max = local_max;
}

/******************************************************************************
 * get_col_minmax
 *
 * Use a parallele reduction to compute the indices of the row with min and max
 * value
 *****************************************************************************/

void Inendi::PVPlotted::get_col_minmax(PVRow& min, PVRow& max, PVCol const col) const
{
	uint32_t vmin = PVPlotted::MAX_VALUE;
	uint32_t vmax = 0;
	const PVRow nrows = get_row_count();
// TODO: use the SSE4.2 optimised version here
#pragma omp parallel
	{
		// Define thread local variables for local minmax extraction
		uint32_t local_min = PVPlotted::MAX_VALUE;
		uint32_t local_max = 0;
		PVRow local_min_col = 0;
		PVRow local_max_col = 0;

// Share work among threads
#pragma omp for
		for (PVRow i = 0; i < nrows; i++) {
			const uint32_t v = this->get_value(i, col);
			if (v > local_max) {
				local_max = v;
				local_max_col = i;
			} else if (v < local_min) {
				local_min = v;
				local_min_col = i;
			}
		}

// Perform final reduction. This is not a parallel reduction but it should
// not be really expensive.
// TODO : As it is a two arguments reduction, it can be done using
// OpenMP 3.1 but maybe with custom reduction from OpenMP 4.0
#pragma omp critical
		{
			if (local_min < vmin) {
				vmin = local_min;
				min = local_min_col;
			}
			if (local_max > vmax) {
				vmax = local_max;
				max = local_max_col;
			}
		}
	}
}

PVRow Inendi::PVPlotted::get_col_min_row(PVCol const c) const
{
	assert(c < get_nraw_column_count());
	return _minmax_values[c].min;
}

PVRow Inendi::PVPlotted::get_col_max_row(PVCol const c) const
{
	assert(c < get_nraw_column_count());
	return _minmax_values[c].max;
}

void Inendi::PVPlotted::update_plotting()
{
	create_table();
	_plotted_updated.emit(_last_updated_cols);
}

QList<PVCol> Inendi::PVPlotted::get_columns_to_update() const
{
	QList<PVCol> ret;

	for (PVCol j(0); j < get_nraw_column_count(); j++) {
		if (!get_properties_for_col(j).is_uptodate()) {
			ret << j;
		}
	}

	return ret;
}

bool Inendi::PVPlotted::is_uptodate() const
{
	if (!get_parent().is_uptodate()) {
		return false;
	}
	return std::all_of(_columns.begin(), _columns.end(),
	                   std::mem_fn(&PVPlottingProperties::is_uptodate));
}

std::string Inendi::PVPlotted::export_line(PVRow idx,
                                           const PVCore::PVColumnIndexes& col_indexes,
                                           const std::string sep_char,
                                           const std::string) const
{
	assert(col_indexes.size() != 0);

	std::string line;

	for (PVCol c : col_indexes) {
		line += std::to_string(get_value(idx, c)) + sep_char;
	}

	// Remove last sep_char
	line.resize(line.size() - sep_char.size());

	return line;
}

void Inendi::PVPlotted::serialize_write(PVCore::PVSerializeObject& so) const
{
	so.set_current_status("Saving plotting...");
	QString name = QString::fromStdString(_name);
	so.attribute_write("name", name);

	so.set_current_status("Saving plotting properties...");
	PVCore::PVSerializeObject_p list_prop = so.create_object("properties");

	int idx = 0;
	for (PVPlottingProperties const& prop : _columns) {
		PVCore::PVSerializeObject_p new_obj = list_prop->create_object(QString::number(idx++));
		prop.serialize_write(*new_obj);
	}
	so.attribute_write("prop_count", idx);

	// Read the data colletions
	PVCore::PVSerializeObject_p list_obj = so.create_object("view");
	idx = 0;
	for (PVView const* view : get_children()) {
		PVCore::PVSerializeObject_p new_obj = list_obj->create_object(QString::number(idx++));
		view->serialize_write(*new_obj);
	}
	so.attribute_write("view_count", idx);
}

Inendi::PVPlotted& Inendi::PVPlotted::serialize_read(PVCore::PVSerializeObject& so,
                                                     Inendi::PVMapped& parent)
{
	so.set_current_status("Loading plotting...");
	QString name = so.attribute_read<QString>("name");

	PVCore::PVSerializeObject_p list_prop = so.create_object("properties");

	so.set_current_status("Loading plotting properties...");
	std::list<Inendi::PVPlottingProperties> columns;
	int prop_count = so.attribute_read<int>("prop_count");
	for (int idx = 0; idx < prop_count; idx++) {
		PVCore::PVSerializeObject_p new_obj = list_prop->create_object(QString::number(idx));
		columns.emplace_back(PVPlottingProperties::serialize_read(*new_obj));
	}

	PVPlotted& plotted = parent.emplace_add_child(std::move(columns), name.toStdString());

	// Create the list of view
	PVCore::PVSerializeObject_p list_obj = so.create_object("view");

	int view_count = so.attribute_read<int>("view_count");
	for (int idx = 0; idx < view_count; idx++) {
		PVCore::PVSerializeObject_p new_obj = list_obj->create_object(QString::number(idx));
		Inendi::PVView::serialize_read(*new_obj, plotted);
	}

	return plotted;
}

ext: cpp

max_stars_repo_name: inendi-inspector/inspector

max_issues_repo_name: inendi-inspector/inspector

max_forks_repo_name: inendi-inspector/inspector


text:
/**
 * Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
#include "logdevice/server/locallogstore/LocalLogStoreSettings.h"

#include <boost/program_options.hpp>

#include "logdevice/common/commandline_util_chrono.h"

namespace facebook { namespace logdevice {

void LocalLogStoreSettings::defineSettings(SettingEasyInit& init) {
  using namespace SettingFlag;

  init("local-log-store-path",
       &local_log_store_path,
       "",
       nullptr,
       "path to local log store (if storage node)",
       SERVER | REQUIRES_RESTART,
       SettingsCategory::Storage);
  init("max-in-flight-monitor-requests",
       &max_in_flight_monitor_requests,
       "1",
       [](size_t val) {
         if ((ssize_t)val < 1) {
           throw boost::program_options::error(
               "max-in-flight-monitor-requests must be larger than 0");
         }
       },
       "maximum number of in-flight monitoring requests (e.g. manual "
       "compaction) "
       "posted by the monitoring thread",
       SERVER | REQUIRES_RESTART,
       SettingsCategory::Storage);
  init("max-queued-monitor-requests",
       &max_queued_monitor_requests,
       "32",
       [](size_t val) {
         if ((ssize_t)val <= 0) {
           throw boost::program_options::error(
               "max-queued-monitor-requests must be positive");
         }
       },
       "max number of log store monitor requests buffered in the "
       "monitoring thread queue",
       SERVER | REQUIRES_RESTART,
       SettingsCategory::Storage);
  init("logstore-monitoring-interval",
       &logstore_monitoring_interval,
       "10s",
       [](std::chrono::milliseconds val) {
         if (val.count() <= 0) {
           throw boost::program_options::error(
               "logstore-monitoring-interval should be positive");
         }
       },
       "interval between consecutive health checks on the local "
       "log store",
       SERVER,
       SettingsCategory::Storage);
  init("manual-compact-interval",
       &manual_compact_interval,
       "1h",
       [](std::chrono::seconds val) -> void {
         if (val.count() <= 0) {
           throw boost::program_options::error(
               "manual-compact-interval should be positive");
         }
       },
       "minimal interval between consecutive manual "
       "compactions on log stores"
       "that are out of disk space",
       SERVER,
       SettingsCategory::LogsDB);
  init("free-disk-space-threshold",
       &free_disk_space_threshold,
       "0.2",
       [](double val) -> void {
         if (val <= 0 || val >= 1) {
           throw boost::program_options::error(
               "free-disk-space-threshold should be within "
               "(0, 1)");
         }
       },
       "threshold (relative to total diskspace) of minimal "
       "free disk space"
       " for storage partitions to accept writes. This "
       "should be a fraction "
       "between 0.0 (exclusive) and 1.0 (exclusive). "
       "Storage nodes will reject "
       "writes to partitions with free disk space less "
       "than the threshold in "
       "order to guarantee that compactions can be "
       "performed. Note: this only "
       "applies to RocksDB local storage.",
       SERVER,
       SettingsCategory::Storage);
}

}} // namespace facebook::logdevice


text:
/*!
@file
Defines `boost::hana::unfold_left`.

@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_UNFOLD_LEFT_HPP
#define BOOST_HANA_UNFOLD_LEFT_HPP

#include <boost/hana/fwd/unfold_left.hpp>

#include <boost/hana/append.hpp>
#include <boost/hana/concept/sequence.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/empty.hpp>
#include <boost/hana/first.hpp>
#include <boost/hana/functional/partial.hpp>
#include <boost/hana/optional.hpp>
#include <boost/hana/second.hpp>

namespace boost { namespace hana {
    //! @cond
    template <typename S>
    struct unfold_left_t {
    #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
        static_assert(hana::Sequence<S>::value,
        "hana::unfold_left<S> requires 'S' to be a Sequence");
    #endif

        template <typename State, typename F>
        constexpr auto operator()(State&& state, F&& f) const {
            return unfold_left_impl<S>::apply(
                static_cast<State&&>(state),
                static_cast<F&&>(f)
            );
        }
    };
    //! @endcond

    template <typename S, bool condition>
    struct unfold_left_impl<S, when<condition>> : default_ {
        struct unfold_left_helper {
            template <typename F, typename P>
            constexpr auto operator()(F&& f, P&& p) const {
                return hana::append(
                    unfold_left_impl::apply(
                        hana::first(static_cast<P&&>(p)),
                        static_cast<F&&>(f)
                    ),
                    hana::second(static_cast<P&&>(p))
                );
            }
        };

        template <typename Init, typename F>
        static constexpr auto apply(Init&& init, F&& f) {
            decltype(auto) elt = f(static_cast<Init&&>(init));
            return hana::maybe(empty<S>(),
                hana::partial(unfold_left_helper{}, static_cast<F&&>(f)),
                static_cast<decltype(elt)&&>(elt)
            );
        }
    };
}} // end namespace boost::hana

#endif // !BOOST_HANA_UNFOLD_LEFT_HPP


text:
#include <iostream>
#include <Eigen/Dense>
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>

using namespace Eigen;
namespace py = pybind11;

using RowMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;

Eigen::MatrixXf multMatrix(MatrixXf matriz)
{
     MatrixXf c;
     c = 2*matriz;
     std::cout << "2*matriz =\n" << c << std::endl;

     return c;
}

void multMatrix_Ref(Eigen::Ref<MatrixXf> matriz)
{
     matriz = 2*matriz;
     std::cout << "2*matriz =\n" << matriz << std::endl;
}

void multRowMatrix_Ref(Eigen::Ref<RowMatrixXf> matriz)
{
     matriz = 2*matriz;
     std::cout << "2*matriz =\n" << matriz << std::endl;
}

Eigen::MatrixXf multMatrixByMatrix_Ref(Eigen::Ref<MatrixXf> matriz1, Eigen::Ref<MatrixXf> matriz2)
{

     MatrixXf mult = matriz1 * matriz2.transpose();
     //std::cout << "matriz1*matriz2 =\n" << mult << std::endl;
     return mult;
}

PYBIND11_MODULE(demo, m) {
     m.doc() = "pybind11 example plugin"; // optional module docstring
     m.def("multMatrix", &multMatrix, "Funcion con un argumento",
          py::arg("m"));
     m.def("multMatrixRef", &multMatrix_Ref, "Funcion con un argumento pasado por referencia",
          py::arg("m"));
     m.def("multRowMatrixRef", &multRowMatrix_Ref, "Funcion con un argumento pasado por referencia con rowMajor",
          py::arg("m"));
     m.def("multMatrixByMatrix_Ref", &multMatrixByMatrix_Ref, "Funcion con 2 argumento pasado por referencia",
          py::arg("matriz1"), py::arg("matriz2"));
}

max_stars_repo_name: argos-uach/eigen-demo

max_issues_repo_name: argos-uach/eigen-demo

max_forks_repo_name: argos-uach/eigen-demo


text:
/**
 * This module is intended to provide a python interface to
 * fact-generator, by leveraging the Boost.Python library.
 **/
#include <boost/filesystem.hpp>
#include <boost/python.hpp>
#include "ParseException.hpp"

namespace fs = boost::filesystem;
namespace py = boost::python;

void
pyfactgen(py::list inputFiles, std::string outputDir, std::string delim = "\t")
{
    int length = py::extract<int>(inputFiles.attr("__len__")());
    std::vector<fs::path> files(length);

    // Create list of input files
    for (int i = 0; i < len(inputFiles); ++i) {
        files[i] = py::extract<char const *>(inputFiles[i]);

        // Check file existence
        if (!fs::exists(files[i])) {
            std::stringstream error_stream;
            error_stream << "No such file or directory: "
                         << files[i];

            std::string err_msg = error_stream.str();
            PyErr_SetString(PyExc_IOError, err_msg.c_str());
            boost::python::throw_error_already_set();
            return;
        }
    }

    // Create non-existing directory
    if (!fs::exists(outputDir))
        fs::create_directory(outputDir);

    if (!fs::is_directory(outputDir)) {
        PyErr_SetString(PyExc_ValueError,
                        "Invalid output directory path");
        boost::python::throw_error_already_set();
        return;
    }

    // Remove old contents
    for (fs::directory_iterator end, it(outputDir); it != end; ++it)
        remove_all(it->path());

    // Ensure output directory is empty
    if (!fs::is_empty(outputDir)) {
        PyErr_SetString(PyExc_ValueError,
                        "Output directory not empty");
        boost::python::throw_error_already_set();
        return;
    }

    void factgen2(std::vector<fs::path> files, fs::path outputDir, std::string delim);

    // Run fact generation
    factgen2(files, outputDir, delim);
}

// Translate parse exception to python

PyObject *parseExceptionType = NULL;

void translateParseException(ParseException const &e)
{
    assert(parseExceptionType != NULL);
    py::object pythonExceptionInstance(e);
    PyErr_SetObject(parseExceptionType, pythonExceptionInstance.ptr());
}

// Create thin wrappers for overloaded function

BOOST_PYTHON_FUNCTION_OVERLOADS(pyfactgen_overloads, pyfactgen, 2, 3)

// Path converter

struct path_to_python_str
{
    static PyObject* convert(fs::path const& p)
    {
        return boost::python::incref(
            boost::python::object(p.string()).ptr());
    }
};

// Declare boost python module

BOOST_PYTHON_MODULE(factgen)
{
    using namespace boost::python;

    // register exception
    class_<ParseException>
        parseExceptionClass("ParseException", py::init<fs::path>());

    parseExceptionType = parseExceptionClass.ptr();

    register_exception_translator<ParseException>
        (&translateParseException);

    // register the path-to-python converter
    to_python_converter<fs::path, path_to_python_str>();

    def("run", pyfactgen, pyfactgen_overloads());
}

max_stars_repo_name: TheoKant/cclyzer-souffle

max_issues_repo_name: TheoKant/cclyzer-souffle

max_forks_repo_name: TheoKant/cclyzer-souffle


text:
/**
 *  Copyright (C) 2015 Topology LP
 *
 *  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 <bonefish/native/native_server.hpp>
#include <bonefish/rawsocket/rawsocket_server.hpp>
#include <bonefish/rawsocket/tcp_listener.hpp>
#include <bonefish/rawsocket/uds_listener.hpp>
#include <bonefish/router/wamp_routers.hpp>
#include <bonefish/serialization/wamp_serializers.hpp>
#include <bonefish/serialization/msgpack_serializer.hpp>
#include <bonefish/trace/trace.hpp>
#include <bonefish/websocket/websocket_server.hpp>

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/address.hpp>
#include <memory>
#include <stdlib.h>

// In some cases you may need to integrate bonefish with your application
// such that it is running in the same process space. This serves as a simple
// example of how to use the bonefish library to startup your own instance
// natively. As the library evolves, this example will be updated.

int main(int argc, char** argv)
{
    if (getenv("BONEFISH_TRACE")) {
        bonefish::trace::set_enabled(true);
    }

    boost::asio::io_service io_service;

    std::shared_ptr<bonefish::wamp_routers> routers =
            std::make_shared<bonefish::wamp_routers>();

    std::shared_ptr<bonefish::wamp_router> router =
            std::make_shared<bonefish::wamp_router>(io_service, "default");

    routers->add_router(router);

    std::shared_ptr<bonefish::wamp_serializers> serializers =
            std::make_shared<bonefish::wamp_serializers>();
    serializers->add_serializer(std::make_shared<bonefish::msgpack_serializer>());

    std::shared_ptr<bonefish::native_server> native_server =
            std::make_shared<bonefish::native_server>(io_service, routers);
    native_server->start();

    std::shared_ptr<bonefish::rawsocket_server> rawsocket_server =
            std::make_shared<bonefish::rawsocket_server>(routers, serializers);
    std::shared_ptr<bonefish::uds_listener> uds_listener =
            std::make_shared<bonefish::uds_listener>(io_service, "/tmp/bonefish.sock");
    std::shared_ptr<bonefish::tcp_listener> tcp_listener =
            std::make_shared<bonefish::tcp_listener>(io_service, boost::asio::ip::address(), 8888);

    rawsocket_server->attach_listener(
            std::static_pointer_cast<bonefish::rawsocket_listener>(uds_listener));
    rawsocket_server->attach_listener(
            std::static_pointer_cast<bonefish::rawsocket_listener>(tcp_listener));
    rawsocket_server->start();

    std::shared_ptr<bonefish::websocket_server> websocket_server =
            std::make_shared<bonefish::websocket_server>(io_service, routers, serializers);
    websocket_server->start(boost::asio::ip::address(), 9999);

    io_service.run();

    return 0;
}

max_stars_repo_name: aiwc/extlib-bonefish

max_issues_repo_name: aiwc/extlib-bonefish

max_forks_repo_name: aiwc/extlib-bonefish


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

#include <cmath>
#include <Eigen/Geometry>
#include <boost/format.hpp>
#include <comma/base/exception.h>
#include <comma/math/compare.h>
#include "../angle.h"
#include "coordinates.h"
#include <iomanip>

namespace {

    static const double eighty_degrees = 80 * M_PI / 180.0;

    static const double scaled_cos_eighty_degrees = 2.0 / M_PI * std::cos( eighty_degrees );

    bool precise_is_far( const snark::spherical::coordinates & l, const snark::spherical::coordinates & r, double _epsilon )
    {
        return Eigen::AngleAxis< double >( Eigen::Quaternion< double >::FromTwoVectors( l.to_cartesian(), r.to_cartesian() ) ).angle() > _epsilon;
    }

    bool is_far( const snark::spherical::coordinates & l, const snark::spherical::coordinates & r, double _epsilon )
    {
        // for very short arcs skip shortcuts and enforce thorough comparison because of numerical stability issues in Eigen
        // the actual value is about 6 m / earth radius; enough to make AngleAxis::angle() non-zero
        double threshold = std::max( snark::spherical::coordinates::epsilon, _epsilon );
        // make quick decisions first; for latitude shortcut no explanations needed
        if ( std::abs( l.latitude - r.latitude ) > threshold ) { return true; }
        double delta_longitude = std::abs( l.longitude - r.longitude );
        // nearly 360 delta means very close; take the shorter of the two possible arcs
        delta_longitude = delta_longitude > M_PI ? 2 * M_PI - delta_longitude : delta_longitude;
        // longitude shortcut:
        //     ignore near-Pole regions
        //     take a lower limit on great circle arc length:
        //         the arc at the higher (by modulo) of the two latitudes is shorter than the real arc (lower estimate)
        //             proof not given here; differentiate the exact expression by one of the latitudes; the derivative sign is
        //             defined by the other latitude: negative in the Northern hemisphere, positive in the Southern; therefore,
        //             if the fixed latitude (not the one being differentiated upon) is chosen as the max by modulo, the function
        //             may only increase as the other latitude moves either South or North, respectively
        //         for the same latitudes, use the lower estimate of the great circle arc length:
        //             exact length = 2 * asin( cos(latitude) * sin( delta_longitude / 2 ) )
        //             estimates: asin(x) >= x for any x in [0, 1]
        //                        sin(y) >= 2/pi * y for any y in [0, pi/2]
        //             thus exact length >= 2 cos(latitude) * sin( delta_longitude / 2 ) >= cos(latitude) * 2/pi * delta_longitude >= cos(80 degrees) * 2/pi * delta_longitude
        //     if the lower limit is above the threshold, the real arc length is above the threshold as well
        double max_latitude = std::max( std::abs( l.latitude ), std::abs( r.latitude ) );
        if ( max_latitude < eighty_degrees && delta_longitude * scaled_cos_eighty_degrees > threshold ) { return true; }
        // shortcuts failed, do lengthy computations
        return precise_is_far( l, r, threshold );
    }
}

namespace snark { namespace spherical {

const double coordinates::epsilon = 1e-6;

bool coordinates::operator==( const coordinates& rhs ) const
{
    return !is_far( *this, rhs, epsilon );
}

bool coordinates::is_near( const coordinates& c, double epsilon ) const
{
    return !is_far( *this, c, epsilon );
}

bool coordinates::is_near( const coordinates & l, const coordinates & r, double _epsilon )
{
    return !is_far( l, r, _epsilon );
}

/// limits longitude to [-PI, PI)
static double limit( const double longitude )
{
    // todo: this is just a quick patch, not a real fix; what if longitude equals e.g. -3*M_PI?
    // todo: seriously quick and dirty, to fix anti merridian crossing
    return longitude < -M_PI ? longitude + 2 * M_PI : longitude >= M_PI ? longitude - 2 * M_PI : longitude;
}

coordinates::coordinates( const double latitude, const double longitude ) : latitude( latitude ), longitude( limit( longitude ) )
{
}

coordinates::coordinates( const snark::bearing_elevation& be ) : latitude( be.elevation() ), longitude( limit( be.bearing() ) )
{
}

coordinates::coordinates( const Eigen::Vector3d& xyz )
{
    snark::range_bearing_elevation rbe( xyz );
    latitude = rbe.elevation();
    longitude = limit( rbe.bearing() );
}

Eigen::Vector3d to_navigation_frame( const coordinates& c, const Eigen::Vector3d& v )
{
    const Eigen::Matrix3d& r1 = Eigen::AngleAxis< double >( -c.longitude, Eigen::Vector3d( 0, 0, 1 ) ).toRotationMatrix();
    const Eigen::Matrix3d& r2 = Eigen::AngleAxis< double >( c.latitude + M_PI / 2, Eigen::Vector3d( 0, 1, 0 ) ).toRotationMatrix();
    return r2 * r1 * v;
}

coordinates& coordinates::operator+=( const coordinates& rhs )
{
    double d = latitude + rhs.latitude;
    static const double epsilon = 0.00005;
    if( comma::math::equal( d, M_PI / 2, epsilon ) ) { d = M_PI / 2; }
    else if( comma::math::equal( d, -M_PI / 2, epsilon ) ) { d = -M_PI / 2; }
    else if( d > M_PI / 2 || d < -M_PI / 2 ) { COMMA_THROW( comma::exception, "adding " << ( latitude * 180 / M_PI ) << " and " << ( rhs.latitude * 180 / M_PI ) << " gives invalid latitude of " << ( d * 180 / M_PI ) << " degress" ); }
    latitude = d;
    longitude += rhs.longitude;
    while( longitude < -M_PI ) { longitude += 2 * M_PI; } // brutal, but mod() is slower in most cases, i think
    while( this->longitude >= M_PI ) { longitude -= 2 * M_PI; } // brutal, but mod() is slower in most cases, i think
    return *this;
}

coordinates::operator std::string() const
{
    const std::pair< double, double >& c = to_degrees();
    return (boost::format("%.2f") % c.first ).str() + "," + (boost::format("%.2f") % c.second).str();
}

bool coordinates::is_near( const Eigen::Vector3d& c, double _epsilon ) const
{
    return ( to_cartesian() - c ).lpNorm<Eigen::Infinity>() < _epsilon;
}

coordinates coordinates::from_degrees(double latitude, double longitude)
{
    return coordinates( snark::math::radians( snark::math::degrees( latitude ) ).value,
                        snark::math::radians( snark::math::degrees( longitude ) ).value );
}

std::pair< double, double > coordinates::to_degrees() const
{
    return std::make_pair( snark::math::degrees( snark::math::radians( latitude ) ).value
                         , snark::math::degrees( snark::math::radians( longitude ) ).value );
}

} } // namespace snark { namespace spherical {

max_stars_repo_name: mission-systems-pty-ltd/snark

max_issues_repo_name: NEU-LC/snark

max_forks_repo_name: NEU-LC/snark


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

#ifndef _SIRIKATA_TCPSST_MULTIPLEXED_SOCKET_HPP_
#define _SIRIKATA_TCPSST_MULTIPLEXED_SOCKET_HPP_

#include <sirikata/core/util/SerializationCheck.hpp>
#include <boost/thread.hpp>
#include "TCPSSTDecls.hpp"
#include "TCPStream.hpp"

namespace Sirikata {
namespace Network {

class ASIOReadBuffer;
class ASIOSocketWrapper;

class MultiplexedSocket:public SelfWeakPtr<MultiplexedSocket>, public SerializationCheck {
public:
    friend class ASIOReadBuffer;
    class RawRequest {
    public:
        bool unordered;
        bool unreliable;
        Stream::StreamID originStream;
        Chunk * data;

        uint32 size() const {
            return data->size();
        }
    };
    enum SocketConnectionPhase{
        PRECONNECTION,
        WAITCONNECTING,//need to fetch the lock, but about to connect
        CONNECTED,
        DISCONNECTED
    };
private:

//Begin Members//

    ///ASIO strand which guarantees serialized callbacks
    IOStrand* mIO;
    ///a vector of ASIO sockets (wrapped in with a simple send-full-packet abstraction)
    std::vector<ASIOSocketWrapper> mSockets;
    ///This callback is called whenever a newly encountered StreamID is picked up
    Stream::SubstreamCallback mNewSubstreamCallback;
    typedef std::tr1::unordered_map<Stream::StreamID,TCPStream::Callbacks*,Stream::StreamID::Hasher> CallbackMap;
	///Workaround for VC8 bug that does not define std::pair<Stream::StreamID,Callbacks*>::operator=
    class StreamIDCallbackPair{
    public:
        Stream::StreamID mID;
        TCPStream::Callbacks* mCallback;
        StreamIDCallbackPair(Stream::StreamID id,TCPStream::Callbacks* cb):mID(id) {
            mCallback=cb;
        }
        std::pair<Stream::StreamID,TCPStream::Callbacks*> pair() const{
           return std::pair<Stream::StreamID,TCPStream::Callbacks*>(mID,mCallback);
        }
    };
    /// these next items (mCallbackRegistration, mNewRequests, mSocketConnectionPhase) are synced together take the lock, check for preconnection,,, if connected, don't take lock...otherwise take lock and push data onto the new requests queue
    static boost::mutex sConnectingMutex;
    ///list of packets that must be sent before mSocketConnectionPhase switches to CONNECTION
    SizedThreadSafeQueue<RawRequest>* mNewRequests;
    ///must be set to PRECONNECTION when items are being placed on mNewRequests queue and WAITCONNECTING when it is emptying the queue (with lock held) and finally CONNECTED when the user can send directly to the socket.  DISCONNECTED must be set as soon as the socket fails to write or read
    volatile SocketConnectionPhase mSocketConnectionPhase;
    ///This is a list of items for callback registration so that when packets are received by those streamIDs the appropriate callback may be called
    std::deque<StreamIDCallbackPair> mCallbackRegistration;
    ///a map of ID to callback, only to be touched by the io reactor thread
    CallbackMap mCallbacks;
    ///Whether the streams are zero delimited and in a base64 encoding (useful for interaction with web sockets)
    TCPStream::StreamType mStreamType;
    ///a map from StreamID to count of number of acked close requests--to avoid any unordered packets coming in
    std::tr1::unordered_map<Stream::StreamID,unsigned int,Stream::StreamID::Hasher>mAckedClosingStreams;
    ///a set of StreamIDs to hold the streams that were requested closed but have not been acknowledged, to prevent received packets triggering NewStream callbacks as if a new ID were received
    std::tr1::unordered_set<Stream::StreamID,Stream::StreamID::Hasher>mOneSidedClosingStreams;
#define ThreadSafeStack ThreadSafeQueue //FIXME this can be way more efficient
    ///The highest streamID that has been used for making new streams on this side
    AtomicValue<uint32> mHighestStreamID;
    ///actually free stream IDs that will not be sent out until recalimed by this side
    ThreadSafeStack<Stream::StreamID>mFreeStreamIDs;
#undef ThreadSafeStack

//Begin helper functions//

    ///Copies items from newcallback to mCallbacks: must be called from the single io thread so no one would be looking to call the callbacks at the same time
    void ioReactorThreadCommitCallback(StreamIDCallbackPair& newcallback);
    ///reads the current list of id-callback pairs to the registration list and if setConectedStatus is set, changes the status of the overall MultiplexedSocket at the same time
    bool CommitCallbacks(std::deque<StreamIDCallbackPair> &registration, SocketConnectionPhase status, bool setConnectedStatus=false);

    ///Returns the least busy stream upon which unordered data may be piled. It will always favor preferred stream if that is less busy
    size_t leastBusyStream(size_t preferredStream);
    /**
     *chance in the current load that an unreliable packet may be dropped
     * (due to busy queues, etc).
     * \returns drop chance which must be less than 1.0 and greater or equal to 0.0
     */
    float dropChance(const Chunk*data,size_t whichStream);
    /**
     *  sends bytes to the network directly.
     *  assumes that the mSocketConnectionPhase in the CONNECTED state
     */
    static bool sendBytesNow(const MultiplexedSocketPtr& thus,const RawRequest&data, bool force);
    /**
     * Calls the connected callback with the succeess or failure status. Sets status while holding the sConnectingMutex lock so that after that point no more Connected responses
     * will be sent out. Then inserts the registrations into the mCallbacks map during the ioReactor thread.
     */
    void connectionFailureOrSuccessCallback(SocketConnectionPhase status, Stream::ConnectionStatus reportedProblem, const std::string&errorMessage=std::string());
   /**
    * The connection failed before any sockets were established (or as a helper function after they have been cleaned)
    * This function will call all substreams disconnected methods
    */
    void connectionFailedCallback(const std::string& error);
   /**
    * The connection failed before any sockets were established (or as a helper function after they have been cleaned)
    * This function will call all substreams disconnected methods
    */
    void hostDisconnectedCallback(const std::string& error);
public:
    TCPStream::StreamType getStreamType() const {
        return mStreamType;
    }
    ///public io service accessor for new stream construction
    IOStrand* getStrand() {return mIO;}

    /**
     * Sends a packet telling the other side that this stream is closed (or alternatively if its a closeAck that the close request was received and no further packets for that
     * stream will be sent with that streamID
     */
    static void closeStream(const MultiplexedSocketPtr& thus,const Stream::StreamID&sid,TCPStream::TCPStreamControlCodes code=TCPStream::TCPStreamCloseStream);

    /**
     * Either sends or queues bytes in the data request depending on the connection state
     * if the state is not connected then it must take a lock and place them on the mNewRequests queue
     */
    static bool sendBytes(const MultiplexedSocketPtr& thus,const RawRequest&data, unsigned int maxSendQueueSize=2147483647);
    /**
     * Finds if there is enough space to enqueue the particular bytes at this moment.
     */
    bool canSendBytes(Stream::StreamID origin,size_t dataSize)const;
    /**
     * Adds callbacks onto the queue of callbacks-to-be-added
     * Returns true if the callbacks will be actually used or false if the socket is already disconnected
     */
    SocketConnectionPhase addCallbacks(const Stream::StreamID&sid, TCPStream::Callbacks* cb);
    ///function that searches mFreeStreamIDs or uses the mHighestStreamID to find the next unused free stream ID
    Stream::StreamID getNewID();
    ///gets the first stream ID for a newly created stream
    static Stream::StreamID getFirstStreamID(bool connector);
    ///Constructor for a connecting stream
    MultiplexedSocket(IOStrand*io, const Stream::SubstreamCallback&substreamCallback, TCPStream::StreamType type);
    ///Constructor for a listening stream with a prebuilt connection of ASIO sockets
    MultiplexedSocket(IOStrand*io, const UUID&uuid, const Stream::SubstreamCallback &substreamCallback, TCPStream::StreamType type);
    ///call after construction to setup mSockets
    void initFromSockets(const std::vector<TCPSocket*>&sockets, size_t max_send_buffer_size);
    ///Sends the protocol headers to all ASIO socket wrappers when a known fully open connection has been listened for
    static void sendAllProtocolHeaders(const MultiplexedSocketPtr& thus, const std::string&origin, const std::string&host, const std::string&port, const std::string&resource_name, const std::string&subprotocol,bool doSendSubProtocol, const std::map<TCPSocket*,std::string>& response, TCPStream::StreamType streamType);
    ///erase all sockets and callbacks since the refcount is now zero;
    ~MultiplexedSocket();
    ///a stream that has been closed and the other side has agreed not to send any more packets using that ID
    void shutDownClosedStream(unsigned int controlCode,const Stream::StreamID &id);
    /**
     * Process an entire packet when received from the IO reactor thread.
     * Control packets come in on Stream::StreamID() and others should be directed
     * to the appropriate callback
     */
    void receiveFullChunk(unsigned int whichSocket, Stream::StreamID id, Chunk&newChunk, const Stream::PauseReceiveCallback& pauseReceive);

    /**
     * Process a socket-level ping. If expectPong, send a pong as a reply.
     */
    void receivePing(unsigned int whichSocket, MemoryReference data, bool isPong);

   /**
    * The a particular socket's connection failed
    * This function will call all substreams disconnected methods
    */
    void connectionFailedCallback(unsigned int whichSocket, const std::string& error);
   /**
    * The connection failed to connect before any sockets had been established (ex: host not found)
    * This function will call all substreams disconnected methods
    */
    template <class ErrorCode> void connectionFailedCallback(const ErrorCode& error) {
        connectionFailedCallback(error.message());
    }
   /**
    * The a particular socket's connection failed
    * This function will call all substreams disconnected methods
    */
    template <class ErrorCode> void connectionFailedCallback(unsigned int whichSocket, const ErrorCode& error) {
        connectionFailedCallback(whichSocket,error.message());
    }
   /**
    * The a particular socket's connection failed
    * This function will call all substreams disconnected methods
    */
    template <class ErrorCode> void connectionFailedCallback(const ASIOSocketWrapper* whichSocket, const ErrorCode &error) {
        unsigned int which=0;
        for (std::vector<ASIOSocketWrapper>::iterator i=mSockets.begin(),ie=mSockets.end();i!=ie;++i,++which) {
            if (&*i==whichSocket)
                break;
        }
        connectionFailedCallback(which==mSockets.size()?0:which,error.message());
    }

   /**
    * The a particular socket's connection failed
    * This function will call all substreams disconnected methods
    */
    void hostDisconnectedCallback(unsigned int whichSocket, const std::string& error);
   /**
    * The a particular socket's connection failed
    * This function will call all substreams disconnected methods
    */
    template <class ErrorCode> void hostDisconnectedCallback(unsigned int whichSocket, const ErrorCode& error) {
        hostDisconnectedCallback(whichSocket,error.message());
    }
   /**
    * The a particular socket's connection failed
    * This function will call all substreams disconnected methods
    */
    template <class ErrorCode> void hostDisconnectedCallback(const ASIOSocketWrapper* whichSocket, const ErrorCode &error) {
        unsigned int which=0;
        for (std::vector<ASIOSocketWrapper>::iterator i=mSockets.begin(),ie=mSockets.end();i!=ie;++i,++which) {
            if (&*i==whichSocket)
                break;
        }
        hostDisconnectedCallback(which==mSockets.size()?0:which,error.message());
    }

    static void ioReactorThreadResumeRead(const MultiplexedSocketWPtr&, Stream::StreamID id);
    static void ioReactorThreadPauseSend(const MultiplexedSocketWPtr& mp, Stream::StreamID id);

   /**
    * The a particular established a connection:
    * This function will call all substreams connected methods
    */
    void connectedCallback() {
        connectionFailureOrSuccessCallback(CONNECTED,Stream::Connected);
    }
    void unpauseSendStreams(const std::vector<Stream::StreamID>&toUnpause);

    /**
     *  Connect a newly constructed MultiplexedSocket to a given address
     * \param address is a protocol-agnostic string of endpoint and service ID
     * \param numSockets indicates how many TCP sockets should manage the
     *        orderlessness of this connection
     * \param maxEnqueuedSendSize the maximum number of enqueued bytes for
     *        sending that have not been committed to the underlying network
     *        implementation.
     * \param noDelay if true, disables Nagle's algorithm on the underling
     *        sockets.
     * \param kernelSendBufferSize the size of the buffer allocated for
     *        sending data in the underlying networking implementation. Note
     *        that this is additional space on top of that allocated by this
     *        library.
     * \param kernelReceiveBufferSize the size of the buffer allocated for
     *        receiving data in the underlying networking implementation. Note
     *        that this is additional space on top of that allocated by this
     *        library.
     */
    void connect(const Address&address, unsigned int numSockets, size_t maxEnqueuedSendSize, bool noDelay, unsigned int kernelSendBufferSize, unsigned int kernelReceiveBufferSize);

/**
 *  Prepare a socket for an outbound connection.
 *  After this call messages may be queued and number of redundant connections set
 *  Additionally this socket may now be cloned
 */
    void prepareConnect(unsigned int numSockets, size_t maxEnqueuedSendSize, bool noDelay, unsigned int kernelSendBufferSize, unsigned int kernelReceiveBufferSize);

    unsigned int numSockets() const {
        return mSockets.size();
    }
    ASIOSocketWrapper&getASIOSocketWrapper(unsigned int whichSocket){
        return mSockets[whichSocket];
    }
    const ASIOSocketWrapper&getASIOSocketWrapper(unsigned int whichSocket)const{
        return mSockets[whichSocket];
    }

    Address getRemoteEndpoint(Stream::StreamID id)const ;
    Address getLocalEndpoint(Stream::StreamID id)const ;

    // -- Statistics
    Duration averageSendLatency() const;
    Duration averageReceiveLatency() const;
};

} // namespace Network
} // namespace Sirikata

#endif //_SIRIKATA_TCPSST_MULTIPLEXED_SOCKET_HPP_

max_stars_repo_name: sirikata/sirikata

max_issues_repo_name: sirikata/sirikata

max_forks_repo_name: sirikata/sirikata


text:
/*

Copyright (c) 2006, Arvid Norberg & Daniel Wallin
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef REFRESH_050324_HPP
#define REFRESH_050324_HPP

#include <vector>

#include <libtorrent/kademlia/traversal_algorithm.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/observer.hpp>
#include <libtorrent/kademlia/msg.hpp>

#include <boost/function.hpp>

namespace libtorrent { namespace dht
{

#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(refresh);
#endif

class routing_table;
class rpc_manager;

class refresh : public traversal_algorithm
{
public:
	typedef std::vector<node_entry>::iterator InIt;
	typedef boost::function<void()> done_callback;

	void ping_reply(node_id id);
	void ping_timeout(node_id id, bool prevent_request = false);

	refresh(node_impl& node, node_id target, InIt first, InIt last
		, done_callback const& callback);

	virtual char const* name() const { return "refresh"; }

private:

	void done();
	void invoke(node_id const& id, udp::endpoint addr);

	void invoke_pings_or_finish(bool prevent_request = false);

	int m_max_active_pings;
	int m_active_pings;

	done_callback m_done_callback;

	std::vector<result>::iterator m_leftover_nodes_iterator;
};

class refresh_observer : public observer
{
public:
	refresh_observer(
		boost::intrusive_ptr<refresh> const& algorithm
		, node_id self)
		: observer(algorithm->allocator())
		, m_algorithm(algorithm)
		, m_self(self)
	{}
	~refresh_observer();

	void send(msg& m)
	{
		m.info_hash = m_algorithm->target();
	}

	void timeout();
	void reply(msg const& m);
	void abort() { m_algorithm = 0; }

private:
	boost::intrusive_ptr<refresh> m_algorithm;
	node_id const m_self;
};

class ping_observer : public observer
{
public:
	ping_observer(
		boost::intrusive_ptr<refresh> const& algorithm
		, node_id self)
		: observer(algorithm->allocator())
		, m_self(self)
		, m_algorithm(algorithm)
	{}
	~ping_observer();

	void send(msg& p) {}
	void timeout();
	void reply(msg const& m);
	void abort() { m_algorithm = 0; }

private:
	node_id const m_self;
	boost::intrusive_ptr<refresh> m_algorithm;
};

inline refresh::refresh(
	node_impl& node
	, node_id target
	, refresh::InIt first
	, refresh::InIt last
	, done_callback const& callback)
	: traversal_algorithm(node, target, first, last)
	, m_max_active_pings(10)
	, m_active_pings(0)
	, m_done_callback(callback)
{
	boost::intrusive_ptr<refresh> self(this);
	add_requests();
}

} } // namespace libtorrent::dht

#endif // REFRESH_050324_HPP

max_stars_repo_name: CarysT/medusa

max_issues_repo_name: CarysT/medusa

max_forks_repo_name: CarysT/medusa


text:
//          Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_CTX_ALL_H
#define BOOST_CTX_ALL_H

#include <boost/context/fcontext.hpp>
#include <boost/context/stack_allocator.hpp>
#include <boost/context/stack_utils.hpp>

#endif // BOOST_CTX_ALL_H


text:
#pragma once

#include <boost/serialization/saci/node_base.hpp>
#include <boost/serialization/saci/branch_impl.hpp>
#include <boost/serialization/saci/branches_impl.hpp>
#include <boost/serialization/saci/leaves_impl.hpp>
#include <boost/serialization/saci/root.hpp>

max_stars_repo_name: ricardocosme/saci

max_issues_repo_name: ricardocosme/saci

max_forks_repo_name: ricardocosme/saci


text:
#include "matrix.hpp"
#include "generator_options.hpp"
#include <ctime>
#include <cstdlib>
#include <cassert>
#include <cmath>
#include <iostream>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/io.hpp>

template<typename MatrixType>
void populate(MatrixType& matrix, const std::size_t bandwidth, const double density, const bool symmetric)
{
  const double weight = 1e15;
  assert(matrix.size1() == matrix.size2());

  // Place random values with appropriate bandwidth
  for(std::size_t row=0; row<matrix.size1(); ++row)
  {
    for(std::size_t col=std::max(static_cast<std::size_t>(0), row-bandwidth); col<std::min(matrix.size2(), row+bandwidth+1); ++col)
    {
      if (drand48 () < density)
      {
        const double value = drand48() * weight;
        matrix(row, col) += value;

        if (symmetric)
          matrix(col, row) += value;
      }
    }
  }

  // Make diagonally dominant
  for (typename MatrixType::iterator1 rowIter = matrix.begin1(); rowIter != matrix.end1(); ++rowIter)
  {
    const typename MatrixType::value_type weight = 1e1;  // arbitrary value to increase the sum by to make strictly dominant
    typename MatrixType::value_type absSum;
    for(typename MatrixType::iterator2 colIter(rowIter.begin()); colIter != rowIter.end(); ++colIter)
    {
      if (colIter.index1() != colIter.index2())
        absSum += std::fabs(*colIter);
    }
    matrix(rowIter.index1(), rowIter.index1()) = absSum + weight;
  }
}

int main(int argc, char* argv[])
{
  GeneratorOptions options;
  options.processOptions(argc, argv);
  srand48(time(NULL));

  const unsigned size = options.getSize();
  const bool symmetric = options.getSymmetric();

  boost::numeric::ublas::mapped_matrix<double> matrix(size, size);

  populate(matrix, size/4, 4.0/size, symmetric);

  CCSMatrix<double> csrMatrix(matrix, symmetric);
  std::cout << "Generating " << (symmetric ? "a symmetric" : "an unsymmetric") << " matrix of size " << size << "." << std::endl;
  std::cout << "Number of non-zeros in generated matrix: " << csrMatrix.nnz() << "." << std::endl;

  csrMatrix.writeToFile(options.getOutputFile());
}

max_stars_repo_name: FrancisRussell/desola

max_issues_repo_name: FrancisRussell/desola

max_forks_repo_name: FrancisRussell/desola


text:
//
// Created by chiliu on 5/12/18.
//

#include "../include/myslam/VisualOdometry.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <algorithm>
#include <boost/timer.hpp>

namespace myslam
{
    VisualOdometry::VisualOdometry():
        state_(INITIALIZING), ref_(nullptr), curr_(nullptr), map_(new Map), num_lost_(0), num_inliers_(0)
            //, matcher_flann_( new cv::flann::LshIndexParams (5,10,2))
    {
        num_of_features_        = Config::get<int> ("number_of_features");
        scale_factor_           = Config::get<double> ("scale_factor");
        level_pyramid_          = Config::get<int> ("level_pyramid");
        match_ratio_            = Config::get<float> ("match_ratio");
        max_num_lost_           = Config::get<float> ("max_num_lost");
        min_inliers_            = Config::get<int> ("min_inliers");
        key_frame_min_rot       = Config::get<double> ("keyframe_rotation");
        key_frame_min_trans     = Config::get<double> ("keyframe_translation");
        map_point_erase_ratio_  = Config::get<double> ("map_point_erase_ratio");
        orb_ = cv::ORB::create( num_of_features_, scale_factor_, level_pyramid_ );
    }

    VisualOdometry::~VisualOdometry()
    {

    }

    bool VisualOdometry::addFrame(Frame::Ptr frame)
    {
        switch ( state_ )
        {
            case INITIALIZING:
            {
                state_ =OK;
                curr_ = ref_ = frame;
                map_->insertKeyFrame( frame );
                // extract features from first frame
                extractKeyPoints();
                computeDescriptors();
                // compute the 3d position of features in ref frame
                setRef3DPoints();
                break;
            }
            case OK:
            {
                curr_ = frame;
                extractKeyPoints();                 // orb->detect
                computeDescriptors();               // orb->compute
                featureMatching();                  // calculate good matches
                poseEstimationPnP();                // calculate T_c_r_estimated_
                if (checkEstimatePose() == true )   // this is a good estimation
                {
                    // T_c_w = T_c_r * T_r_w
                    curr_->T_c_w_ = T_c_r_estimated_ * ref_->T_c_w_;
                    ref_ = curr_;
                    setRef3DPoints();
                    num_lost_ = 0;
                    if ( checkKeyFrame() == true )  // this is a key frame
                    {
                        addKeyFrame();
                    }
                }
                else    // bad estimation due to various reasons
                {
                    num_lost_++;
                    if ( num_lost_ > max_num_lost_ )
                    {
                        state_ = LOST;
                    }
                    return false;
                }
                break;
            }
            case LOST:
            {
                cout<<" vo has lost."<<endl;
                break;
            }
        }
        return true;
    }

    void VisualOdometry::extractKeyPoints()
    {
        orb_->detect ( curr_->color_, keypoints_curr_);
    }

    void VisualOdometry::computeDescriptors()
    {
        orb_->compute ( curr_->color_, keypoints_curr_, descriptors_curr_);
    }

    void VisualOdometry::featureMatching()
    {
        // match desp_ref and desp_curr, use OpencCV's burte force match
        vector<cv::DMatch> matches;
        cv::BFMatcher matcher (cv::NORM_HAMMING);
        matcher.match( descriptors_ref_, descriptors_curr_, matches );

        // select good matches
        //// find minimum distance in all matches
        float min_dis = std::min_element(
                matches.begin(), matches.end(),
                []( const cv::DMatch& m1, const cv::DMatch& m2 )
                {
                    return m1.distance < m2.distance;
                }
        )->distance;
        ////  store good matches
        feature_matches_.clear();
        for( cv::DMatch& m: matches )
        {
            if ( m.distance < max<float>( min_dis * match_ratio_, 30.0 ) )
            {
                feature_matches_.push_back(m);
            }
        }
        cout<< " good matches: "<<feature_matches_.size()<<endl;

    }

    void VisualOdometry::setRef3DPoints()
    {
        // select the features with depth measurements
        pts_3d_ref_.clear();
        descriptors_ref_ = Mat();
        for ( size_t i=0; i<keypoints_curr_.size(); i++)
        {
            // calculate depth of every keypoint in current frame
            double d = ref_->findDepth(keypoints_curr_[i]);
            if ( d > 0)
            {
                // 2D-->3D use eigen to calculate camera coordinate points
                Vector3d p_cam = ref_->camera_->pixel2camera(
                        Vector2d(keypoints_curr_[i].pt.x, keypoints_curr_[i].pt.y),d
                );
                // eigen --> opencv, save opencv 3D point
                pts_3d_ref_.push_back( cv::Point3f(p_cam(0,0), p_cam(1,0), p_cam(2,0)));
                descriptors_ref_.push_back( descriptors_curr_.row(i));
            }
        }

    }

    void VisualOdometry::poseEstimationPnP()
    {
        // construct 3d->2d obersvations
        //// prepare 3d and 2d points
        vector<cv::Point3f> pts3d;
        vector<cv::Point2f> pts2d;

        for (cv::DMatch m: feature_matches_)
        {
            pts3d.push_back(pts_3d_ref_[m.queryIdx]);
            pts2d.push_back(keypoints_curr_[m.trainIdx].pt);
        }
        cout<<"last pts_3d_ref_[m.queryIdx]: "<<pts3d[pts3d.size()-1]<<endl;
        cout<<"last keypoints_curr_[m.trainIdx].pt: "<<pts2d[pts2d.size()-1]<<endl;
        cout<<"pts3d.size(): "<<pts3d.size()<<endl;
        cout<<"pts2d.size(): "<<pts2d.size()<<endl;

        //// prepare intrinsic matrix of camera
        Mat K = (cv::Mat_<double>(3,3)<<
            ref_->camera_->fx_, 0, ref_->camera_->cx_,
            0, ref_->camera_->fy_, ref_->camera_->cy_,
            0,0,1
        );

//        cout<<" K : "<<endl;
//        cout<<ref_->camera_->fx_<<endl;
//        cout<<ref_->camera_->fy_<<endl;
//        cout<< ref_->camera_->cx_<<endl;
//        cout<<ref_->camera_->cy_<<endl;
//        cout<<K<<endl;

        //// prepare output of  pnp_ransac
        //// rotation vector, translation vector, Output vector that contains indices of inliers in objectPoints and imagePoints .
        Mat rvec, tvec, inliners;

        //// Finds an object pose from 3D-2D point correspondences using the RANSAC scheme.
        cv::solvePnPRansac(pts3d, pts2d, K, Mat(), rvec, tvec, false, 100, 4.0, 0.99, inliners);
        num_inliers_ = inliners.rows;
        cout<<"pnp ransac inliers: "<< num_inliers_<<endl;

        //// Save OpenCV Mat --> SE3 lie group in sophus
        T_c_r_estimated_ = SE3(
                SO3(rvec.at<double>(0,0), rvec.at<double>(1,0), rvec.at<double>(2,0)),
                Vector3d( tvec.at<double>(0,0), tvec.at<double>(1,0), tvec.at<double>(2,0))
        );

        cout<<" rvec "<<rvec.at<double>(0,0)<<" "<<rvec.at<double>(1,0)<<" "<<rvec.at<double>(2,0)<<" "<<endl;
        cout<<" tvec "<<tvec.at<double>(0,0)<<" "<<tvec.at<double>(1,0)<<" "<<tvec.at<double>(2,0)<<" "<<endl;
        cout<<"T_c_r_estimated_: "<<T_c_r_estimated_<<endl;
    }

    bool VisualOdometry::checkEstimatePose()
    {
        // check is the estimated pose is good
        if ( num_inliers_ < min_inliers_)
        {
            cout<<" reject this pnp ransac slove because inlier is too small:"<< num_inliers_<<endl;
            return false;
        }
        Sophus::Vector6d d = T_c_r_estimated_.log();
        if ( d.norm() > 5.0 )
        {
            cout<<"reject because motion is too large: "<<d.norm()<<endl;
            return false;
        }
        return true;
    }

    bool VisualOdometry::checkKeyFrame()
    {
        Sophus::Vector6d d = T_c_r_estimated_.log();    // lie group --> lie algebra
        Vector3d trans = d.head<3>();                   // the first n coeffs in d, Eigen function
        Vector3d rot = d.tail<3>();                     // // the last n coeffs in d, Eigen function
        if ( rot.norm() > key_frame_min_rot || trans.norm() > key_frame_min_trans)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    void VisualOdometry::addKeyFrame()
    {
        cout<<" add a key frame "<<endl;
        map_->insertKeyFrame( curr_ );
    }

}


text:
/***************************************************************************
 * Copyright 1998-2017 by authors (see AUTHORS.txt)                        *
 *                                                                         *
 *   This file is part of LuxRender.                                       *
 *                                                                         *
 * 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 <stdexcept>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>

#include "slg/film/film.h"
#include "slg/kernels/kernels.h"
#include "slg/film/imagepipeline/plugins/vignetting.h"
#include "luxrays/kernels/kernels.h"

using namespace std;
using namespace luxrays;
using namespace slg;

//------------------------------------------------------------------------------
// Vignetting plugin
//------------------------------------------------------------------------------

BOOST_CLASS_EXPORT_IMPLEMENT(slg::VignettingPlugin)

VignettingPlugin::VignettingPlugin(const float s) : scale(s) {
#if !defined(LUXRAYS_DISABLE_OPENCL)
	applyKernel = NULL;
#endif
}

VignettingPlugin::~VignettingPlugin() {
#if !defined(LUXRAYS_DISABLE_OPENCL)
	delete applyKernel;
#endif
}

ImagePipelinePlugin *VignettingPlugin::Copy() const {
	return new VignettingPlugin(scale);
}

//------------------------------------------------------------------------------
// CPU version
//------------------------------------------------------------------------------

void VignettingPlugin::Apply(Film &film, const u_int index) {
	Spectrum *pixels = (Spectrum *)film.channel_IMAGEPIPELINEs[index]->GetPixels();

	const u_int width = film.GetWidth();
	const u_int height = film.GetHeight();
	const float invWidth = 1.f / width;
	const float invHeight = 1.f / height;

	#pragma omp parallel for
	for (
			// Visual C++ 2013 supports only OpenMP 2.5
#if _OPENMP >= 200805
			unsigned
#endif
			int y = 0; y < height; ++y) {
		for (u_int x = 0; x < width; ++x) {
			const u_int index = x + y * width;

			if (*(film.channel_FRAMEBUFFER_MASK->GetPixel(index))) {
				const float nx = x * invWidth;
				const float ny = y * invHeight;
				const float xOffset = (nx - .5f) * 2.f;
				const float yOffset = (ny - .5f) * 2.f;
				const float tOffset = sqrtf(xOffset * xOffset + yOffset * yOffset);

				// Normalize to range [0.f - 1.f]
				const float invOffset = 1.f - (fabsf(tOffset) * 1.42f);
				float vWeight = Lerp(invOffset, 1.f - scale, 1.f);

				pixels[index].c[0] *= vWeight;
				pixels[index].c[1] *= vWeight;
				pixels[index].c[2] *= vWeight;
			}
		}
	}
}

//------------------------------------------------------------------------------
// OpenCL version
//------------------------------------------------------------------------------

#if !defined(LUXRAYS_DISABLE_OPENCL)
void VignettingPlugin::ApplyOCL(Film &film, const u_int index) {
	if (!applyKernel) {
		// Compile sources
		const double tStart = WallClockTime();

		cl::Program *program = ImagePipelinePlugin::CompileProgram(
				film,
				"-D LUXRAYS_OPENCL_KERNEL -D SLG_OPENCL_KERNEL",
				slg::ocl::KernelSource_plugin_vignetting_funcs,
				"VignettingPlugin");

		SLG_LOG("[VignettingPlugin] Compiling VignettingPlugin_Apply Kernel");
		applyKernel = new cl::Kernel(*program, "VignettingPlugin_Apply");

		delete program;

		// Set kernel arguments
		u_int argIndex = 0;
		applyKernel->setArg(argIndex++, film.GetWidth());
		applyKernel->setArg(argIndex++, film.GetHeight());
		applyKernel->setArg(argIndex++, *(film.ocl_IMAGEPIPELINE));
		applyKernel->setArg(argIndex++, *(film.ocl_FRAMEBUFFER_MASK));
		applyKernel->setArg(argIndex++, scale);

		const double tEnd = WallClockTime();
		SLG_LOG("[VignettingPlugin] Kernels compilation time: " << int((tEnd - tStart) * 1000.0) << "ms");
	}

	film.oclIntersectionDevice->GetOpenCLQueue().enqueueNDRangeKernel(*applyKernel,
			cl::NullRange, cl::NDRange(RoundUp(film.GetWidth() * film.GetHeight(), 256u)), cl::NDRange(256));
}
#endif

max_stars_repo_name: LuxRender/LuxRays

max_issues_repo_name: LuxRender/LuxRays

max_forks_repo_name: LuxRender/LuxRays


text:
//
// Boost.Pointer Container
//
//  Copyright Thorsten Ottosen 2003-2005. 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)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//

#include <boost/test/unit_test.hpp>
#include "associative_test_data.hpp"
#include <boost/ptr_container/ptr_set.hpp>

void test_set()
{

    ptr_set_test< ptr_set<Base>, Base, Derived_class >();
    ptr_set_test< ptr_set<Value>, Value, Value >();

    ptr_set_test< ptr_multiset<Base>, Base, Derived_class >();
    ptr_set_test< ptr_multiset<Value>, Value, Value >();

    ptr_set<int> set;

    BOOST_CHECK_THROW( set.insert( 0 ), bad_ptr_container_operation );
    set.insert( new int(0) );
    BOOST_CHECK_THROW( (set.replace(set.begin(), 0 )), bad_ptr_container_operation );
}

using boost::unit_test::test_suite;

test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    test_suite* test = BOOST_TEST_SUITE( "Pointer Container Test Suite" );

    test->add( BOOST_TEST_CASE( &test_set ) );

    return test;
}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM