text:
/**
 * @file barConnectionInfo.hpp
 * @author Luiz Victor Linhares Rocha (luizvictorlrocha@gmail.com)
 * @brief defines class for storing levels of connection in a bar
 * @version 0.1
 * @date 2018-10-08
 *
 * @copyright Copyright (c) 2018
 *
 */

#ifndef REDE_BARCONNECTIONINFO_HPP_
#define REDE_BARCONNECTIONINFO_HPP_

#include <vector>
#include <boost/shared_ptr.hpp>
#include "neuralFluxDeclare.hpp"

using std::vector;
using boost::shared_ptr;

namespace neuralFlux {

class BarConnectionInfo;
typedef shared_ptr<BarConnectionInfo> BarConnectionInfoPtr;

class BarConnectionInfo {
 public:
    explicit BarConnectionInfo(BarPtr bar, int level = 3);
    BarConnectionInfo(BarPtr bar, const vector<BarConnectionInfoPtr> &connecteds, int level = 3);
    BarPtr getBar();
    int getLevel();
    const vector<BarConnectionInfoPtr> &getConnectedBars();
    void setLevel(int level);
    void setBarConnection(BarConnectionInfoPtr bar);
    void applyLevelToNeighbours();
    int getConnectionsWithLevel(int minLevel = 2);

 private:
    vector<BarConnectionInfoPtr> connected;
    int level;
    BarPtr bar;

    void printResult(BarPtr bar);
    void printInput(BarPtr bar);
};
}  // namespace neuralFlux

#endif  // REDE_BARCONNECTIONINFO_HPP_

ext: hpp

max_stars_repo_name: BigsonLvrocha/NeuralPowerFlow

max_issues_repo_name: BigsonLvrocha/NeuralPowerFlow

max_forks_repo_name: BigsonLvrocha/NeuralPowerFlow


text:
#pragma once

#include <data_model.hpp>
#include <graph_model.hpp>

#include <vector>
#include <map>
#include <iostream>
#include <deque>
#include <sstream>
#include <stdexcept>
#include <iterator>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>

namespace verilog {
  namespace graph {

    LogicValue propagate(LogicValue v, NegP np) {
      checkValid(v);

      return np == NegP::Positive ? v : !v;
    }

    void simulate(
        std::map<std::string, bool> & inputs,
        std::map<std::string, bool> & outputs, G_builder & b) {

      G & g = b.g;

      using namespace boost;

      std::deque<int> topo_order;
      boost::topological_sort(g.graph, std::front_inserter(topo_order));
      //

      // Initialize the constants
      g.graph[g.zero].value = LogicValue::Zero;
      g.graph[g.one].value = LogicValue::One;

      //std::cout << "// initialized constants\n";
      //write_graph(std::cout, b);

      // Initialize the inputs
      for (auto it : inputs) {
        g.graph[b.get_vertex(it.first)].value = fromBool(it.second);
      }

      //std::cout << "// initialized inputs\n";
      //write_graph(std::cout, b);

      // Propagate the values to the outputs
      for (int node : topo_order) {
        if(in_degree(node, g.graph) > 0) {
          auto p = in_edges(node, g.graph);

          LogicValue sum = LogicValue::One;

          for (auto e = p.first; e != p.second; ++e) {

            int s = source(*e, g.graph);
            LogicValue value = propagate(g.graph[s].value, g.graph[*e]);

            sum = sum && value;
          }
          g.graph[node].value = sum;

        }

        //std::cout << "// executed " << node << "\n";
        //write_graph(std::cout, b);
      }

      // output the outputs!
      for(std::string n : b.outputs) {
        outputs[n] = toBool(g.graph[b.get_vertex(n)].value);
      }
    }
  }
}


text:
/*
 * cppAttributeAccess.hpp
 *
 *
 * @date 14-07-2020
 * @author Teddy DIDE
 * @version 1.00
 * cppBase generated by gensources.
 */

#ifndef _CPPATTRIBUTE_ACCESS_HPP_
#define _CPPATTRIBUTE_ACCESS_HPP_

#include <boost/scoped_ptr.hpp>
#include <memory>
#include <boost/signals2.hpp>
#include <boost/any.hpp>
#include "cppBaseExport.hpp"
#include "cppAttribute.hpp"

#define A(str) encode<EncodingT,ansi>(str)
#define C(str) encode<ansi,EncodingT>(str)

NAMESPACE_BEGIN(data_access)

using namespace entity;

/// Represents an access class for CppAttribute object.
/// This class is used to manage CppAttribute entity in database.
template <class EncodingT>
class CPPBASE_API  _CppAttributeAccess {
private :
	std::list< boost::shared_ptr< _CppAttribute<EncodingT> > > m_backup;
	// Is a transaction in progress before queries ?
	bool m_transactionOwner;
	static _CppAttributeAccess<EncodingT>* m_instance;

public:
	typedef boost::signals2::signal<void (operation_access_t, typename EncodingT::string_t const&, boost::any const&)>  signal_t;
	typedef boost::signals2::signal<void (operation_access_t)>  signal_transaction_t;
	typedef boost::signals2::connection  connection_t;

private:
	signal_t m_insertSignal;
	signal_t m_updateSignal;
	signal_t m_deleteSignal;
	signal_transaction_t m_transactionSignal;

private:
	/** Creates a new element CppAttributeAccess.
	*/
	_CppAttributeAccess();
	/** Releases the CppAttributeAccess object.
	*/
	~_CppAttributeAccess();
	Category*	m_logger;

protected :
public :
	/** Returns CppAttributeAccess object.
	@return Instance of CppAttributeAccess.
	*/
	 static _CppAttributeAccess<EncodingT>* getInstance();
	/** Returns CppAttribute objects from database.
	@param filter Condition allowing to filter data.
	@return List of CppAttribute objects.
	*/
	 std::vector< boost::shared_ptr< _CppAttribute<EncodingT> > > getManyCppAttributes(typename EncodingT::string_t const&  filter) const;
	/** Returns all CppAttribute objects from database.
	@return List of CppAttribute objects.
	*/
	 std::vector< boost::shared_ptr< _CppAttribute<EncodingT> > > getAllCppAttributes() const;
	/** Returns CppAttribute object from database.
	@param identifier
	@return The CppAttribute object.
	*/
	 boost::shared_ptr< _CppAttribute<EncodingT> > getOneCppAttribute(long long identifier) const;
	/** Returns CppAttribute objects from database. Data are locked for update.
	@param filter Condition allowing to filter data.
	@param nowait Asynchonous call.
	@return List of CppAttribute objects.
	*/
	 std::vector< boost::shared_ptr< _CppAttribute<EncodingT> > > selectManyCppAttributes(typename EncodingT::string_t const&  filter, bool nowait = false, bool addition = false);
	/** Returns CppAttribute object from database. Data are locked for update.
	@param identifier
	@param nowait Asynchonous call.
	@return The CppAttribute object.
	*/
	 boost::shared_ptr< _CppAttribute<EncodingT> > selectOneCppAttribute(long long identifier, bool nowait = false, bool addition = false);
	/** Returns whether the data CppAttribute are selected.
	@param o The CppAttribute object.
	@return True if the data CppAttribute are selected.
	*/
	 bool isSelectedCppAttribute(boost::shared_ptr< _CppAttribute<EncodingT> > o) const;
	/** Cancel the selection. The CppAttribute object cannot be updated or deleted from database.
	*/
	 void cancelSelection();
	/** Fills cppClass data from database.
	@param o The CppAttribute object.
	*/
	 void fillCppClass(boost::shared_ptr< _CppAttribute<EncodingT> > o);
	/** Returns whether CppAttribute data are altered from database.
	@param o The CppAttribute object.
	@return True if data CppAttribute have been altered.
	*/
	 bool isModifiedCppAttribute(boost::shared_ptr< _CppAttribute<EncodingT> > o) const;
	/** Updates CppAttribute data to database.
	@param o The CppAttribute object.
	*/
	 void updateCppAttribute(boost::shared_ptr< _CppAttribute<EncodingT> > o);
	/** Inserts CppAttribute data to database.
	@param o The CppAttribute object.
	*/
	 void insertCppAttribute(boost::shared_ptr< _CppAttribute<EncodingT> > o);
	/** Deletes CppAttribute data to database.
	@param o The CppAttribute object.
	*/
	 void deleteCppAttribute(boost::shared_ptr< _CppAttribute<EncodingT> > o);
	/** Add signal for CppAttribute insertion.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addInsertSignal(typename signal_t::slot_function_type subscriber);
	/** Add signal for CppAttribute update.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addUpdateSignal(typename signal_t::slot_function_type subscriber);
	/** Add signal for CppAttribute deletion.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addDeleteSignal(typename signal_t::slot_function_type subscriber);
	/** Add signal for CppAttribute transaction result.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addTransactionSignal(typename signal_transaction_t::slot_function_type subscriber);
	/** Remove signal for CppAttribute insertion.
	@param connection The connection
	*/
	 void removeInsertSignal(connection_t connection);
	/** Remove signal for CppAttribute update.
	@param connection The connection
	*/
	 void removeUpdateSignal(connection_t connection);
	/** Remove signal for CppAttribute deletion.
	@param connection The connection
	*/
	 void removeDeleteSignal(connection_t connection);
	/** Remove signal for CppAttribute transaction result.
	@param connection The connection
	*/
	 void removeTransactionSignal(connection_t connection);
};

typedef _CppAttributeAccess<ucs> UniCppAttributeAccess;
typedef _CppAttributeAccess<ansi> CppAttributeAccess;

NAMESPACE_END

#undef C
#undef A

#if !defined(HAS_CPPBASE_DLL) || defined(BUILD_CPPBASE_DLL)
#include "cppAttributeAccess_impl.hpp"
#endif // !defined(HAS_CPPBASE_DLL) || defined(BUILD_CPPBASE_DLL)

#endif


text:
#include <Eigen/Core>

#include <numpy_eigen/boost_python_headers.hpp>
Eigen::Matrix<boost::int64_t, 2, Eigen::Dynamic> test_long_2_D(
    const Eigen::Matrix<boost::int64_t, 2, Eigen::Dynamic>& M) {
    return M;
}
void export_long_2_D() { boost::python::def("test_long_2_D", test_long_2_D); }

ext: cpp

max_stars_repo_name: chengfzy/kalibr

max_issues_repo_name: chengfzy/kalibr

max_forks_repo_name: chengfzy/kalibr


text:
#include <unordered_map>
#include <iostream>

#include <Eigen/Core>

#include "DBSCAN.h"

#include "LineGroup.h"

#include "LineDetection.h"

namespace localization
{

void LineDetection::filterLineCluster(const std::vector<Line>& cluster)
{
    if (cluster.empty()) return;

    std::vector<LineGroup> orientationFiltered;
    filterByOrientation(cluster, orientationFiltered);

    std::vector<LineGroup> proximityFiltered;
    for (int i = 0; i < orientationFiltered.size(); ++i)
    {
        filterByProximity(orientationFiltered[i], proximityFiltered);
    }

    filteredLines_.clear();
    for (int i = 0; i < proximityFiltered.size(); ++i)
    {
        filteredLines_.push_back(proximityFiltered[i].convertToLine());
    }
}

void LineDetection::filterByOrientation(const std::vector<Line>& cluster,
                                        std::vector<LineGroup>& filtered)
{
    for (int i = 0; i < cluster.size(); ++i)
    {
        groupByOrientation(cluster[i], filtered);
    }
}

void LineDetection::groupByOrientation(const Line& line, std::vector<LineGroup>& groups)
{
    bool groupFound = false;
    for (int i = 0; i < groups.size() && !groupFound; ++i)
    {
        if (groups[i].isCollateral(line, 0.80))
        {
            groups[i].add(line);
            groupFound = true;
        }
    }

    if (!groupFound)
    {
        groups.push_back(LineGroup(line));
    }
}

void LineDetection::filterByProximity(const LineGroup& group,
                                      std::vector<LineGroup>& filtered)
{
    std::vector<const Line*> lines = group.getLines();
    std::vector<Vector> centroids(lines.size());
    for (int i = 0; i < lines.size(); ++i)
    {
        centroids[i] = lines[i]->getCentroid();
    }

    std::vector<int> clusterMemberships;
    DBSCAN::DBSCAN(centroids, 50, 1, clusterMemberships);

    parseClusterMemberships(clusterMemberships, lines, filtered);
}

void LineDetection::parseClusterMemberships(const std::vector<int>& clusterMemberships,
                                            const std::vector<const Line*>& cluster,
                                                  std::vector<LineGroup>& filtered)
{
    if (cluster.size() != clusterMemberships.size()) return;

    std::unordered_map<int, LineGroup> groups;

    std::unordered_map<int, LineGroup>::iterator it = groups.end();
    for (int i = 0; i < clusterMemberships.size(); ++i)
    {
        int groupId = clusterMemberships[i];
        it = groups.find(groupId);
        if (it != groups.end())
        {
            it->second.add(*cluster[i]);
        }
        else
        {
            groups.insert({ groupId, LineGroup(*cluster[i]) });
        }
    }

    for (it = groups.begin(); it != groups.end(); it++)
    {
        filtered.push_back(it->second);
    }
}

}


text:
#pragma once
#include <boost/lexical_cast.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include <opencv2/core/mat.hpp>

namespace cereal
{
    void save(BinaryOutputArchive& ar, const cv::Mat& mat)
    {
        int rows, cols, type;
        bool continuous;

        rows = mat.rows;
        cols = mat.cols;
        type = mat.type();
        continuous = mat.isContinuous();

        ar& rows& cols& type& continuous;

        if (continuous)
        {
            const size_t data_size = rows * cols * mat.elemSize();
            auto mat_data = cereal::binary_data(mat.ptr(), data_size);
            ar& mat_data;
        }
        else
        {
            const size_t row_size = cols * mat.elemSize();
            for (int i = 0; i < rows; i++)
            {
                auto row_data = cereal::binary_data(mat.ptr(i), row_size);
                ar& row_data;
            }
        }
    }

    void load(BinaryInputArchive& ar, cv::Mat& mat)
    {
        int rows, cols, type;
        bool continuous;

        ar& rows& cols& type& continuous;

        if (continuous)
        {
            mat.create(rows, cols, type);
            const size_t data_size = rows * cols * mat.elemSize();
            auto mat_data = cereal::binary_data(mat.ptr(), data_size);
            ar& mat_data;
        }
        else
        {
            mat.create(rows, cols, type);
            const size_t row_size = cols * mat.elemSize();
            for (int i = 0; i < rows; i++)
            {
                auto row_data = cereal::binary_data(mat.ptr(i), row_size);
                ar& row_data;
            }
        }
    };

    void save(cereal::JSONOutputArchive& ar, const cv::Mat& mat)
    {
        int rows, cols, type;
        bool continuous;

        rows = mat.rows;
        cols = mat.cols;
        type = mat.type();
        continuous = mat.isContinuous();

        ar(CEREAL_NVP(rows));
        ar(CEREAL_NVP(cols));
        ar(CEREAL_NVP(type));
        ar(CEREAL_NVP(continuous));
        if (mat.rows * mat.cols < 15 * 15 && mat.channels() == 1)
        {
            std::vector<float> data(mat.rows * mat.cols);
            mat.convertTo(cv::Mat(mat.rows, mat.cols, CV_32F, data.data()), CV_32F);
            ar(CEREAL_NVP(data));
        }
        else
        {
            if (continuous)
            {
                const size_t data_size = rows * cols * mat.elemSize();
                ar.saveBinaryValue(mat.ptr(), data_size, "data");
            }
            else
            {
                const size_t row_size = cols * mat.elemSize();
                for (int i = 0; i < rows; i++)
                {
                    ar.saveBinaryValue(
                        mat.ptr(i), row_size, (std::string("data") + boost::lexical_cast<std::string>(i)).c_str());
                }
            }
        }
    }

    void load(cereal::JSONInputArchive& ar, cv::Mat& mat)
    {
        int rows, cols, type;
        bool continuous;

        // ar & rows & cols & type & continuous;
        ar(CEREAL_NVP(rows));
        ar(CEREAL_NVP(cols));
        ar(CEREAL_NVP(type));
        ar(CEREAL_NVP(continuous));
        if (rows * cols < 15 * 15 && type <= CV_64F)
        {
            std::vector<float> data;
            ar(CEREAL_NVP(data));
            mat.create(rows, cols, type);
            cv::Mat(rows, cols, CV_32F, data.data()).convertTo(mat, type);
        }
        else
        {
            if (continuous)
            {
                mat.create(rows, cols, type);
                const size_t data_size = rows * cols * mat.elemSize();
                ar.loadBinaryValue(mat.ptr(), data_size, "data");
            }
            else
            {
                mat.create(rows, cols, type);
                const size_t row_size = cols * mat.elemSize();
                for (int i = 0; i < rows; i++)
                {
                    ar.loadBinaryValue(
                        mat.ptr(i), row_size, (std::string("data") + boost::lexical_cast<std::string>(i)).c_str());
                }
            }
        }
    }

    template <class AR>
    void save(AR& ar, cv::Mat const& mat)
    {
    }
    template <class AR>
    void load(AR& ar, cv::Mat& mat)
    {
    }
}

max_stars_repo_name: dtmoodie/Acquilla

max_issues_repo_name: dtmoodie/Acquilla

max_forks_repo_name: dtmoodie/Acquilla


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 FLOW_STATS_IN_HH__
#define FLOW_STATS_IN_HH__

#include <stddef.h>
#include <string>

#include <boost/shared_array.hpp>
#include "event.hh"
#include "netinet++/datapathid.hh"
#include "ofp-msg-event.hh"

#include "openflow/openflow.h"

namespace vigil {

struct Flow_stats
    : public ofp_flow_stats
{
    std::vector<const ofp_action_header*> v_actions;

    Flow_stats(const ofp_flow_stats*);
private:
    boost::shared_array<uint8_t> action_data;
};

struct Flow_stats_in_event
    : public Event,
      public Ofp_msg_event
{
    Flow_stats_in_event(const datapathid& dpid, const ofp_stats_reply *osr,
                        std::auto_ptr<Buffer> buf);

    // -- only for use within python
    Flow_stats_in_event() : Event(static_get_name()) { }

    static const Event_name static_get_name() {
        return "Flow_stats_in_event";
    }

    datapathid datapath_id;
    bool more;
    std::vector<Flow_stats> flows;

    Flow_stats_in_event(const Flow_stats_in_event&);
    Flow_stats_in_event& operator=(const Flow_stats_in_event&);
}; // Flow_stats_in_event

} // namespace vigil

#endif // FLOW_STATS_IN_HH__

ext: hh

max_stars_repo_name: ayjazz/OESS

max_issues_repo_name: ayjazz/OESS

max_forks_repo_name: ayjazz/OESS


text:
#include <fstream>
#include <iostream>
#include <string>
#include <cmath>
#include <chrono>
#include <future>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include "csv.hpp"
#include "../assembly/assembly.cpp"
#include "../distance/distance.cpp"
#include "../distribution/distribution.cpp"

using namespace std;
using namespace std::chrono;
using namespace csv;

bool task_compute_distance(
	const int task_nb,
	const string kind,
	const vector<string>& assembly_ids
) {
	auto start = system_clock::now();

	cerr << "Thread " << task_nb << " started." << endl;

	string dataFolder = "../data/";
	string sequencesFolder = dataFolder + "sequences/";

	string assembly_dist_path;
	if (kind == "tri-nucleotide") {
		assembly_dist_path = dataFolder + "tri_nucleotide_dist_genome_wide_with_overlap.csv";
	} else {
		assembly_dist_path = dataFolder + "amino_acid_dist_genome_wide.csv";
	}

	ifstream assembly_dist_f(assembly_dist_path);
	Distributions assembly_distributions(assembly_dist_f);

	int i = 0;
	for (auto& accession : assembly_ids) {
		if (i == 0 || (i+1) % 100 == 0) {
			auto tp = system_clock::now();
			cerr << "Thread " << task_nb << ": Processing assembly " << i + 1 << " / " << assembly_ids.size();
			cerr << " (elapsed: " << duration_cast<seconds>(tp - start).count() << " seconds)" << endl;
		}
		++i;

		string cds_dist_path;
		string outputPath;
		if (kind == "tri-nucleotide") {
			cds_dist_path = (
				sequencesFolder + accession + "/" +
				accession + "_tri_nucleotide_dist_without_rc_with_overlap.csv.gz"
			);
			outputPath = (
				sequencesFolder + accession + "/" +
				accession + "_tri_nucleotide_distance_to_mean.csv"
			);
		} else {
			cds_dist_path = (
				sequencesFolder + accession + "/" +
				accession + "_amino_acid_dist.csv.gz"
			);
			outputPath = (
				sequencesFolder + accession + "/" +
				accession + "_amino_acid_distance_to_mean.csv"
			);
		}

		ifstream cds_dist_f(cds_dist_path, ios_base::in | ios_base::binary);
		boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
		inbuf.push(boost::iostreams::gzip_decompressor());
		inbuf.push(cds_dist_f);
		istream instream(&inbuf);

		Distributions cds_distributions(instream);

		auto mean_dist = duplicate_rows(
			assembly_distributions[accession],
			cds_distributions.size()
		);

		vector<string> protein_ids = cds_distributions.Keys();
		xt::xarray<double>& distributions = cds_distributions.Values();

		xt::xarray<double> distances = jensen_shannon_distance(mean_dist, distributions, 1);

		ofstream of(outputPath);
		auto writer = make_csv_writer(of);

		vector<string> headers{"protein_id", "distance"};
		writer << headers;

		for (int n = 0; n < distances.size(); ++n) {
			string protein_id = protein_ids[n];
			double distance = distances[n];
			if (isnan(distance)) {
				cerr << "Distance: NaN value encountered for accession " << accession << endl;
				continue;
			} else if (isinf(distance)) {
				cerr << "Distance: Inf value encountered for accession " << accession << endl;
				continue;
			}
			vector<string> row{protein_id, to_string(distance)};
			writer << row;
		}
	}

	auto tp = system_clock::now();
	cerr << "Thread " << task_nb << ": DONE";
	cerr << " (elapsed: " << duration_cast<seconds>(tp - start).count() << " seconds)" << endl;
	return true;
}

void compute_distance(const string kind, const int n_threads) {
	string dataFolder = "../data/";
	string assembliesPath = dataFolder + "assemblies.csv";

	Assemblies assemblies(assembliesPath);
	auto assembly_ids = assemblies.GetIds();

	cerr << "Processing " << assemblies.Size() << " assemblies" << endl;
	cerr << "Starting " << n_threads << " threads" << endl;

	auto n_per_thread = ceil((double) assembly_ids.size() / (double) n_threads);

	vector<future<bool>> futures;
	for (int i = 0; i < n_threads; ++i) {
		auto start = assembly_ids.begin() + i * n_per_thread;
		auto end = assembly_ids.end();
		int endInt = i * n_per_thread + n_per_thread;
		if (endInt < assembly_ids.size()) {
			end = assembly_ids.begin() + endInt;
		}
		auto ids = vector<string>(start, end);
		futures.push_back(async(task_compute_distance, i+1, kind, ids));
	}
	for (auto& f : futures) {
		if(!f.get()) {
			throw runtime_error("Unexpected error while processing future's output");
		}
	}
	cerr << "DONE" << endl;
}

max_stars_repo_name: srom/nbias

max_issues_repo_name: srom/nbias

max_forks_repo_name: srom/nbias


text:
/**********************************************************************
*  Copyright (c) 2008-2014, Alliance for Sustainable Energy.
*  All rights reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**********************************************************************/

#ifndef RUNMANAGER_LIB_PARALLELENERGYPLUSSPLITJOB_HPP
#define RUNMANAGER_LIB_PARALLELENERGYPLUSSPLITJOB_HPP

#include <boost/filesystem.hpp>
#include <string>
#include "../../utilities/core/Logger.hpp"
#include "Job_Impl.hpp"
#include "JobParam.hpp"
#include "../../utilities/core/Checksum.hpp"

#include <QFileSystemWatcher>
#include <QFileInfo>
#include <QDateTime>

namespace openstudio {
namespace runmanager {
namespace detail {

  /**
   * Job type that converts a Model file into an IDF in process.
   */
  class ParallelEnergyPlusSplitJob : public Job_Impl
  {
    Q_OBJECT;

    public:
      /// ParallelEnergyPlusSplit constructor.
      ParallelEnergyPlusSplitJob(const UUID &t_uuid,
          const Tools &tools,
          const JobParams &params,
          const Files &files,
      const JobState &t_restoreData);

      virtual ~ParallelEnergyPlusSplitJob();

      // Reimplemented virtual functions from Job_Impl
      virtual bool outOfDateImpl(const boost::optional<QDateTime> &t_lastrun) const;
      virtual std::string description() const;
      virtual Files outputFilesImpl() const;
      virtual std::string getOutput() const;
      virtual void cleanup();

      virtual void requestStop();

    protected:
      virtual void startImpl(const std::shared_ptr<ProcessCreator> &t_creator);
      static std::vector<openstudio::path> generateFileNames(const openstudio::path &t_outdir, int t_num);

      virtual void basePathChanged();
      virtual void standardCleanImpl() { LOG(Error, "standardCleanImpl not implemented yet."); }

    private:
      REGISTER_LOGGER("openstudio.runmanager.ParallelEnergyPlusSplit");

      FileInfo inputFile() const;

      mutable QReadWriteLock m_mutex;

      std::map<openstudio::path, FileTrack> m_files; //< Files tracked for outOfDate status
      int m_numSplits; //< Number of splits to create
      int m_offset;

      boost::optional<FileInfo> m_input; //< IDF that is being converted
      mutable boost::optional<Files> m_outputfiles; //< IDF files that were created from run

      std::string m_description; //< Description of job
  };

}
}
}
#endif // RUNMANAGER_LIB_PARALLELENERGYPLUSSPLITJOB_HPP


text:
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program 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
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include <boost/filesystem.hpp>

#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/dbhelpers.h"
#include "mongo/db/operation_context_noop.h"
#include "mongo/db/repl/replication_coordinator_mock.h"
#include "mongo/db/service_context_d_test_fixture.h"
#include "mongo/db/storage/storage_repair_observer.h"
#include "mongo/logv2/log.h"
#include "mongo/unittest/death_test.h"
#include "mongo/unittest/unittest.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest

namespace mongo {
namespace {

static const NamespaceString kConfigNss("local.system.replset");
static const std::string kRepairIncompleteFileName = "_repair_incomplete";

using boost::filesystem::path;

class StorageRepairObserverTest : public ServiceContextMongoDTest {
public:
    StorageRepairObserverTest() {
        repl::ReplicationCoordinator::set(
            getServiceContext(),
            std::make_unique<repl::ReplicationCoordinatorMock>(getServiceContext()));
    }

    void assertRepairIncompleteOnTearDown() {
        _assertRepairIncompleteOnTearDown = true;
    }

    void createMockReplConfig(OperationContext* opCtx) {
        BSONObj replConfig;
        Lock::DBLock dbLock(opCtx, "local", MODE_X);
        Helpers::putSingleton(opCtx, "local.system.replset", replConfig);
    }

    void assertReplConfigValid(OperationContext* opCtx, bool valid) {
        BSONObj replConfig;
        ASSERT(Helpers::getSingleton(opCtx, "local.system.replset", replConfig));
        if (valid) {
            ASSERT(!replConfig.hasField("repaired"));
        } else {
            ASSERT(replConfig.hasField("repaired"));
        }
    }

    bool hasReplConfig(OperationContext* opCtx) {
        BSONObj replConfig;
        Lock::DBLock dbLock(opCtx, "local", MODE_IS);
        return Helpers::getSingleton(opCtx, "local.system.replset", replConfig);
    }

    path repairFilePath() {
        return path(storageGlobalParams.dbpath) / path(kRepairIncompleteFileName);
    }

    StorageRepairObserver* reset() {
        StorageRepairObserver::set(
            getServiceContext(),
            std::make_unique<StorageRepairObserver>(storageGlobalParams.dbpath));
        return getRepairObserver();
    }

    StorageRepairObserver* getRepairObserver() {
        return StorageRepairObserver::get(getServiceContext());
    }

    void setUp() {
        ServiceContextMongoDTest::setUp();
        storageGlobalParams.repair = true;
    }

    void tearDown() {
        auto repairObserver = getRepairObserver();
        if (_assertRepairIncompleteOnTearDown) {
            ASSERT(repairObserver->isIncomplete());
        } else {
            ASSERT(!repairObserver->isIncomplete());
        }

        if (repairObserver->isDone() && repairObserver->isDataInvalidated()) {
            LOGV2(22291, "Modifications: ");
            for (const auto& mod : repairObserver->getModifications()) {
                LOGV2(22292,
                      "  {mod_getDescription}",
                      "mod_getDescription"_attr = mod.getDescription());
            }
        }
        storageGlobalParams.repair = false;
    }

private:
    bool _assertRepairIncompleteOnTearDown = false;
};

TEST_F(StorageRepairObserverTest, DataUnmodified) {
    auto repairObserver = getRepairObserver();

    auto repairFile = repairFilePath();
    ASSERT(!boost::filesystem::exists(repairFile));
    ASSERT(!repairObserver->isIncomplete());

    repairObserver->onRepairStarted();

    ASSERT(repairObserver->isIncomplete());
    ASSERT(boost::filesystem::exists(repairFile));

    auto opCtx = cc().makeOperationContext();
    createMockReplConfig(opCtx.get());

    repairObserver->onRepairDone(opCtx.get());
    ASSERT(!repairObserver->isIncomplete());
    ASSERT(!boost::filesystem::exists(repairFile));

    ASSERT(repairObserver->isDone());
    ASSERT(!repairObserver->isDataInvalidated());

    assertReplConfigValid(opCtx.get(), true);
}

TEST_F(StorageRepairObserverTest, DataModified) {
    auto repairObserver = getRepairObserver();

    auto repairFile = repairFilePath();
    ASSERT(!boost::filesystem::exists(repairFile));
    ASSERT(!repairObserver->isIncomplete());

    repairObserver->onRepairStarted();

    ASSERT(repairObserver->isIncomplete());
    ASSERT(boost::filesystem::exists(repairFile));

    std::string mod("Collection mod");
    repairObserver->invalidatingModification(mod);

    auto opCtx = cc().makeOperationContext();
    Lock::GlobalWrite lock(opCtx.get());
    createMockReplConfig(opCtx.get());

    repairObserver->onRepairDone(opCtx.get());
    ASSERT(!repairObserver->isIncomplete());
    ASSERT(!boost::filesystem::exists(repairFile));

    ASSERT(repairObserver->isDone());
    ASSERT(repairObserver->isDataInvalidated());
    ASSERT_EQ(1U, repairObserver->getModifications().size());

    assertReplConfigValid(opCtx.get(), false);
}

TEST_F(StorageRepairObserverTest, DataValidAfterBenignModification) {
    auto repairObserver = getRepairObserver();

    auto repairFile = repairFilePath();
    ASSERT(!boost::filesystem::exists(repairFile));
    ASSERT(!repairObserver->isIncomplete());

    repairObserver->onRepairStarted();

    ASSERT(repairObserver->isIncomplete());
    ASSERT(boost::filesystem::exists(repairFile));

    std::string mod("Collection mod");
    repairObserver->benignModification(mod);

    auto opCtx = cc().makeOperationContext();
    Lock::GlobalWrite lock(opCtx.get());
    createMockReplConfig(opCtx.get());

    repairObserver->onRepairDone(opCtx.get());
    ASSERT(!repairObserver->isIncomplete());
    ASSERT(!boost::filesystem::exists(repairFile));

    ASSERT(repairObserver->isDone());
    ASSERT(!repairObserver->isDataInvalidated());
    ASSERT_EQ(1U, repairObserver->getModifications().size());

    assertReplConfigValid(opCtx.get(), true);
}

TEST_F(StorageRepairObserverTest, DataModifiedDoesNotCreateReplConfigOnStandalone) {
    auto repairObserver = getRepairObserver();

    auto repairFile = repairFilePath();
    ASSERT(!boost::filesystem::exists(repairFile));
    ASSERT(!repairObserver->isIncomplete());

    repairObserver->onRepairStarted();

    ASSERT(repairObserver->isIncomplete());
    ASSERT(boost::filesystem::exists(repairFile));

    std::string mod("Collection mod");
    repairObserver->invalidatingModification(mod);

    auto opCtx = cc().makeOperationContext();
    Lock::GlobalWrite lock(opCtx.get());

    repairObserver->onRepairDone(opCtx.get());
    ASSERT(!repairObserver->isIncomplete());
    ASSERT(!boost::filesystem::exists(repairFile));

    ASSERT(repairObserver->isDone());
    ASSERT(repairObserver->isDataInvalidated());
    ASSERT_EQ(1U, repairObserver->getModifications().size());
    ASSERT(!hasReplConfig(opCtx.get()));
}

TEST_F(StorageRepairObserverTest, RepairIsIncompleteOnFailure) {
    auto repairObserver = getRepairObserver();

    auto repairFile = repairFilePath();
    ASSERT(!boost::filesystem::exists(repairFile));
    ASSERT(!repairObserver->isIncomplete());

    repairObserver->onRepairStarted();

    ASSERT(repairObserver->isIncomplete());
    ASSERT(boost::filesystem::exists(repairFile));

    // Assert that a failure to call onRepairDone does not remove the failure file.
    assertRepairIncompleteOnTearDown();
}

TEST_F(StorageRepairObserverTest, RepairIncompleteAfterRestart) {
    auto repairObserver = getRepairObserver();
    ASSERT(!repairObserver->isIncomplete());
    repairObserver->onRepairStarted();
    ASSERT(repairObserver->isIncomplete());

    repairObserver = reset();
    ASSERT(repairObserver->isIncomplete());

    // Assert that a failure to call onRepairStarted does not create the failure file.
    assertRepairIncompleteOnTearDown();
}

TEST_F(StorageRepairObserverTest, RepairCompleteAfterRestart) {
    auto repairObserver = getRepairObserver();
    ASSERT(!repairObserver->isIncomplete());
    repairObserver->onRepairStarted();
    ASSERT(repairObserver->isIncomplete());

    std::string mod("Collection mod");
    repairObserver->invalidatingModification(mod);

    auto opCtx = cc().makeOperationContext();
    Lock::GlobalWrite lock(opCtx.get());
    createMockReplConfig(opCtx.get());

    repairObserver->onRepairDone(opCtx.get());
    ASSERT(repairObserver->isDone());
    ASSERT_EQ(1U, repairObserver->getModifications().size());

    repairObserver = reset();
    ASSERT(!repairObserver->isIncomplete());
    // Done is reservered for completed operations.
    ASSERT(!repairObserver->isDone());
    assertReplConfigValid(opCtx.get(), false);
}

DEATH_TEST_F(StorageRepairObserverTest, FailsWhenDoneCalledFirst, "Invariant failure") {
    auto repairObserver = getRepairObserver();
    ASSERT(!repairObserver->isIncomplete());

    auto opCtx = cc().makeOperationContext();
    createMockReplConfig(opCtx.get());
    repairObserver->onRepairDone(opCtx.get());
}

DEATH_TEST_F(StorageRepairObserverTest, FailsWhenStartedCalledAfterDone, "Invariant failure") {
    auto repairObserver = getRepairObserver();
    ASSERT(!repairObserver->isIncomplete());
    repairObserver->onRepairStarted();
    ASSERT(repairObserver->isIncomplete());

    auto opCtx = cc().makeOperationContext();
    createMockReplConfig(opCtx.get());
    repairObserver->onRepairDone(opCtx.get());
    ASSERT(repairObserver->isDone());
    assertReplConfigValid(opCtx.get(), true);

    repairObserver->onRepairStarted();
}
}  // namespace
}  // namespace mongo

max_stars_repo_name: benety/mongo

max_issues_repo_name: benety/mongo

max_forks_repo_name: benety/mongo


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

#include <binary/span.hpp>

namespace mk = mikodev::binary;

namespace mikodev::binary::tests::span_tests
{
    BOOST_AUTO_TEST_CASE(span__constructor__empty)
    {
        mk::span span = mk::span();
        BOOST_REQUIRE_EQUAL(span.buffer(), nullptr);
        BOOST_REQUIRE_EQUAL(span.length(), 0);
    }

    BOOST_AUTO_TEST_CASE(span__constructor__unchecked_from_stack)
    {
        const char text[] = "Hello, world!";
        mk::span span = mk::span(reinterpret_cast<const_byte_ptr>(&text[0]), sizeof(text) - 1);
        BOOST_TEST_MESSAGE(reinterpret_cast<const char*>(span.buffer()));
        BOOST_REQUIRE_EQUAL(reinterpret_cast<const char*>(span.buffer()), &text[0]);
        BOOST_REQUIRE_EQUAL(span.length(), sizeof(text) - 1);
    }
}

max_stars_repo_name: afxres/binary-cxx

max_issues_repo_name: afxres/binary-cxx

max_forks_repo_name: afxres/binary-cxx


text:
//
// Simple example of using pybind based on http://pybind11.readthedocs.io/en/latest/basics.html
// but extended to use the Numpy-Eigen binding.
//
// Arun Venkatraman (arunvenk@cs.cmu.edu)
// December 2016
//

#include <pybind11/pybind11.h>

#include <Eigen/Dense>
#include <pybind11/eigen.h>
#include <pybind11/stl.h>

#include <experiments/single_obs_diffdrive.hh>

#include <experiments/simulators/circle_world.hh>

#include <array>
#include <sstream>
#include <tuple>

Eigen::MatrixXd add(const Eigen::MatrixXd &i, const Eigen::MatrixXd &j)
{
    return i + j;
}

namespace py = pybind11;

PYBIND11_PLUGIN(ilqr_diffdrive)
{
    using Circle = circle_world::Circle;
    using CircleWorld = circle_world::CircleWorld;

    py::module m("ilqr_diffdrive", "iLQR on DiffDrive dynamics.");

    py::enum_<PolicyTypes>(m, "PolicyTypes")
    .value("HINDSIGHT", PolicyTypes::HINDSIGHT)
    .value("TRUE_ILQR", PolicyTypes::TRUE_ILQR)
    .value("ARGMAX_ILQR", PolicyTypes::ARGMAX_ILQR)
    .value("PROB_WEIGHTED_CONTROL", PolicyTypes::PROB_WEIGHTED_CONTROL)
    .export_values()
    .def("__str__", &to_string);

    m.def("single_obs_control_diffdrive", [](PolicyTypes policy, bool has_obs, std::array<double, 2> prior)
            {
                std::string state_fname, obs_fname;
                const double cost_to_go
                    = single_obs_control_diffdrive(policy, has_obs, prior,
                        state_fname, obs_fname);
                return std::make_tuple(cost_to_go, state_fname, obs_fname);
            },
            "Function for controlling diffdrive.");

    m.def("control_diffdrive", [](PolicyTypes policy,
                CircleWorld &true_world,
                CircleWorld &other_world,
                std::array<double, 2> prior,
                std::string state_fname = "",
                std::string obs_fname = ""
                )
            {
                const double cost_to_go
                    = control_diffdrive(policy, true_world,
                        other_world, prior,
                        state_fname, obs_fname);
                return std::make_tuple(cost_to_go, state_fname, obs_fname);
            },
            "Function for controlling diffdrive.");

    py::class_<Circle>(m, "Circle")
        .def(py::init<const double, const double, const double>())
        .def(py::init<const double, const Eigen::Vector2d &>())
        .def_property("radius", (double (Circle::*)() const) &Circle::radius, [](Circle &c, double r) { c.radius() = r; })
        .def_property("position", (const Eigen::Vector2d& (Circle::*)() const) &Circle::position, [](Circle &c, const Eigen::Vector2d &p) { c.position() = p; })
        .def("__repr__", [](const Circle &c)
                {
                    std::ostringstream oss;
                    oss << "Circle(" << c.radius()
                    << ", [" << c.position().transpose() << "])";
                    return oss.str();
                });
        ;

    py::class_<CircleWorld>(m, "CircleWorld")
        .def(py::init<>())
        .def(py::init<const std::array<double, 4> &>())
        .def("add_obstacle", (void (CircleWorld::*)(const double, double, double)) &CircleWorld::add_obstacle)
        .def("add_obstacle", (void (CircleWorld::*)(const double, const Eigen::Vector2d&)) &CircleWorld::add_obstacle)
        .def("add_obstacle", (void (CircleWorld::*)(const Circle &)) &CircleWorld::add_obstacle)
        .def("dimensions", &CircleWorld::dimensions)
        .def_property("obstacles", (std::vector<Circle>& (CircleWorld::*)()) &CircleWorld::obstacles, [](CircleWorld &c, std::vector<Circle>& obs)
                {
                    c.obstacles() = obs;
                })
        .def("__repr__", [](const CircleWorld &w)
                {
                    auto dims = w.dimensions();
                    std::ostringstream oss;
                    oss << "CircleWorld(" << w.obstacles().size()
                    << " obstacles, world_size=[" << dims[0]
                    << " " << dims[1] << " " << dims[2]
                    << " " << dims[3] << "])";
                    return oss.str();
                });
        ;

    return m.ptr();
}

ext: cc