text:
#include "teca_cartesian_mesh_regrid.h"

#include "teca_cartesian_mesh.h"
#include "teca_array_collection.h"
#include "teca_variant_array.h"
#include "teca_metadata.h"
#include "teca_cartesian_mesh_util.h"

#include <algorithm>
#include <iostream>

#if defined(TECA_HAS_BOOST)
#include <boost/program_options.hpp>
#endif

using std::string;
using std::vector;
using std::cerr;
using std::endl;

//#define TECA_DEBUG

// convert an extent from the target coordinate system
// into an extent in the source coordinate system
// get the extent in the source
int convert_extent(
    const vector<unsigned long> &target_ext,
    const const_p_teca_variant_array &target_x,
    const const_p_teca_variant_array &target_y,
    const const_p_teca_variant_array &target_z,
    const const_p_teca_variant_array &source_x,
    const const_p_teca_variant_array &source_y,
    const const_p_teca_variant_array &source_z,
    vector<unsigned long> &source_ext)
{
    NESTED_TEMPLATE_DISPATCH_FP(
        const teca_variant_array_impl,
        target_x.get(),
        1,

        const NT1 *p_target_x = std::dynamic_pointer_cast<TT1>(target_x)->get();
        const NT1 *p_target_y = std::dynamic_pointer_cast<TT1>(target_y)->get();
        const NT1 *p_target_z = std::dynamic_pointer_cast<TT1>(target_z)->get();

        NESTED_TEMPLATE_DISPATCH_FP(
            const teca_variant_array_impl,
            source_x.get(),
            2,

            const NT2 *p_source_x = std::dynamic_pointer_cast<TT2>(source_x)->get();
            const NT2 *p_source_y = std::dynamic_pointer_cast<TT2>(source_y)->get();
            const NT2 *p_source_z = std::dynamic_pointer_cast<TT2>(source_z)->get();

            return bounds_to_extent(
                static_cast<NT2>(p_target_x[target_ext[0]]),
                static_cast<NT2>(p_target_x[target_ext[1]]),
                static_cast<NT2>(p_target_y[target_ext[2]]),
                static_cast<NT2>(p_target_y[target_ext[3]]),
                static_cast<NT2>(p_target_z[target_ext[4]]),
                static_cast<NT2>(p_target_z[target_ext[5]]),
                p_source_x, p_source_y, p_source_z,
                source_x->size() - 1,
                source_y->size() - 1,
                source_z->size() - 1,
                true, source_ext);
            )
        )

    // unsupported coordinate type
    return -1;
}

// 0 order (nearest neighbor) interpolation
// for nodal data on stretched cartesian mesh.
template<typename CT, typename DT>
int interpolate_nearest(
    CT cx,
    CT cy,
    CT cz,
    const CT *p_x,
    const CT *p_y,
    const CT *p_z,
    const DT *p_data,
    unsigned long ihi,
    unsigned long jhi,
    unsigned long khi,
    unsigned long nx,
    unsigned long nxy,
    DT &val)
{
    // get i,j of node less than cx,cy
    unsigned long i = 0;
    unsigned long j = 0;
    unsigned long k = 0;

    if ((ihi && index_of(p_x, 0, ihi, cx, true, i))
        || (jhi && index_of(p_y, 0, jhi, cy, true, j))
        || (khi && index_of(p_z, 0, khi, cz, true, k)))
    {
        // cx,cy,cz is outside the coordinate axes
        return -1;
    }

    // get i,j of node greater than cx,cy
    unsigned long ii = std::min(i + 1, ihi);
    unsigned long jj = std::min(j + 1, jhi);
    unsigned long kk = std::min(k + 1, khi);

    // get index of nearest node
    unsigned long p = (cx - p_x[i]) <= (p_x[ii] - cx) ? i : ii;
    unsigned long q = (cy - p_y[j]) <= (p_y[jj] - cy) ? j : jj;
    unsigned long r = (cz - p_z[k]) <= (p_z[kk] - cz) ? k : kk;

    // assign value from nearest node
    val = p_data[p + nx*q + nxy*r];
    return 0;
}

// --------------------------------------------------------------------------
teca_cartesian_mesh_regrid::teca_cartesian_mesh_regrid()
    : interpolation_mode(nearest)
{
    this->set_number_of_input_connections(2);
    this->set_number_of_output_ports(1);
}

// --------------------------------------------------------------------------
teca_cartesian_mesh_regrid::~teca_cartesian_mesh_regrid()
{}

#if defined(TECA_HAS_BOOST)

// --------------------------------------------------------------------------
void teca_cartesian_mesh_regrid::get_properties_description(
    const string &prefix, options_description &global_opts)
{
    options_description opts("Options for " + prefix + "(teca_cartesian_mesh_regrid)");

    opts.add_options()
        TECA_POPTS_GET(vector<string>, prefix, source_arrays, "list of arrays to move from source to target mesh")
        TECA_POPTS_GET(int, prefix, interpolation_mode, "linear or nearest interpolation")
        ;

    global_opts.add(opts);
}

// --------------------------------------------------------------------------
void teca_cartesian_mesh_regrid::set_properties(
    const string &prefix, variables_map &opts)
{
    TECA_POPTS_SET(opts, vector<string>, prefix, source_arrays)
    TECA_POPTS_SET(opts, int, prefix, interpolation_mode)
}

#endif

// --------------------------------------------------------------------------
void teca_cartesian_mesh_regrid::clear_source_arrays()
{
    this->source_arrays.clear();
    this->set_modified();
}

// --------------------------------------------------------------------------
void teca_cartesian_mesh_regrid::add_source_array(const std::string &array)
{
    this->source_arrays.push_back(array);
    this->set_modified();
}

// --------------------------------------------------------------------------
teca_metadata teca_cartesian_mesh_regrid::get_output_metadata(
    unsigned int port,
    const std::vector<teca_metadata> &input_md)
{
#ifdef TECA_DEBUG
    cerr << teca_parallel_id()
        << "teca_cf_reader::get_output_metadata" << endl;
#endif
    (void)port;

    // start with a copy of metadata from the target
    teca_metadata output_md(input_md[0]);

    // get target metadata
    vector<string> target_vars;
    input_md[0].get("variables", target_vars);

    vector<string> target_time_vars;
    input_md[0].get("time variables", target_time_vars);

    teca_metadata target_atts;
    input_md[0].get("attributes", target_atts);

    // get source metadata
    vector<string> source_vars;
    input_md[0].get("variables", source_vars);

    vector<string> source_time_vars;
    input_md[0].get("time variables", source_time_vars);

    teca_metadata source_atts;
    input_md[0].get("attributes", source_atts);

    // merge metadata from source and target
    // varibales and time_vars should be unique lists.
    // attributes are indexed by variable names
    // in the case of collisions, the target variable
    // is kept, the source variable is ignored
    size_t n_source_vars = source_vars.size();
    for (size_t i = 0; i < n_source_vars; ++i)
    {
        const string &source = source_vars[i];

        // check that there's not a variable of that same name in target
        vector<string>::iterator first = target_vars.begin();
        vector<string>::iterator last = target_vars.end();
        if (find(first, last, source) == last)
        {
            // not present in target, ok to add it
            target_vars.push_back(source);

            teca_metadata atts;
            source_atts.get(source, atts);
            target_atts.insert(source, atts);

            // check if it's a time var as well
            first = source_time_vars.begin();
            last = source_time_vars.end();
            if (find(first, last, source) != last)
                target_time_vars.push_back(source);
        }

    }

    // update with merged lists
    output_md.insert("variables", target_vars);
    output_md.insert("time variables", target_time_vars);
    output_md.insert("attributes", target_atts);

    return output_md;
}

// --------------------------------------------------------------------------
std::vector<teca_metadata> teca_cartesian_mesh_regrid::get_upstream_request(
    unsigned int port,
    const std::vector<teca_metadata> &input_md,
    const teca_metadata &request)
{
    (void)port;

    vector<teca_metadata> up_reqs(2);

    // compose the target request
    teca_metadata target_req(request);

    // clear our keys
    target_req.remove("regrid_source_arrays");

    // remove reqeust for any arrays that should come from
    // the source
    vector<string> req_target_arrays;
    request.get("arrays", req_target_arrays);
    size_t n_target_arrays = this->source_arrays.size();
    for (size_t i = 0; i < n_target_arrays; ++i)
    {
        vector<string>::iterator it;
        vector<string>::iterator first = req_target_arrays.begin();
        vector<string>::iterator last = req_target_arrays.end();
        if ((it = find(first, last, this->source_arrays[i])) != last)
        {
            // erase
            *it = req_target_arrays.back();
            req_target_arrays.pop_back();
        }
    }
    target_req.insert("arrays", req_target_arrays);

    // compose the source request
    // merge in named arrays
    vector<string> arrays;
    request.get("regrid_source_arrays", arrays);

    std::copy(this->source_arrays.begin(),
        this->source_arrays.end(), std::back_inserter(arrays));

    // get the target extent and coordinates
    vector<unsigned long> target_extent(6, 0l);
    request.get("extent", target_extent);

    teca_metadata target_coords;
    p_teca_variant_array target_x;
    p_teca_variant_array target_y;
    p_teca_variant_array target_z;

    if (input_md[0].get("coordinates", target_coords)
        || !(target_x = target_coords.get("x"))
        || !(target_y = target_coords.get("y"))
        || !(target_z = target_coords.get("z")))
    {
        TECA_ERROR("failed to locate target mesh coordinates")
        return up_reqs;
    }

    // get the source extent and coordinates
    teca_metadata source_coords;
    p_teca_variant_array source_x;
    p_teca_variant_array source_y;
    p_teca_variant_array source_z;

    if (input_md[1].get("coordinates", source_coords)
        || !(source_x = source_coords.get("x"))
        || !(source_y = source_coords.get("y"))
        || !(source_z = source_coords.get("z")))
    {
        TECA_ERROR("failed to locate source mesh coordinates")
        return up_reqs;
    }

    // map the target extent to the source mesh
    vector<unsigned long> source_extent(6, 0l);
    if (convert_extent(
        target_extent,
        target_x, target_y, target_z,
        source_x, source_y, source_z,
        source_extent))
    {
        TECA_ERROR("failed to convert from target to source extent")
        return up_reqs;
    }

    // build the request
    teca_metadata source_req(target_req);
    source_req.insert("arrays", arrays);
    source_req.insert("extent", source_extent);

    // send the requests up
    up_reqs[0] = target_req;
    up_reqs[1] = source_req;

    return up_reqs;
}

// --------------------------------------------------------------------------
const_p_teca_dataset teca_cartesian_mesh_regrid::execute(
    unsigned int port,
    const std::vector<const_p_teca_dataset> &input_data,
    const teca_metadata &request)
{
#ifdef TECA_DEBUG
    cerr << teca_parallel_id()
        << "teca_cartesian_mesh_regrid::execute" << endl;
#endif
    (void)port;

    p_teca_cartesian_mesh in_target
        = std::dynamic_pointer_cast<teca_cartesian_mesh>(
            std::const_pointer_cast<teca_dataset>(input_data[0]));

    const_p_teca_cartesian_mesh source
        = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[1]);

    if (!in_target || !source)
    {
        TECA_ERROR("invalid input. target invalid "
            << !in_target << " source invalid " << !source )
        return nullptr;
    }

    // create the output
    p_teca_cartesian_mesh target = teca_cartesian_mesh::New();
    target->shallow_copy(in_target);

    // get the source and targent extents
    vector<unsigned long> source_ext;
    source->get_extent(source_ext);

    vector<unsigned long> target_ext;
    target->get_extent(target_ext);

    // get the list of arrays to move
    vector<string> source_arrays;
    request.get("regrid_source_source_arrays", source_arrays);
    std::copy(this->source_arrays.begin(),
        this->source_arrays.end(), std::back_inserter(source_arrays));

    // move the arrays
    const_p_teca_variant_array target_xc = target->get_x_coordinates();
    const_p_teca_variant_array target_yc = target->get_y_coordinates();
    const_p_teca_variant_array target_zc = target->get_z_coordinates();
    p_teca_array_collection target_ac = target->get_point_arrays();

    unsigned long target_nx = target_xc->size();
    unsigned long target_ny = target_yc->size();
    unsigned long target_nz = target_zc->size();
    unsigned long target_size = target_nx*target_ny*target_nz;

    const_p_teca_variant_array source_xc = source->get_x_coordinates();
    const_p_teca_variant_array source_yc = source->get_y_coordinates();
    const_p_teca_variant_array source_zc = source->get_z_coordinates();
    const_p_teca_array_collection source_ac = source->get_point_arrays();

    unsigned long source_nx = source_xc->size();
    unsigned long source_ny = source_yc->size();
    unsigned long source_nz = source_zc->size();
    unsigned long source_nxy = source_nx*source_ny;
    unsigned long source_ihi = source_nx - 1;
    unsigned long source_jhi = source_ny - 1;
    unsigned long source_khi = source_nz - 1;

    NESTED_TEMPLATE_DISPATCH_FP(
        const teca_variant_array_impl,
        target_xc.get(),
        1,

        const NT1 *p_target_xc = std::dynamic_pointer_cast<TT1>(target_xc)->get();
        const NT1 *p_target_yc = std::dynamic_pointer_cast<TT1>(target_yc)->get();
        const NT1 *p_target_zc = std::dynamic_pointer_cast<TT1>(target_zc)->get();

        NESTED_TEMPLATE_DISPATCH_FP(
            const teca_variant_array_impl,
            source_xc.get(),
            2,

            const NT2 *p_source_xc = std::dynamic_pointer_cast<TT2>(source_xc)->get();
            const NT2 *p_source_yc = std::dynamic_pointer_cast<TT2>(source_yc)->get();
            const NT2 *p_source_zc = std::dynamic_pointer_cast<TT2>(source_zc)->get();

            size_t n_arrays = source_arrays.size();
            for (size_t i = 0; i < n_arrays; ++i)
            {
                const_p_teca_variant_array source_a = source_ac->get(source_arrays[i]);
                p_teca_variant_array target_a = source_a->new_instance();
                target_a->resize(target_size);

                NESTED_TEMPLATE_DISPATCH(
                    teca_variant_array_impl,
                    target_a.get(),
                    3,

                    const NT3 *p_source_a = std::dynamic_pointer_cast<const TT3>(source_a)->get();
                    NT3 *p_target_a = std::dynamic_pointer_cast<TT3>(target_a)->get();

                    unsigned long q = 0;
                    for (unsigned long k = 0; k < target_nz; ++k)
                    {
                        for (unsigned long j = 0; j < target_ny; ++j)
                        {
                            for (unsigned long i = 0; i < target_nx; ++i, ++q)
                            {
                                if (interpolate_nearest<NT2,NT3>(
                                    static_cast<NT2>(p_target_xc[i]),
                                    static_cast<NT2>(p_target_yc[j]),
                                    static_cast<NT2>(p_target_zc[k]),
                                    p_source_xc, p_source_yc, p_source_zc,
                                    p_source_a, source_ihi, source_jhi, source_khi,
                                    source_nx, source_nxy,
                                    p_target_a[q]))
                                {
                                    TECA_ERROR("failed to interpolate " << i << ", " << j << ", " << k)
                                    return nullptr;
                                }
                            }
                        }
                    }

                    target_ac->set(source_arrays[i], target_a);
                    )
                }
                )
            )

    return target;
}

ext: cxx


text:
#include "StoreElementTest.h"

#include <algorithm>
#include <boost/foreach.hpp>

namespace ddj {
namespace store {

	TEST_F(StoreElementTest, Constructor)
	{
		EXPECT_TRUE(_element != nullptr);
		ASSERT_EQ(24, sizeof(*_element) );
	}

	TEST_F(StoreElementTest, Sort)
	{
		const int len = 10;
		storeElement elements[len];

		for (int i=0;i<len;i++)
	    {
	        elements[i].time = len-i-1;
	    }

		std::sort(elements, elements+len, OrderStoreElementByTimeAsc());

		for (int i=0;i<len;i++)
	    {
	        ASSERT_EQ(elements[i].time, i);
	    }
	}
}}

ext: cpp

max_stars_repo_name: d-d-j/gpuStore

max_issues_repo_name: d-d-j/gpuStore

max_forks_repo_name: d-d-j/gpuStore


text:
// Copyright (C) 2004-2012 The Trustees of Indiana University.

// 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)

//  Authors: Nicholas Edmonds
//           Andrew Lumsdaine

// Example usage of delta_stepping_shortest_paths algorithm

#include <am++/am++.hpp>

// Communicate via MPI
#include <am++/mpi_transport.hpp>

// Enable PBGL interfaces to BGL algorithms
#include <boost/graph/use_mpi.hpp>

// Distributed adjacency list -- NOTE: The graph class needs to be included before any algorithms
#include <boost/graph/distributed/adjacency_list.hpp>

// Dijkstra's single-source shortest paths algorithm
#include <boost/graph/distributed/delta_stepping_shortest_paths.hpp>

// METIS Input
#include <boost/graph/metis.hpp>

// Graphviz Output
#include <boost/graph/distributed/graphviz.hpp>

// Standard Library includes
#include <fstream>
#include <string>

#ifdef BOOST_NO_EXCEPTIONS
void
boost::throw_exception(std::exception const& ex)
{
    std::cout << ex.what() << std::endl;
    abort();
}
#endif

typedef int weight_type;

// Edge property bundle
struct WeightedEdge {
  WeightedEdge(weight_type weight = 0) : weight(weight) { }

  weight_type weight;
};

// Vertex property bundle
struct VertexProperties {
  VertexProperties(weight_type d = 0) : distance(d) { }

  weight_type distance;
};

// Define MPI datatypes for bundled properties so AM++ can send messages containing them
namespace amplusplus {
  template<>
  struct make_mpi_datatype<WeightedEdge> : make_mpi_datatype_base {
    make_mpi_datatype<weight_type> dt1;
    scoped_mpi_datatype dt;
    make_mpi_datatype(): dt1() {
      int blocklengths[1] = {1};
      MPI_Aint displacements[1];
      WeightedEdge test_object;
      MPI_Aint test_object_ptr;
      MPI_Get_address(&test_object, &test_object_ptr);
      MPI_Get_address(&test_object.weight, &displacements[0]);
      displacements[0] -= test_object_ptr;
      MPI_Datatype types[1] = {dt1.get()};
      MPI_Type_create_struct(1, blocklengths, displacements, types, dt.get_ptr());
      MPI_Type_commit(dt.get_ptr());
    }
    MPI_Datatype get() const {return dt;}
  };

  template<>
  struct make_mpi_datatype<VertexProperties> : make_mpi_datatype_base {
    make_mpi_datatype<weight_type> dt1;
    scoped_mpi_datatype dt;
    make_mpi_datatype(): dt1() {
      int blocklengths[1] = {1};
      MPI_Aint displacements[1];
      VertexProperties test_object;
      MPI_Aint test_object_ptr;
      MPI_Get_address(&test_object, &test_object_ptr);
      MPI_Get_address(&test_object.distance, &displacements[0]);
      displacements[0] -= test_object_ptr;
      MPI_Datatype types[1] = {dt1.get()};
      MPI_Type_create_struct(1, blocklengths, displacements, types, dt.get_ptr());
      MPI_Type_commit(dt.get_ptr());
    }
    MPI_Datatype get() const {return dt;}
  };
}

using namespace boost;

/* An undirected graph with distance values stored on the vertices. */
typedef adjacency_list<vecS, distributedS<vecS>, directedS,
                       VertexProperties, WeightedEdge>
  Graph;

int main(int argc, char* argv[])
{
  amplusplus::environment env = amplusplus::mpi_environment(argc, argv);
  amplusplus::transport trans = env.create_transport();

  // Parse command-line options
  const char* filename = "weighted_graph.gr";
  if (argc > 1) filename = argv[1];

  // Open the METIS input file
  std::ifstream in(filename);
  graph::metis_reader reader(in);

  // Load the graph using the default distribution
  Graph g(reader.begin(), reader.end(), reader.weight_begin(),
          reader.num_vertices(), trans);

  // Get vertex 0 in the graph
  graph_traits<Graph>::vertex_descriptor start = vertex(0, g);

  // Initialize delta stepping algorithm
  boost::graph::distributed::delta_stepping_shortest_paths<Graph,
    boost::property_map<Graph, weight_type VertexProperties::*>::type,
    boost::property_map<Graph, weight_type WeightedEdge::*>::type>
      D(g, get(&VertexProperties::distance, g), get(&WeightedEdge::weight, g));

  // Compute shortest paths from vertex 0
  D.run(start);

  // Output a Graphviz DOT file
  std::string outfile = filename;
  if (argc > 2)
    outfile = argv[2];
  else {
    size_t i = outfile.rfind('.');
    if (i > 0 && i != std::string::npos)
      outfile.erase(outfile.begin() + i, outfile.end());
    outfile += "-dijkstra.dot";
  }

  if (trans.rank() == 0) {
    std::cout << "Writing GraphViz output to " << outfile << "... ";
    std::cout.flush();
  }
  write_graphviz(outfile, g,
                 make_label_writer(get(&VertexProperties::distance, g)),
                 make_label_writer(get(&WeightedEdge::weight, g)));
  if (trans.rank() == 0)
    std::cout << "Done." << std::endl;

  return 0;
}

max_stars_repo_name: thejkane/AGM

max_issues_repo_name: thejkane/AGM

max_forks_repo_name: thejkane/AGM


text:
#include "generation-gui.h"

#include <imgui/imgui.h>
#include <Eigen/Dense>
#include <glm/gtc/type_ptr.hpp>
#include <string>

#include "gui/icons-awesome.h"
#include "maths/rbf.h"
#include "components/graphics/material.h"
#include "components/physics/transform.h"

GenerationGui::GenerationGui(Context& ctx, SingletonComponents& scomps)
    : m_ctx(ctx), m_scomps(scomps)
{
    m_controlPointsXYZ.push_back(glm::ivec3(10, 10, 10));
    m_controlPointsWeights.push_back(5);
    m_controlPointsXYZ.push_back(glm::ivec3(0, 0, 0));
    m_controlPointsWeights.push_back(5);
}

GenerationGui::~GenerationGui() {}

void GenerationGui::update() {
    ImGui::Begin(ICON_FA_SEEDLING "  Generation", 0);
        if (ImGui::Button("Add control point")) {
            m_controlPointsXYZ.push_back(glm::ivec3(0, 0, 0));
            m_controlPointsWeights.push_back(1);
        }

        if (m_controlPointsXYZ.size() > 2)
            if (ImGui::Button("Remove control point")) {
                m_controlPointsXYZ.pop_back();
                m_controlPointsWeights.push_back(1);
            }

        ImGui::Spacing();
        ImGui::Separator();
        ImGui::Spacing();

        for (unsigned int i = 0; i < m_controlPointsXYZ.size(); i++) {
            ImGui::SliderFloat(std::to_string(i).c_str(), &m_controlPointsWeights.at(i), 1, 30);
            ImGui::SliderInt3(std::to_string(i).c_str(), (int*) glm::value_ptr(m_controlPointsXYZ.at(i)), 0, 20);
            ImGui::Separator();
        }

        ImGui::Separator();
        ImGui::Spacing();

        if (ImGui::Button("Generate")) {
            Eigen::VectorXd controlPointWeights(m_controlPointsXYZ.size());
            for (unsigned int i = 0; i < m_controlPointsWeights.size(); i++) {
                controlPointWeights[i] = m_controlPointsWeights.at(i);
            }

            std::vector<glm::ivec3> coordWithYtoFind;
            std::vector<met::entity> entityToChange;
            m_ctx.registry.view<comp::Transform>().each([&](met::entity id, comp::Transform& transform){
                coordWithYtoFind.push_back(transform.position);
                entityToChange.push_back(id);
            });
            voxmt::rbfInterpolate(coordWithYtoFind, m_controlPointsXYZ, controlPointWeights, voxmt::RBFType::LINEAR, 0.5f, voxmt::RBFTransformAxis::Y);

            for (size_t i = 0; i < coordWithYtoFind.size(); i++) {
                comp::Transform& trans =  m_ctx.registry.get<comp::Transform>(entityToChange.at(i));
                trans.position = coordWithYtoFind.at(i);
            }

        }
    ImGui::End();
}

void GenerationGui::onEvent(GuiEvent e) {

}

max_stars_repo_name: guillaume-haerinck/voxel-editor

max_issues_repo_name: guillaume-haerinck/voxel-editor

max_forks_repo_name: guillaume-haerinck/voxel-editor


text:
#include <boost/test/unit_test.hpp>
#include "algorithms/data_structures/sll/palindrome_sll.hpp"

BOOST_AUTO_TEST_SUITE(PalindromSLL)

BOOST_AUTO_TEST_CASE(empty_list)
{
    NodeSLL<int>* sll = nullptr;
    BOOST_CHECK(true == Algo::DS::SLL::PalindromeDetection::IsPalindrome(sll));
    DeleteSLL(&sll);
}

BOOST_AUTO_TEST_CASE(valid_palindrome)
{
    {
        NodeSLL<int>* sll = CreateSLL<int>({10, 9, 9, 10});
        BOOST_CHECK(true ==
                    Algo::DS::SLL::PalindromeDetection::IsPalindrome(sll));
        DeleteSLL(&sll);
    }

    {
        NodeSLL<int>* sll = CreateSLL<int>({3, 2, 1, 2, 3});
        BOOST_CHECK(true ==
                    Algo::DS::SLL::PalindromeDetection::IsPalindrome(sll));
        DeleteSLL(&sll);
    }
}

BOOST_AUTO_TEST_CASE(not_palindrome)
{
    NodeSLL<int>* sll = CreateSLL<int>({10, 9, 8, 7});
    BOOST_CHECK(false == Algo::DS::SLL::PalindromeDetection::IsPalindrome(sll));
    DeleteSLL(&sll);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: iamantony/CppNotes

max_issues_repo_name: iamantony/CppNotes

max_forks_repo_name: iamantony/CppNotes


text:
#ifndef __IRODS_PLUGIN_CONTEXT_HPP__
#define __IRODS_PLUGIN_CONTEXT_HPP__

// =-=-=-=-=-=-=-
// stl includes
#include <string>
#include <boost/pointer_cast.hpp>

// =-=-=-=-=-=-=-
#include "irods_plugin_base.hpp"
#include "irods_first_class_object.hpp"

namespace irods {
// =-=-=-=-=-=-=-
// base context class for communicating to plugins
    class plugin_context {
        public:
            // =-=-=-=-=-=-=-
            // ctor
            plugin_context(
                plugin_property_map&   _prop_map,
                first_class_object_ptr _fco,
                const std::string&     _results )  :
                comm_( 0 ),
                prop_map_( _prop_map ),
                fco_( _fco ),
                results_( _results )  {

            } // ctor

            // =-=-=-=-=-=-=-
            // ctor
            plugin_context(
                rsComm_t*              _comm,
                plugin_property_map&   _prop_map,
                first_class_object_ptr _fco,
                const std::string&     _results )  :
                comm_( _comm ),
                prop_map_( _prop_map ),
                fco_( _fco ),
                results_( _results )  {

            } // ctor

            // =-=-=-=-=-=-=-
            // dtor
            virtual ~plugin_context() {

            } // dtor

            // =-=-=-=-=-=-=-
            // test to determine if contents are valid
            virtual error valid() {
                return SUCCESS();

            } // valid

            // =-=-=-=-=-=-=-
            // test to determine if contents are valid
            template < typename OBJ_TYPE >
            error valid() {
                // trap case of incorrect type for first class object
                return boost::dynamic_pointer_cast< OBJ_TYPE >( fco_.get() ) == NULL ?
                    ERROR( INVALID_DYNAMIC_CAST, "invalid type for fco cast" ) :
                    valid();

            } // valid

            // =-=-=-=-=-=-=-
            // accessors
            virtual rsComm_t* comm() {
                return comm_;
            }

            virtual plugin_property_map&   prop_map()     {
                return prop_map_;
            }
            virtual first_class_object_ptr fco()          {
                return fco_;
            }
            virtual const std::string      rule_results() {
                return results_;
            }

            // =-=-=-=-=-=-=-
            // mutators
            virtual void comm( rsComm_t* _c ) {
                comm_ = _c;
            }

            virtual void rule_results( const std::string& _s ) {
                results_ = _s;
            }

        protected:
            // =-=-=-=-=-=-=-
            // attributes
            rsComm_t*              comm_;      // server connection handle
            plugin_property_map&   prop_map_;  // resource property map
            first_class_object_ptr fco_;       // first class object in question
            std::string            results_;   // results from the pre op rule call

    }; // class plugin_context

/// =-=-=-=-=-=-=-
/// @brief type for the generic plugin operation
    typedef error( *plugin_operation )( plugin_context&, ... );

}; // namespace irods

#endif // __IRODS_PLUGIN_CONTEXT_HPP__

ext: hpp

max_stars_repo_name: nesi/irods

max_issues_repo_name: nesi/irods

max_forks_repo_name: nesi/irods


text:
//******************************************************************************
// RCF - Remote Call Framework
//
// Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
// http://www.deltavsoft.com
//
// RCF is distributed under dual licenses - closed source or GPL.
// Consult your particular license for conditions of use.
//
// If you have not purchased a commercial license, you are using RCF
// under GPL terms.
//
// Version: 2.0
// Contact: support <at> deltavsoft.com
//
//******************************************************************************

#ifndef INCLUDE_SF_ARCHIVE_HPP
#define INCLUDE_SF_ARCHIVE_HPP

#include <boost/noncopyable.hpp>

#include <RCF/Export.hpp>

#include <SF/DataPtr.hpp>

namespace SF {

    class IStream;
    class OStream;

    class RCF_EXPORT Archive : boost::noncopyable
    {
    public:

        enum Direction
        {
            READ,
            WRITE
        };

        enum Flag
        {
            PARENT              = 1 << 0,
            POINTER             = 1 << 1,
            NODE_ALREADY_READ   = 1 << 2,
            NO_BEGIN_END        = 1 << 3,
            POLYMORPHIC         = 1 << 4
        };

        Archive(Direction dir, IStream *stream);
        Archive(Direction dir, OStream *stream);

        Archive &   operator&(Flag flag);
        bool        isRead() const;
        bool        isWrite() const;
        IStream *   getIstream() const;
        OStream *   getOstream() const;
        bool        isFlagSet(Flag flag) const;
        void        setFlag(Flag flag, bool bEnable = true);
        void        clearFlag(Flag flag);
        void        clearState();
        DataPtr &   getLabel();
        bool        verifyAgainstArchiveSize(std::size_t bytesToRead);

        int         getRuntimeVersion();
        int         getArchiveVersion();

    private:

        Direction       mDir;
        IStream *       mIstream;
        OStream *       mOstream;
        DataPtr         mLabel;
        unsigned int    mFlags;
    };

}

#include <SF/Serializer.hpp>

#endif // ! INCLUDE_SF_ARCHIVE_HPP

max_stars_repo_name: ASMlover/study

max_issues_repo_name: ASMlover/study

max_forks_repo_name: ASMlover/study


text:
/*Authors: Marcin Zalewski / Jesun Sahariar Firoz*/

#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <limits>
#include <map>
#include <mutex>
#include <numeric>
#include <regex>
#include <sstream>
#include <sys/time.h>
#include <utility>
#include <vector>

#include <extensions/allocator/allocator.hpp>
#include <upcxx/allocate.hpp>
#include <upcxx/atomic.hpp>
#include <upcxx/backend.hpp>
#include <upcxx/rget.hpp>
#include <upcxx/rpc.hpp>
#include <upcxx/rput.hpp>
#include <upcxx/upcxx.hpp>

#include <boost/asio.hpp>
#include <boost/dynamic_bitset.hpp>

#if defined NDEBUG
const bool  debug{false};
#else
const bool debug{true};
#endif
#define dout \
    if (!debug) {} \
    else std::cerr

namespace ip = boost::asio::ip;

typedef unsigned long long ve_type;
typedef uint64_t           IndexType;

using element                     = std::tuple<ve_type, ve_type>;
using edge_list                   = std::vector<std::tuple<ve_type, ve_type>>;
std::string edgelistFile          = "";
uint64_t    num_vertices          = 0;
uint64_t    num_vertices_per_rank = 0;

// retain a per-destination queue for current and next iteration
std::vector<std::vector<std::pair<uint64_t, uint64_t>,
                        upcxxc::allocator<std::pair<uint64_t, uint64_t>>>>
    nextFrontierQarr[2];
// received buffer is never exported, so no need for current and next
std::vector<std::pair<uint64_t, uint64_t>> received_buffer;

double GetCurrentTime() {
  static struct timeval  tv;
  static struct timezone tz;
  gettimeofday(&tv, &tz);
  return tv.tv_sec + 1.e-6 * tv.tv_usec;
}

double TimeDifference(double& a, double& b) { return 1000 * (b - a); }

double ElapsedMillis(double start, double stop) {
  return TimeDifference(start, stop);
}

struct gptr_and_len {
  upcxx::global_ptr<uint64_t> p;    // pointer to first element in adjacencies
  int                         n;    // number of elements
};

struct gptr_and_len_pair {
  upcxx::global_ptr<std::pair<uint64_t, uint64_t>>
      p;    // pointer to first element in destination buffer
  int n;    // number of elements
};

std::vector<upcxx::global_ptr<gptr_and_len>> bases;

using BaseType = std::vector<upcxx::global_ptr<gptr_and_len>>;

using BaseQType = std::vector<upcxx::global_ptr<gptr_and_len_pair>>;

uint64_t index_to_vertex_id(size_t index) {
  // muliply for rows, add for row offset
  return index * upcxx::rank_n() + upcxx::rank_me();
}

size_t vertex_id_to_index(uint64_t vertex_id) {
  // It's ok to round off, as every vertex in a row in cyclic dist. will have the same index on every rank
  return vertex_id / upcxx::rank_n();
}

auto print_graph() {
  // For each vertex
  for (uint64_t i = 0; i < num_vertices_per_rank; i++) {
    const auto vtx_ptr =
        bases[upcxx::rank_me()].local()
            [i];    // <--This gives the local ptr to the gbl ptr and length for a vtx
    const auto adj_list_start = vtx_ptr.p.local();
    const auto adj_list_len   = vtx_ptr.n;

    auto current_vertex_id = index_to_vertex_id(i);

    std::cout << "i = " << i << ", vertex id = " << current_vertex_id
              << ", adjs: ";
    // For each neighbor of the vertex, get the adjacency  list and do the set intersection.
    for (auto j = 0; j < vtx_ptr.n; j++) {
      auto neighbor = adj_list_start[j];
      std::cout << neighbor << ", ";
    }
    std::cout << std::endl;
  }
}

upcxx::intrank_t vertex_id_to_rank(uint64_t v_id) {
  return v_id % upcxx::rank_n();
}

auto vertex_id_to_offset(uint64_t v_id) { return v_id / upcxx::rank_n(); }

void init_adjs(std::istream& infile, BaseType& bases) {
  infile.read(reinterpret_cast<char*>(&num_vertices), sizeof(num_vertices));
  std::cout << num_vertices << std::endl;

  bases.reserve(upcxx::rank_n());
  num_vertices_per_rank =
      (num_vertices + upcxx::rank_n() - 1 - upcxx::rank_me()) / upcxx::rank_n();
  std::cout << "No of vertices per rank: " << num_vertices_per_rank
            << std::endl;
  bases[upcxx::rank_me()] =
      upcxx::new_array<gptr_and_len>(num_vertices_per_rank);

  for (int r = 0; r < upcxx::rank_n(); r++) {
    bases[r] = upcxx::broadcast(bases[r], r).wait();
  }

  for (uint64_t i = upcxx::rank_me(); i < num_vertices; i += upcxx::rank_n()) {
    gptr_and_len pn;
    uint64_t     adj_indices[2];
    const auto   index_seekg = 1 + i;
    infile.seekg(index_seekg * sizeof(uint64_t), infile.beg);
    infile.read(reinterpret_cast<char*>(adj_indices), 2 * sizeof(uint64_t));
    auto cur_adj_len = adj_indices[1] - adj_indices[0];
    pn.n             = cur_adj_len;
    pn.p                      = upcxx::new_array<uint64_t>(cur_adj_len);
    const auto adj_list_seekg = 2 + num_vertices + adj_indices[0];
    infile.seekg(adj_list_seekg * sizeof(uint64_t), infile.beg);
    infile.read(reinterpret_cast<char*>(pn.p.local()),
                cur_adj_len * sizeof(uint64_t));
    for (auto edg = 0; edg < cur_adj_len; edg++) {
      std::cout << pn.p.local()[edg] << " ";
    }

    const auto base_index                       = vertex_id_to_index(i);
    bases[upcxx::rank_me()].local()[base_index] = pn;
  }
}

void readBinaryFormat(const std::string& filename, BaseType& bases) {
  std::ifstream inputFile;
  inputFile.exceptions(std::ifstream::failbit);
  try {
    inputFile.open(filename);
    init_adjs(inputFile, bases);
    inputFile.close();
  } catch (std::ios_base::failure& fail) {
    std::cerr << "Something went wrong with reading the matrix from file "
              << filename << std::endl;
    throw fail;
  }
}

int main(int argc, char* argv[]) {
  upcxx::init();

  boost::asio::io_service io_service;

  std::string h = ip::host_name();
  std::cout << "hostname: " << h << 'n';

  int         argIndex = 1;
  std::string arg_t(argv[argIndex]);
  uint64_t    source = 0;
  while (argIndex < argc) {
    std::string arg(argv[argIndex]);
    if (arg == "--edgelistfile") {
      ++argIndex;
      edgelistFile = std::string(argv[argIndex]);
      ++argIndex;
    }
    if (arg == "--source") {
      ++argIndex;
      source = std::stoul(argv[argIndex], nullptr, 0);
      ++argIndex;
    }
  }
  readBinaryFormat(edgelistFile, bases);

  upcxx::barrier();

  boost::dynamic_bitset<> color_map(num_vertices_per_rank);
  std::vector<uint64_t>   parent_map(num_vertices_per_rank);

  auto level               = 0;
  auto current_queue_index = [&]() { return level % 2; };
  auto nextFrontierQ       = [&]() -> auto& {
    dout << "nextFrontierQarr[" << current_queue_index() << "]"
              << std::endl;
    return nextFrontierQarr[current_queue_index()];
  };
  for (size_t i = 0; i < 2; ++i) {
    nextFrontierQarr[i].resize(upcxx::rank_n());
  }
  // find the rank of the source
  auto rank = vertex_id_to_rank(source);
  // if I am the owner of the source
  if (rank == upcxx::rank_me()) {
    auto v_index = vertex_id_to_index(source);
    // Set source's colormap to 1.
    color_map.set(v_index);
    parent_map[v_index] = source;    // source is its own parent
    auto vtx_ptr        = bases[upcxx::rank_me()].local()[v_index];
    auto adj_list_start = vtx_ptr.p.local();
    auto adj_list_len   = vtx_ptr.n;
    // For each neighbor of the vertex, put it in appropriate buffer
    for (auto j = 0; j < vtx_ptr.n; j++) {
      auto neighbor     = adj_list_start[j];
      auto neighborRank = vertex_id_to_rank(neighbor);
      nextFrontierQ()[neighborRank].push_back(std::make_pair(neighbor, source));
    }
  }

  BaseQType gpNextFrontierQarr[2];
  // access current queue
  auto gpNextFrontierQ = [&]() -> auto& {
    return gpNextFrontierQarr[current_queue_index()];
  };
  // initialize and exchange
  for (auto i = 0; i < 2; ++i) {
    gpNextFrontierQarr[i].resize(upcxx::rank_n());
    gpNextFrontierQarr[i][upcxx::rank_me()] =
        upcxx::new_array<gptr_and_len_pair>(upcxx::rank_n());
    for (int r = 0; r < upcxx::rank_n(); r++) {
      gpNextFrontierQarr[i][r] =
          upcxx::broadcast(gpNextFrontierQarr[i][r], r).wait();
    }
  }

  double start{0};
  double stop{0};
  if (upcxx::rank_me() == 0) start = GetCurrentTime();

  while (true) {
    // for each rank
    size_t localFrontierSize = 0;
    for (upcxx::intrank_t r = 0; r < upcxx::rank_n(); r++) {
      // sort and remove duplicates
      std::sort(nextFrontierQ()[r].begin(), nextFrontierQ()[r].end(),
                [](auto& a, auto& b) { return a.first < b.first; });
      std::unique(nextFrontierQ()[r].begin(), nextFrontierQ()[r].end(),
                  [](auto& a, auto& b) { return a.first == b.first; });

      // Now copy the neighbor list per rank to the dist obj
      gptr_and_len_pair pn;
      auto              destination_buffer_size = nextFrontierQ()[r].size();
      pn.n                                      = destination_buffer_size;
      dout << "nextFrontierQ()[r].data() = " << nextFrontierQ()[r].data()
                << ", r = " << r << std::endl;
      pn.p = upcxx::try_global_ptr(nextFrontierQ()[r].data());
      if (pn.p == nullptr) {
        if (nextFrontierQ()[r].size() > 0) {
          throw std::runtime_error(
              "Could not get a global pointer from upcxx allocator vector.");
        }
      }
      gpNextFrontierQ()[upcxx::rank_me()].local()[r] = pn;

      // reduce local frontier sizes
      localFrontierSize += nextFrontierQ()[r].size();
    }

    // Do a reduction to check whether we have reached the end
    //////////////////////////////////////////////////////////
    size_t totalFrontierSize = 0;
    auto done_reduction =
        upcxx::reduce_all(&localFrontierSize, &totalFrontierSize, 1,
                          [](size_t a, size_t b) { return a + b; });
    done_reduction.wait();

    // zero out receive buffer
    received_buffer.resize(0);
    // the start of the conjoined future
    upcxx::future<> fut_all = upcxx::make_future();

    if (upcxx::rank_me() == 0) {
      std::cout << "Level: " << level << " Size: " << totalFrontierSize
                << std::endl;
    }

    if (totalFrontierSize == 0) break;

    // Get vertices targeted for me from each rank
    for (upcxx::intrank_t r = 0; r < upcxx::rank_n(); r++) {
      upcxx::future<> fut =
          upcxx::rget(    // TODO: skip me
              gpNextFrontierQ()[r] + upcxx::rank_me())
              .then([=](gptr_and_len_pair pn) {
                std::vector<std::pair<uint64_t, uint64_t>> target_neighbor_list(
                    pn.n);
                return upcxx::rget(pn.p, target_neighbor_list.data(), pn.n)
                    .then([=, target_neighbor_list =
                                  std::move(target_neighbor_list)]() {
                      received_buffer.insert(received_buffer.end(),
                                             target_neighbor_list.begin(),
                                             target_neighbor_list.end());
                    });
              });
      // conjoin the futures
      fut_all = upcxx::when_all(fut_all, fut);
    }

    // wait for all the conjoined futures to complete
    fut_all.wait();
    dout << "fut_all" << std::endl;

    // Important: do not increment the level until rgets are finished or the rgets will work with the wrong level
    level += 1;

    // After level is increased, we can clear the data from the previous level that is still in the queue
    for (upcxx::intrank_t r = 0; r < upcxx::rank_n(); r++) {
      nextFrontierQ()[r].resize(0);
    }

    // At this point everyone should have the next frontier for the next iteration
    // sort and remove duplicates
    std::sort(received_buffer.begin(), received_buffer.end(),
              [](auto& a, auto& b) { return a.first < b.first; });
    std::unique(received_buffer.begin(), received_buffer.end(),
                [](auto& a, auto& b) { return a.first == b.first; });

    for (auto vertex_p : received_buffer) {
      auto vtx    = vertex_p.first;
      auto parent = vertex_p.second;
      // Check whether the vertex has already been visited.
      auto v_index = vertex_id_to_index(vtx);
      if (color_map[v_index]) {    //Already visited
        continue;
      } else {    // Not visited yet
        dout << "Marking " << vtx << " as visited. " << std::endl;
        color_map.set(v_index);
        parent_map[v_index] = parent;
        // Put all its neighbors into the nextfrontier
        auto vtx_ptr        = bases[upcxx::rank_me()].local()[v_index];
        auto adj_list_start = vtx_ptr.p.local();
        auto adj_list_len   = vtx_ptr.n;
        // For each neighbor of the vertex, put it in appropriate buffer
        for (auto j = 0; j < vtx_ptr.n; j++) {
          auto neighbor     = adj_list_start[j];
          auto neighborRank = vertex_id_to_rank(neighbor);
          nextFrontierQ()[neighborRank].push_back(
              std::make_pair(neighbor, vtx));
        }
      }
    }
  }

  if (upcxx::rank_me() == 0) {
    stop          = GetCurrentTime();
    float elapsed = ElapsedMillis(start, stop);
    std::cout << "Total time " << elapsed << " ms." << std::endl;
  }

  // TODO: clean up after each barrier, empty the next frontier ds, received buffer ds etc.
  upcxx::finalize();
  return 0;
}

max_stars_repo_name: pnnl/chgl

max_issues_repo_name: tcarneirop/chgl

max_forks_repo_name: tcarneirop/chgl


text:
// system include files
#include <memory>
#include <cmath>
#include <iostream>
#include <sstream>
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH

// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"

#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"

#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"

#include "L1Trigger/CSCTrackFinder/interface/CSCSectorReceiverLUT.h"
#include "DataFormats/CSCDigi/interface/CSCCorrelatedLCTDigiCollection.h"
#include "DataFormats/L1CSCTrackFinder/interface/TrackStub.h"//
#include "DataFormats/L1CSCTrackFinder/interface/CSCTriggerContainer.h"
#include "DataFormats/MuonDetId/interface/CSCTriggerNumbering.h"
#include "L1Trigger/CSCTrackFinder/interface/CSCTrackFinderDataTypes.h"

#include "L1Trigger/CSCTrackFinder/test/src/RunSRLUTs.h"

#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "DataFormats/VertexReco/interface/Vertex.h"

#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "DataFormats/Luminosity/interface/LumiSummary.h"

#include "TH1F.h"
#include "TFile.h"
#include "TTree.h"

using namespace std;
using namespace edm;

class LCTOccupancies : public edm::EDAnalyzer {
   public:
      explicit LCTOccupancies(const edm::ParameterSet&);
      ~LCTOccupancies();

   private:
      virtual void beginJob() ;
      virtual void analyze(const edm::Event&, const edm::EventSetup&);
      virtual void endJob() ;
      virtual void beginLuminosityBlock(edm::LuminosityBlock const& iLumiBlock,
					edm::EventSetup const& iSetup);

      // ----------member data ---------------------------

  //TH1F* rateHist;

	edm::InputTag lctsTag;
	edm::InputTag vertexColTag;
  	edm::Service<TFileService> fs;
        csctf_analysis::RunSRLUTs* runSRLUTs;
	float insLumi;
	int nVertex;
	bool haveRECO;
	int singleSectorNum;
	std::string outTreeFileName;

	TH1F* hNVertex;
	TH1F* hInsLumi;

	TH1F* hMPCLink;
	TH1F* hLocalPhi;
	TH1F* hPhi;
	TH1F* hEta;
	TH1F* hPhiPacked;
	TH1F* hEtaPacked;
	TH1F* hBx;

	TH1F* hSector;
	TH1F* hStation;
	TH1F* hEndcap;
	TH1F* hSubSector;

	TH1F* hOccStation1SubSec1;
	TH1F* hOccStation1SubSec2;
	TH1F* hOccStation2;
	TH1F* hOccStation3;
	TH1F* hOccStation4;
	TH1F* hOccMax;
	TH1F* hOccMaxNo0;
	TH1F* hStubsTotal;

	TH1F* hOccME11a;
	TH1F* hOccME11b;
	TH1F* hOccME12;
	TH1F* hOccME13;
	TH1F* hOccME21;
	TH1F* hOccME22;
	TH1F* hOccME31;
	TH1F* hOccME32;
	TH1F* hOccME41;
	TH1F* hOccME42;
	TH1F* hOccME42SingleSector;

	std::vector<TH1F*> hOccME1ChambsSubSec1;
	std::vector<TH1F*> hOccME1ChambsSubSec2;
	std::vector<TH1F*> hOccME2Chambs;
	std::vector<TH1F*> hOccME3Chambs;
	std::vector<TH1F*> hOccME4Chambs;

	//Tree stuff
	TFile* treeFile;
	TTree* tree;
	std::vector<int> occStation1SubSec1;
	std::vector<int> occStation1SubSec2;
	std::vector<int> occStation2;
	std::vector<int> occStation3;
	std::vector<int> occStation4;

	std::vector<std::vector<int> > occME1ChamberSubSec1;
	std::vector<std::vector<int> > occME1ChamberSubSec2;
	std::vector<std::vector<int> > occME2Chamber;
	std::vector<std::vector<int> > occME3Chamber;
	std::vector<std::vector<int> > occME4Chamber;
};
//
// constants, enums and typedefs
//

//
// static data member definitions
//

//
// constructors and destructor
//
LCTOccupancies::LCTOccupancies(const edm::ParameterSet& iConfig)

{
   //now do what ever initialization is needed
   runSRLUTs = new csctf_analysis::RunSRLUTs();
   lctsTag= iConfig.getParameter<edm::InputTag>("lctsTag");
   vertexColTag= iConfig.getParameter<edm::InputTag>("vertexColTag");
   outTreeFileName= iConfig.getUntrackedParameter<std::string>("outTreeFileName");
   haveRECO = iConfig.getUntrackedParameter<bool>("haveRECO");
   singleSectorNum = iConfig.getUntrackedParameter<int>("singleSectorNum");

   treeFile = new TFile(outTreeFileName.c_str(),"RECREATE");
   tree = new TTree("tree","tree");

   occStation1SubSec1 = std::vector<int>(12,0);
   occStation1SubSec2 = std::vector<int>(12,0);
   occStation2 = std::vector<int>(12,0);
   occStation3 = std::vector<int>(12,0);
   occStation4 = std::vector<int>(12,0);

   for(int iSector = 0; iSector<12; iSector++)
   {
      occME1ChamberSubSec1.push_back(std::vector<int>(12,0));
      occME1ChamberSubSec2.push_back(std::vector<int>(12,0));
      occME2Chamber.push_back(std::vector<int>(9,0));
      occME3Chamber.push_back(std::vector<int>(9,0));
      occME4Chamber.push_back(std::vector<int>(9,0));
   }

   tree->Branch("nVertex",&nVertex,"nVertex/I");
   tree->Branch("insLumi",&insLumi,"insLumi/F");

   tree->Branch("occStation1SubSec1","vector<int>",&occStation1SubSec1);
   tree->Branch("occStation1SubSec2","vector<int>",&occStation1SubSec2);
   tree->Branch("occStation2","vector<int>",&occStation2);
   tree->Branch("occStation3","vector<int>",&occStation3);
   tree->Branch("occStation4","vector<int>",&occStation4);

   tree->Branch("occME1ChamberSubSec1","vector<std::vector<int> >",&occME1ChamberSubSec1);
   tree->Branch("occME1ChamberSubSec2","vector<std::vector<int> >",&occME1ChamberSubSec2);
   tree->Branch("occME2Chamber","vector<std::vector<int> >",&occME2Chamber);
   tree->Branch("occME3Chamber","vector<std::vector<int> >",&occME3Chamber);
   tree->Branch("occME4Chamber","vector<std::vector<int> >",&occME4Chamber);
}

LCTOccupancies::~LCTOccupancies()
{

   // do anything here that needs to be done at desctruction time
   // (e.g. close files, deallocate resources etc.)
   treeFile->cd();
   tree->Write();
   delete runSRLUTs;
}

//
// member functions
//

// ------------ method called to for each event  ------------
void
LCTOccupancies::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)
{
  ///////////////////
  //Setup Stuff//////
  ///////////////////
  nVertex=0;

  std::vector<csctf::TrackStub> stubs;
  std::vector<csctf::TrackStub>::const_iterator stub;

  //MuonDigiCollection<CSCDetId,CSCCorrelatedLCTDigi>    "csctfunpacker"          ""        "CsctfFilter"
  edm::Handle<CSCCorrelatedLCTDigiCollection> lctDigiColls;
  iEvent.getByLabel(lctsTag,lctDigiColls);

  std::vector<csctf::TrackStub>* trackStubs = new std::vector<csctf::TrackStub>;
  runSRLUTs->makeTrackStubs(lctDigiColls.product(),trackStubs);

  std::vector<csctf::TrackStub>::const_iterator ts = trackStubs->begin();
  std::vector<csctf::TrackStub>::const_iterator tsEnd = trackStubs->end();

  for(unsigned i=0;i<12;i++)
  {
  }

  std::vector<int> occME11a(24,0);
  std::vector<int> occME11b(24,0);
  std::vector<int> occME12(24,0);
  std::vector<int> occME13(24,0);
  std::vector<int> occME21(12,0);
  std::vector<int> occME22(12,0);
  std::vector<int> occME31(12,0);
  std::vector<int> occME32(12,0);
  std::vector<int> occME41(12,0);
  std::vector<int> occME42(12,0);
  int occME42SingleSector=0;

  for(int iSectors = 0; iSectors<12; iSectors++)
  {
   occStation1SubSec1[iSectors]=0;
   occStation1SubSec2[iSectors]=0;
   occStation2[iSectors]=0;
   occStation3[iSectors]=0;
   occStation4[iSectors]=0;
   for(int iChambers = 0; iChambers<12; iChambers++)
   {
    occME1ChamberSubSec1[iSectors][iChambers]=0;
    occME1ChamberSubSec2[iSectors][iChambers]=0;
    if(iChambers<9)
    {
      occME2Chamber[iSectors][iChambers]=0;
      occME3Chamber[iSectors][iChambers]=0;
      occME4Chamber[iSectors][iChambers]=0;
    }
   }
  }

  for (;ts != tsEnd; ts++)
  {
	//std::cout << "etaValue: \t" <<ts->etaValue()<< std::endl;
	//std::cout << "phiValue: \t" <<ts->phiValue()<< std::endl;
	//std::cout << "eta: \t" <<ts->etaPacked()<< std::endl;
	//std::cout << "phi: \t" <<ts->phiPacked()<< std::endl;
	//std::cout << "cscid: \t" <<ts->cscid()<< std::endl;
	//std::cout << "subsector: \t" <<ts->subsector()<< std::endl;
	//std::cout << "sector: \t" <<ts->sector()<< std::endl;
	//std::cout << "station: \t" <<ts->station()<< std::endl;
	//std::cout << "endcap: \t" <<ts->endcap()<< std::endl;
	//std::cout << "bx: \t" <<ts->BX()<< std::endl;
	//std::cout << "MPCLink: \t" <<ts->getMPCLink()<< std::endl;
	//std::cout << std::endl;

	unsigned sector = ts->sector()-1;

	if(ts->BX() != 0)
		continue;
	hMPCLink->Fill(ts->getMPCLink());
	hLocalPhi->Fill(ts->phiValue());
	hPhi->Fill(ts->phiValue()+15.0*M_PI/180+(sector)*60.0*M_PI/180);
	hPhiPacked->Fill(ts->phiPacked());
	hEta->Fill(ts->etaValue());
	hEtaPacked->Fill(ts->etaPacked());
	hBx->Fill(ts->BX());
        int station = ts->station();
        int subsector = ts->subsector();
	//CSCDetId detId(ts->getDetId().rawId());
	CSCDetId detId(ts->getDetId());
        int ring = detId.ring();
	int triggerChamber = CSCTriggerNumbering::triggerCscIdFromLabels(detId);
	//ME11a ring==4 doesn't work, no ring==4 events ?
	//std::cout << "station: \t" <<ts->station()<< std::endl;
	//std::cout << "ring: \t" <<ring<< std::endl << std::endl;
	if (ts->endcap()==2)
	{
	  station = -station;
	  sector = sector+6;
	}
	hSector->Fill(sector+1);
	hStation->Fill(station);
	hSubSector->Fill(subsector);

        //std::cout << "station: " << station << std::endl;
        //std::cout << "my sector packed: " << sector << std::endl;
        //std::cout << "trigger Chamber: " << triggerChamber << std::endl;

	station = abs(station);
	if (station==1)
	{
	  if(subsector==1)
	  {
  		occME1ChamberSubSec1[sector][triggerChamber-1]++;
		occStation1SubSec1[sector]++;
		if (ring==4)
		  occME11a[sector]++;
		else if (ring==1)
		  occME11b[sector]++;
		else if (ring==2)
		  occME12[sector]++;
		else if (ring==3)
		  occME13[sector]++;
          }
	  else
	  {
  		occME1ChamberSubSec2[sector][triggerChamber-1]++;
		occStation1SubSec2[sector]++;
		if (ring==4)
		  occME11a[sector+12]++;
		else if (ring==1)
		  occME11b[sector+12]++;
		else if (ring==2)
		  occME12[sector+12]++;
		else if (ring==3)
		  occME13[sector+12]++;
          }
	}
	if (station==2)
	{
	  	occME2Chamber[sector][triggerChamber-1]++;
		occStation2[sector]++;
		if (ring==1)
		  occME21[sector]++;
		else if (ring==2)
		  occME22[sector]++;
	}
	if (station==3)
	{
	  	occME3Chamber[sector][triggerChamber-1]++;
		occStation3[sector]++;
		if (ring==1)
		  occME31[sector]++;
		else if (ring==2)
		  occME32[sector]++;
	}
	if (station==4)
	{
	  	occME4Chamber[sector][triggerChamber-1]++;
		occStation4[sector]++;
		if (ring==1)
		  occME41[sector]++;
		else if (ring==2)
		{
		  occME42[sector]++;
		  occME42SingleSector++;
		}
	}
  }

  int maxOcc = 0;

  for (unsigned iSector=0; iSector<12; iSector++)
  {
    if (singleSectorNum != -1 && singleSectorNum != (int) iSector)
	continue;
    hOccStation1SubSec1->Fill(occStation1SubSec1[iSector]);
    hOccStation1SubSec2->Fill(occStation1SubSec2[iSector]);
    hOccStation2->Fill(occStation2[iSector]);
    hOccStation3->Fill(occStation3[iSector]);
    hOccStation4->Fill(occStation4[iSector]);

    if (occStation1SubSec1[iSector]>maxOcc)
	maxOcc = occStation1SubSec1[iSector];
    if (occStation1SubSec2[iSector]>maxOcc)
	maxOcc = occStation1SubSec2[iSector];
    if (occStation2[iSector]>maxOcc)
	maxOcc = occStation2[iSector];
    if (occStation3[iSector]>maxOcc)
	maxOcc = occStation3[iSector];
    if (occStation4[iSector]>maxOcc)
	maxOcc = occStation4[iSector];
  }
  hOccMax->Fill(maxOcc);
  if(maxOcc>0)
    hOccMaxNo0->Fill(maxOcc);

  hStubsTotal->Fill(trackStubs->size());

  for (unsigned iSector=0; iSector<24; iSector++)
  {
    if (singleSectorNum != -1 && abs(singleSectorNum) != (int) iSector
		&& abs(singleSectorNum) != (int) iSector-12)
	continue;
    hOccME11a->Fill(occME11a[iSector]);
    hOccME11b->Fill(occME11b[iSector]);
    hOccME12->Fill(occME12[iSector]);
    hOccME13->Fill(occME13[iSector]);
    if(iSector<12)
    {
      hOccME21->Fill(occME21[iSector]);
      hOccME22->Fill(occME22[iSector]);
      hOccME31->Fill(occME31[iSector]);
      hOccME32->Fill(occME32[iSector]);
      hOccME41->Fill(occME41[iSector]);
      hOccME42->Fill(occME42[iSector]);
    }
  }
  hOccME42SingleSector->Fill(occME42SingleSector);

  for (unsigned iChamb=0; iChamb<12;iChamb++)
  {
    for (unsigned iSector=0; iSector<12;iSector++)
    {
      if (singleSectorNum != -1 && abs(singleSectorNum) != (int) iSector
		&& abs(singleSectorNum) != (int) iSector-12)
	  continue;
      hOccME1ChambsSubSec1[iChamb]->Fill(occME1ChamberSubSec1[iSector][iChamb]);
      hOccME1ChambsSubSec2[iChamb]->Fill(occME1ChamberSubSec2[iSector][iChamb]);
      if(iChamb<9)
      {
        hOccME2Chambs[iChamb]->Fill(occME2Chamber[iSector][iChamb]);
        hOccME3Chambs[iChamb]->Fill(occME3Chamber[iSector][iChamb]);
        hOccME4Chambs[iChamb]->Fill(occME4Chamber[iSector][iChamb]);
      }
    }
  }

  //Vertex Counting

  if(haveRECO)
   if(vertexColTag.label() != "null")
   {
     edm::Handle<reco::VertexCollection> vertexCol;
     iEvent.getByLabel(vertexColTag,vertexCol);
     reco::VertexCollection::const_iterator vertex;
     for(vertex = vertexCol->begin(); vertex != vertexCol->end(); vertex++)
     {
  	if(vertex->isValid() && !vertex->isFake()) //&& vertex->normalizedChi2()<10)
  		nVertex++;
     }
     //std::cout << "nVertex: " << nVertex << std::endl;
     //std::cout << "luminosity: " <<insLumi << std::endl;
     hNVertex->Fill(nVertex);
   }

  tree->Fill();
}

// ------------ method called once each job just before starting event loop  ------------
void
LCTOccupancies::beginJob()
{

  hNVertex=fs->make<TH1F>("NVertex","N Primary Vertices",30,0,30);
  hNVertex->GetXaxis()->SetTitle("N Primary Vertices");
  hNVertex->GetYaxis()->SetTitle("Counts");
  hInsLumi=fs->make<TH1F>("InsLumi","Lumi Section Instantanious Luminosity",10000,0,1000000);
  hInsLumi->GetXaxis()->SetTitle("Lumi Section Instantanious Luminosity (Uncorrected HF--10^{30} cm^{2}s^{-1})");
  hInsLumi->GetYaxis()->SetTitle("Counts");

  hMPCLink=fs->make<TH1F>("MPCLink","Stub MPC Link Number",5,-1,4);
  hMPCLink->GetXaxis()->SetTitle("MPC Link");
  hMPCLink->GetYaxis()->SetTitle("Counts");
  hLocalPhi=fs->make<TH1F>("LocalPhi","Stub Local #phi",4096,0,2.0*62.0*M_PI/180.0);//62.0*M_PI/180.0
  hLocalPhi->GetXaxis()->SetTitle("Local #phi");
  hLocalPhi->GetYaxis()->SetTitle("Counts");
  hPhi=fs->make<TH1F>("Phi","Stub #phi",100,0,3.2);
  hPhi->GetXaxis()->SetTitle("#phi");
  hPhi->GetYaxis()->SetTitle("Counts");
  hPhiPacked=fs->make<TH1F>("PhiPacked","Stub #phi Packed",4096,0,4096);//4096
  hPhiPacked->GetXaxis()->SetTitle("#phi Packed");
  hPhiPacked->GetYaxis()->SetTitle("Counts");
  hEta=fs->make<TH1F>("Eta","Stub |#eta|",128,0.9,2.4);
  hEta->GetXaxis()->SetTitle("|#eta|");
  hEta->GetYaxis()->SetTitle("Counts");
  hEtaPacked=fs->make<TH1F>("EtaPacked","Stub #eta Packed",128,0,128);//128
  hEtaPacked->GetXaxis()->SetTitle("#eta Packed");
  hEtaPacked->GetYaxis()->SetTitle("Counts");
  hBx=fs->make<TH1F>("Bx","Stub Bx Number",15,0,15);
  hBx->GetXaxis()->SetTitle("bx");
  hBx->GetYaxis()->SetTitle("Counts");

  hStation=fs->make<TH1F>("Station","Stub Station",9,-4.5,4.5);
  hStation->GetXaxis()->SetTitle("Station");
  hStation->GetYaxis()->SetTitle("Counts");
  hSector=fs->make<TH1F>("Sector","Stub Sector",12,0.5,12.5);
  hSector->GetXaxis()->SetTitle("Sector");
  hSector->GetYaxis()->SetTitle("Counts");
  hSubSector=fs->make<TH1F>("SubSector","Stub SubSector",3,0,3);
  hSubSector->GetXaxis()->SetTitle("SubSector");
  hSubSector->GetYaxis()->SetTitle("Counts");

  hOccStation1SubSec1=fs->make<TH1F>("OccStation1SubSec1","Stub Occupancy, Station 1, Subsector 1",5,-0.5,4.5);
  hOccStation1SubSec1->GetXaxis()->SetTitle("Stub Occupancy, Station 1, Subsector 1, Summed over Sectors");
  hOccStation1SubSec1->GetYaxis()->SetTitle("Counts");
  hOccStation1SubSec2=fs->make<TH1F>("OccStation1SubSec2","Stub Occupancy, Station 1, Subsector 2",5,-0.5,4.5);
  hOccStation1SubSec2->GetXaxis()->SetTitle("Stub Occupancy, Station 1, Subsector 1, Summed over Sectors");
  hOccStation1SubSec2->GetYaxis()->SetTitle("Counts");
  hOccStation2=fs->make<TH1F>("OccStation2","Stub Occupancy, Station 2",5,-0.5,4.5);
  hOccStation2->GetXaxis()->SetTitle("Stub Occupancy, Station 2, Summed over Sectors");
  hOccStation2->GetYaxis()->SetTitle("Counts");
  hOccStation3=fs->make<TH1F>("OccStation3","Stub Occupancy, Station 3",5,-0.5,4.5);
  hOccStation3->GetXaxis()->SetTitle("Stub Occupancy, Station 3, Summed over Sectors");
  hOccStation3->GetYaxis()->SetTitle("Counts");
  hOccStation4=fs->make<TH1F>("OccStation4","Stub Occupancy, Station 4",5,-0.5,4.5);
  hOccStation4->GetXaxis()->SetTitle("Stub Occupancy, Station 4, Summed over Sectors");
  hOccStation4->GetYaxis()->SetTitle("Counts");
  hOccMax=fs->make<TH1F>("OccMax","Maximum Stub Occupancy",5,-0.5,4.5);
  hOccMax->GetXaxis()->SetTitle("Maximum Stub Occupancy of Stations, Sectors, and Subsectors");
  hOccMax->GetYaxis()->SetTitle("Counts");
  hOccMaxNo0=fs->make<TH1F>("OccMaxNo0","Maximum Stub Occupancy",4,0.5,4.5);
  hOccMaxNo0->GetXaxis()->SetTitle("Maximum Stub Occupancy of Stations, Sectors, and Subsectors");
  hOccMaxNo0->GetYaxis()->SetTitle("Counts");
  hStubsTotal=fs->make<TH1F>("StubsTotal","N Stubs",20,0,20);
  hStubsTotal->GetXaxis()->SetTitle("N Stubs Unpacked in Event");
  hStubsTotal->GetYaxis()->SetTitle("Counts");

  hOccME11a=fs->make<TH1F>("OccME11a","Stub Occupancy, ME11a, Summed over Sectors, Subsectors",5,-0.5,4.5);
  hOccME11a->GetXaxis()->SetTitle("Stub Occupancy, ME11a, Summed over Sectors, Subsectors");
  hOccME11a->GetYaxis()->SetTitle("Counts");
  hOccME11b=fs->make<TH1F>("OccME11b","Stub Occupancy, ME11b, Summed over Sectors, Subsectors",5,-0.5,4.5);
  hOccME11b->GetXaxis()->SetTitle("Stub Occupancy, ME11b, Summed over Sectors, Subsectors");
  hOccME11b->GetYaxis()->SetTitle("Counts");
  hOccME12=fs->make<TH1F>("OccME12","Stub Occupancy, ME12, Summed over Sectors, Subsectors",5,-0.5,4.5);
  hOccME12->GetXaxis()->SetTitle("Stub Occupancy, ME12, Summed over Sectors, Subsectors");
  hOccME12->GetYaxis()->SetTitle("Counts");
  hOccME13=fs->make<TH1F>("OccME13","Stub Occupancy, ME13, Summed over Sectors, Subsectors",5,-0.5,4.5);
  hOccME13->GetXaxis()->SetTitle("Stub Occupancy, ME13, Summed over Sectors, Subsectors");
  hOccME13->GetYaxis()->SetTitle("Counts");
  hOccME21=fs->make<TH1F>("OccME21","Stub Occupancy, ME21, Summed over Sectors",5,-0.5,4.5);
  hOccME21->GetXaxis()->SetTitle("Stub Occupancy, ME21, Summed over Sectors");
  hOccME21->GetYaxis()->SetTitle("Counts");
  hOccME22=fs->make<TH1F>("OccME22","Stub Occupancy, ME22, Summed over Sectors",5,-0.5,4.5);
  hOccME22->GetXaxis()->SetTitle("Stub Occupancy, ME22, Summed over Sectors");
  hOccME22->GetYaxis()->SetTitle("Counts");
  hOccME31=fs->make<TH1F>("OccME31","Stub Occupancy, ME31, Summed over Sectors",5,-0.5,4.5);
  hOccME31->GetXaxis()->SetTitle("Stub Occupancy, ME31, Summed over Sectors");
  hOccME31->GetYaxis()->SetTitle("Counts");
  hOccME32=fs->make<TH1F>("OccME32","Stub Occupancy, ME32, Summed over Sectors",5,-0.5,4.5);
  hOccME32->GetXaxis()->SetTitle("Stub Occupancy, ME32, Summed over Sectors");
  hOccME32->GetYaxis()->SetTitle("Counts");
  hOccME41=fs->make<TH1F>("OccME41","Stub Occupancy, ME41, Summed over Sectors",5,-0.5,4.5);
  hOccME41->GetXaxis()->SetTitle("Stub Occupancy, ME41, Summed over Sectors");
  hOccME41->GetYaxis()->SetTitle("Counts");
  hOccME42=fs->make<TH1F>("OccME42","Stub Occupancy, ME42, Summed over Sectors",5,-0.5,4.5);
  hOccME42->GetXaxis()->SetTitle("Stub Occupancy, ME42, Summed over Sectors");
  hOccME42->GetYaxis()->SetTitle("Counts");
  hOccME42SingleSector=fs->make<TH1F>("OccME42SingleSector","Stub Occupancy, ME42, All Stubs in 1 Sector",5,-0.5,4.5);
  hOccME42SingleSector->GetXaxis()->SetTitle("Stub Occupancy, ME42");
  hOccME42SingleSector->GetYaxis()->SetTitle("Counts");

  // Now begin individual chamber modeling
  TFileDirectory chambsME1Dir = fs->mkdir("chambsME1");
  TFileDirectory chambsME2Dir = fs->mkdir("chambsME2");
  TFileDirectory chambsME3Dir = fs->mkdir("chambsME3");
  TFileDirectory chambsME4Dir = fs->mkdir("chambsME4");

  for(int i=0; i<12;i++)
  {
	std::stringstream tmpName;
	std::stringstream tmpTitle;
	tmpName << "OccME1Chamb" << i+1;
	tmpTitle << "Stub Occupancy ME1, Chamber " << i+1 << " Summed Over Sectors, SubSectors";
	TH1F* tempHist = chambsME1Dir.make<TH1F>(tmpName.str().c_str(),tmpTitle.str().c_str(),3,-0.5,2.5);
	tempHist->GetXaxis()->SetTitle(tmpTitle.str().c_str());
	tempHist->GetYaxis()->SetTitle("Counts");
	hOccME1ChambsSubSec1.push_back(tempHist);
	hOccME1ChambsSubSec2.push_back((TH1F*) tempHist->Clone());
  }

  for(int i=0; i<9;i++)
  {
    for(int j=2; j<5;j++)
    {
	std::stringstream tmpName;
	std::stringstream tmpTitle;
	tmpName << "OccME"<<j<<"Chamb" << i+1;
	tmpTitle << "Stub Occupancy ME"<<j<<", Chamber " << i+1 << " Summed Over Sectors";
	TH1F* tempHist;
	if(j==2)
	{
	  tempHist = chambsME2Dir.make<TH1F>(tmpName.str().c_str(),tmpTitle.str().c_str(),3,-0.5,2.5);
	  hOccME2Chambs.push_back(tempHist);
	}
	else if(j==3)
	{
	  tempHist = chambsME3Dir.make<TH1F>(tmpName.str().c_str(),tmpTitle.str().c_str(),3,-0.5,2.5);
	  hOccME3Chambs.push_back(tempHist);
	}
	else if(j==4)
	{
	  tempHist = chambsME4Dir.make<TH1F>(tmpName.str().c_str(),tmpTitle.str().c_str(),3,-0.5,2.5);
	  hOccME4Chambs.push_back(tempHist);
	}
	else
	  std::cout << "Warning: problem in initializing Chamber Occ hists!" << std::endl;

	tempHist->GetXaxis()->SetTitle(tmpTitle.str().c_str());
	tempHist->GetYaxis()->SetTitle("Counts");
    }
  }

}

// ------------ method called once each job just after ending the event loop  ------------
void
LCTOccupancies::endJob()
{
  TH1F* hOccStation1AddSubSec=fs->make<TH1F>("OccStation1AddSubSec","Stub Occupancy, Station 1",5,-0.5,4.5);
  hOccStation1AddSubSec->GetXaxis()->SetTitle("Stub Occupancy, Station 1, Summed over Sectors, Subsectors");
  hOccStation1AddSubSec->GetYaxis()->SetTitle("Counts");
  TH1F* hOccAddStations=fs->make<TH1F>("OccAddStation","Stub Occupancy",5,-0.5,4.5);
  hOccAddStations->GetXaxis()->SetTitle("Stub Occupancy, Summed over Stations, Sectors, Subsectors");
  hOccAddStations->GetYaxis()->SetTitle("Counts");

  hOccStation1AddSubSec->Add(hOccStation1SubSec1);
  hOccStation1AddSubSec->Add(hOccStation1SubSec2);
  hOccAddStations->Add(hOccStation1SubSec1);
  hOccAddStations->Add(hOccStation1SubSec2);
  hOccAddStations->Add(hOccStation2);
  hOccAddStations->Add(hOccStation3);
  hOccAddStations->Add(hOccStation4);
}

void
LCTOccupancies::beginLuminosityBlock(edm::LuminosityBlock const& iLumiBlock,
                                         edm::EventSetup const& iSetup)
{
  if(haveRECO)
  {
   edm::Handle<LumiSummary> lumiSummary;
   iLumiBlock.getByLabel("lumiProducer", lumiSummary);

   //
   //collect lumi.
   //
   insLumi=lumiSummary->avgInsDelLumi();//*93.244;
   //std::cout << "luminosity: " <<insLumi << std::endl;
   hInsLumi->Fill(insLumi);
  }
}

//define this as a plug-in
DEFINE_FWK_MODULE(LCTOccupancies);

ext: cc

max_stars_repo_name: nistefan/cmssw

max_issues_repo_name: nistefan/cmssw

max_forks_repo_name: nistefan/cmssw


text:
#pragma once

#include "geometry/rect2d.hpp"
#include "geometry/packer.hpp"

#include "coding/writer.hpp"

#include "base/base.hpp"

#include "std/vector.hpp"
#include "std/list.hpp"
#include "std/string.hpp"
#include "std/map.hpp"

#include <boost/gil/gil_all.hpp>

#include <QtGui/QPainter>
#include <QtGui/QImage>
#include <QtCore/QFileInfo>
#include <QtCore/QSize>
#include <QtSvg/QSvgRenderer>
#include <QtXml/QXmlContentHandler>
#include <QtXml/QXmlDefaultHandler>

class QImage;

namespace gil = boost::gil;

namespace tools
{
  class SkinGenerator
  {
  public:
      struct SymbolInfo
      {
        QSize m_size;
        QString m_fullFileName;
        QString m_symbolID;

        m2::Packer::handle_t m_handle;

        SymbolInfo() {}
        SymbolInfo(QSize size, QString const & fullFileName, QString const & symbolID)
          : m_size(size), m_fullFileName(fullFileName), m_symbolID(symbolID) {}
      };

      typedef vector<SymbolInfo> TSymbols;

      struct SkinPageInfo
      {
        TSymbols m_symbols;
        int m_width;
        int m_height;
        string m_fileName;
        string m_dir;
        string m_suffix;
        m2::Packer m_packer;
      };

  private:

      bool m_needColorCorrection;

      QSvgRenderer m_svgRenderer;

      typedef vector<SkinPageInfo> TSkinPages;
      TSkinPages m_pages;

      bool m_overflowDetected;
      void markOverflow();

  public:

      SkinGenerator(bool needColorCorrection);
      //void processFont(string const & fileName, string const & skinName, vector<int8_t> const & fontSizes, int symbolScale);
      void processSymbols(string const & symbolsDir,
                          string const & skinName,
                          vector<QSize> const & symbolSizes,
                          vector<string> const & suffix);
      void renderPages();
      bool writeToFile(string const & skinName);
      void writeToFileNewStyle(string const & skinName);
    };
} // namespace tools

max_stars_repo_name: bowlofstew/omim

max_issues_repo_name: bowlofstew/omim

max_forks_repo_name: bowlofstew/omim


text:
//
// Created by Can Yang on 2020/4/1.
//

#include "mm/fmm/ubodt_gen_app.hpp"
#include "mm/fmm/ubodt_gen_algorithm.hpp"
#include "network/network.hpp"
#include "network/network_graph.hpp"
#include <boost/archive/binary_oarchive.hpp>
#include "util/debug.hpp"
#include <omp.h>

using namespace FMM;
using namespace FMM::CORE;
using namespace FMM::NETWORK;
using namespace FMM::MM;

void UBODTGenApp::run() const {
  std::chrono::steady_clock::time_point begin =
      std::chrono::steady_clock::now();
  SPDLOG_INFO("Write UBODT to file {}", config_.result_file);
  UBODTGenAlgorithm model(network_,ng_);
  bool binary = config_.is_binary_output();
  std::string status = model.generate_ubodt(config_.result_file, config_.delta,
      binary, config_.use_omp);
  std::chrono::steady_clock::time_point end =
      std::chrono::steady_clock::now();
  double time_spent =
      std::chrono::duration_cast<std::chrono::milliseconds>
          (end - begin).count() / 1000.;
  SPDLOG_INFO("Time takes {}", time_spent);
};

max_stars_repo_name: jczaplew/fmm

max_issues_repo_name: jczaplew/fmm

max_forks_repo_name: jczaplew/fmm


text:
#include "ColorMapper.h"
#include "ColorTree.h"
#include <boost/lexical_cast.hpp>
#include <macgyver/Exception.h>
#include <algorithm>
#include <cmath>
#include <memory>
#include <set>
#include <unordered_map>
#include <vector>

namespace Giza
{
// ----------------------------------------------------------------------
/*
 * Helper classes
 */
// ----------------------------------------------------------------------

// Histogram data
struct ColorInfo
{
  explicit ColorInfo(Color c) : color(c), count(0), keeper(false) {}
  Color color;
  Count count;
  bool keeper;

  ColorInfo &operator++()
  {
    ++count;
    return *this;
  }
  void keep() { keeper = true; }
};

// Histogram information
using Counter = std::unordered_map<Color, ColorInfo>;

// Internal histogram
using ColorHistogram = std::vector<ColorInfo>;

// ----------------------------------------------------------------------
/*!
 * \brief Extract a color from Cairo surface data
 */
// ----------------------------------------------------------------------

inline Color get_color(unsigned char *data, int i, int j, int stride)
{
  unsigned char *ptr = data + j * stride + sizeof(Color) * i;
  return *reinterpret_cast<Color *>(ptr);
}

// ----------------------------------------------------------------------
/*!
 * \brief Set a color to Cairo surface data
 */
// ----------------------------------------------------------------------

inline void set_color(unsigned char *data, int i, int j, int stride, Color color)
{
  unsigned char *ptr = data + j * stride + sizeof(Color) * i;
  *reinterpret_cast<Color *>(ptr) = color;
}

// ----------------------------------------------------------------------
/*!
 * \brief Calculate the occurrance count of each color in the given image
 *
 * \param image The image
 * \return The colormap with occurrance counts
 */
// ----------------------------------------------------------------------

Counter calc_histogram(cairo_surface_t *image)
{
  try
  {
    // Verify data is ok to process

    if (image == nullptr)
      throw Fmi::Exception(BCP, "Cannot calculate colour histogram for a null pointer");

    auto format = cairo_image_surface_get_format(image);
    if (format != CAIRO_FORMAT_ARGB32)
      throw Fmi::Exception(BCP, "Color quantization is implemented only for ARGB32 images");

    // Shorthand variables

    int width = cairo_image_surface_get_width(image);
    int height = cairo_image_surface_get_height(image);
    int stride = cairo_image_surface_get_stride(image);  // bytes to next row
    unsigned char *data = cairo_image_surface_get_data(image);

    // We assume there are going to be lots of colours, se we use
    // a sensible starting bucket size

    Counter counter(4096);

    // Not sure if this is even valid in Cairo, check anyway

    if (width * height == 0)
      return counter;

    // Insert the first color so that we can initialize the iterator cache
    // Note that we insert count 0, but the first loop will fix the number

    Color color0 = get_color(data, 0, 0, stride);
    counter.insert(Counter::value_type(color0, ColorInfo(color0)));

    auto last1 = counter.begin();
    auto last2 = counter.begin();

    for (int j = 0; j < height; j++)
      for (int i = 0; i < width; i++)
      {
        Color color = get_color(data, i, j, stride);

        if (last1->first == color)
        {
          ++last1->second;
          // test if the color is the same in a 3x3 box and is hence a new color to be kept
          if (!last1->second.keeper && i > 1 && j > 1)
          {
            // Note: image(i-1,j) is already known to have the same color (last1 points to it)
            if (get_color(data, i - 2, j, stride) == color &&
                get_color(data, i, j - 1, stride) == color &&
                get_color(data, i - 1, j - 1, stride) == color &&
                get_color(data, i - 2, j - 1, stride) == color &&
                get_color(data, i, j - 2, stride) == color &&
                get_color(data, i - 1, j - 2, stride) == color &&
                get_color(data, i - 2, j - 2, stride) == color)
            {
              last1->second.keep();
            }
          }
        }
        else if (last2->first == color)
        {
          ++last2->second;
          swap(last1, last2);
        }
        else
        {
          auto result = counter.insert(Counter::value_type(color, ColorInfo(color)));
          last2 = last1;
          last1 = result.first;
          ++last1->second;
        }
      }

    return counter;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Perform color replacement
 */
// ----------------------------------------------------------------------

void replace_colors(cairo_surface_t *image, const Giza::ColorMap &inputmap)
{
  try
  {
    // Verify data is ok to process

    if (image == nullptr)
      throw Fmi::Exception(BCP, "Cannot calculate colour histogram for a null pointer");

    auto format = cairo_image_surface_get_format(image);
    if (format != CAIRO_FORMAT_ARGB32)
      throw Fmi::Exception(BCP, "Color replacement is implemented only for ARGB32 images");

    // Shorthand variables

    int width = cairo_image_surface_get_width(image);
    int height = cairo_image_surface_get_height(image);
    int stride = cairo_image_surface_get_stride(image);  // bytes to next row
    unsigned char *data = cairo_image_surface_get_data(image);

    // Speed of the conversion by using an unordered map

    std::unordered_map<Color, Color> colormap(256);
    for (const auto &value : inputmap)
      colormap[value.first] = value.second;

    // Remember last color conversions for extra speed

    Color last_color1 = 0;
    Color last_choice1 = 0;
    Color last_color2 = 0;
    Color last_choice2 = 0;

    for (int j = 0; j < height; j++)
    {
      for (int i = 0; i < width; i++)
      {
        Color color = get_color(data, i, j, stride);
        if (color == last_color1)
          set_color(data, i, j, stride, last_choice1);
        else if (color == last_color2)
        {
          set_color(data, i, j, stride, last_choice2);
          std::swap(last_color1, last_color2);
          std::swap(last_choice1, last_choice2);
        }
        else
        {
          last_color2 = last_color1;
          last_choice2 = last_choice1;
          last_color1 = color;
          last_choice1 = colormap[color];
          set_color(data, i, j, stride, last_choice1);
        }
      }
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Build a color tree and a colormap
 */
// ----------------------------------------------------------------------

void build_tree(cairo_surface_t *image,
                const ColorHistogram &hist,
                ColorTree &colortree,
                ColorMap &colormap,
                double quality)
{
  try
  {
    int width = cairo_image_surface_get_width(image);
    int height = cairo_image_surface_get_height(image);

    const double ratio = 1.0 / (width * height);
    const double factor = -quality / log(10.0);

    for (const auto &info : hist)
    {
      if (colortree.empty() || info.keeper)
      {
        colortree.insert(info.color);
        colormap[info.color] = info.color;
      }
      else
      {
        Color nearest = colortree.nearest(info.color);
        double dist = ColorTree::distance(nearest, info.color);

        double limit = factor * log(ratio * info.count);

        if (dist < limit)
        {
          colormap[info.color] = nearest;
        }
        else
        {
          colortree.insert(info.color);
          colormap[info.color] = info.color;
        }
      }
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Build a color tree and a colormap
 */
// ----------------------------------------------------------------------

void build_tree(cairo_surface_t *image,
                const ColorHistogram &hist,
                ColorTree &colortree,
                ColorMap &colormap,
                double quality,
                int maxcolors,
                double errorfactor)
{
  try
  {
    int width = cairo_image_surface_get_width(image);
    int height = cairo_image_surface_get_height(image);

    const double ratio = 1.0 / (width * height);

    bool done = false;
    while (!done)
    {
      done = true;
      const double factor = -quality / log(10.0);

      for (const auto &info : hist)
      {
        if (colortree.empty() || info.keeper)
        {
          colortree.insert(info.color);
          colormap[info.color] = info.color;
        }
        else
        {
          Color nearest = colortree.nearest(info.color);
          double dist = ColorTree::distance(nearest, info.color);

          const double limit = factor * log(ratio * info.count);
          if (dist < limit)
            colormap[info.color] = nearest;
          else if (colortree.size() < maxcolors)
          {
            colortree.insert(info.color);
            colormap[info.color] = info.color;
          }
          else
          {
            colortree.clear();
            colormap.clear();
            done = false;
            quality *= errorfactor;
            break;
          }
        }
      }
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

bool colorcmp(const ColorInfo &info1, const ColorInfo &info2)
{
  try
  {
    if (info1.keeper == info2.keeper)
      return (info2.count < info1.count);

    return info1.keeper;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Calculate the histogram for color reduction
 *
 * \param image The image
 * \return The histogram object
 */
// ----------------------------------------------------------------------

ColorHistogram colorhistogram(cairo_surface_t *image)
{
  try
  {
    Counter counter = calc_histogram(image);

    ColorHistogram histogram;

    for (const auto &count : counter)
      histogram.push_back(count.second);

    std::sort(histogram.begin(), histogram.end(), &colorcmp);

    return histogram;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Set colormapper options
 */
// ----------------------------------------------------------------------

void ColorMapper::options(const ColorMapOptions &theOptions)
{
  try
  {
    itsOptions = theOptions;

    if (itsOptions.quality < 1)
      throw Fmi::Exception(BCP,
                           "Requested relative color map quality must be at least 1, value " +
                               boost::lexical_cast<std::string>(itsOptions.quality) + " was given");

    if (itsOptions.errorfactor < 1.1)
      throw Fmi::Exception(BCP,
                           "Image color quantization error factor must be at least 1.1, value " +
                               boost::lexical_cast<std::string>(itsOptions.errorfactor) +
                               " was given");
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Return true of true color mode is forced
 */
// ----------------------------------------------------------------------

bool ColorMapper::trueColor() const
{
  try
  {
    return itsOptions.truecolor;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Return the color map created by the last reduce call
 */
// ----------------------------------------------------------------------

const ColorMap &ColorMapper::colormap() const
{
  try
  {
    return itsColorMap;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Calculate the occurrance count of each color in the given image
 *
 * \param image The image
 * \return The histogram object
 */
// ----------------------------------------------------------------------

Histogram ColorMapper::histogram(cairo_surface_t *image)
{
  try
  {
    if (image == nullptr)
      throw Fmi::Exception(BCP, "Cannot calculate colour histogram for a null pointer");

    Counter counter = calc_histogram(image);

    Histogram h;

    for (auto &value : counter)
      h.insert(Histogram::value_type(value.second.count, value.first));

    return h;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Reduce colors from the image adaptively
 *
 * Algorithm if maxcolors has not been set:
 *
 *  -# Calculate the histogram
 *  -# In order of popularity, feed the colors into a color tree
 *     which discards colors which are close enough to a color
 *     chosen earlier.
 *  -# For each color, ask the color tree which is the nearest
 *     color for it.
 *  -# Replace the original colors with the colors found in the previous
 *     step.
 *
 * Note that this is very very close to the common popularity based
 * algorithm. However, the twist is that we have an adaptive error
 * criteria, we are not aiming for a fixed number of colors. Hence
 * we get the benefit of the speed of the popularity based algorithm
 * but will never get too big errors.
 *
 * An algorithm which might produce better quality results would
 * be to aim for color diversity as follows:
 *
 *  -# Perform the insertion phase as in algorithm 1, but
 *     with the error limit doubled.
 *  -# Perform the insertion phase as in algorithm 1, now
 *     with a normal error limit
 *  -# Continue by asking the nearest color for all colors
 *
 * However, we require best possible speed and thus do everything
 * in a single pass. What we could do is to find a way to quickly
 * reorder the histogram to produce more diversity in the colors.
 *
 *
 *
 * If the number of max colors has been set, a modified algorithm
 * is used:
 *
 * First, a desired number of maximum colours can be set. If the desired
 * number cannot be reached using the desired quality, more passes will
 * be made, and each time the desired quality will be reduced by the
 * given errorfactor.
 *
 * However, since the algorithm is designed to maintain reasonable quality
 * for palette images, all colours that occur in at least one 3x3 block
 * will be kept. If the desired limits are tight, eventually all other
 * colours will be converted to the colours that must be kept, and the
 * process stops.
 *
 * \param image The image to modify
 */
// ----------------------------------------------------------------------

void ColorMapper::reduce(cairo_surface_t *image)
{
  try
  {
    // Skip histogram etc if true color is forced
    if (itsOptions.truecolor)
      return;

    // Calculate the histogram

    ColorHistogram hist = colorhistogram(image);

    // Abort if we should use RGBA:
    // - there are many different alpha values
    // - smallest alpha is below some limit

    const int max_unique_alphas = 100;
    const unsigned char max_min_alpha = 128;

    unsigned char min_alpha = 255;
    std::vector<int> alphas(256, 0);
    for (const auto &c : hist)
    {
      auto a = alpha(c.color);
      alphas[a] = 1;
      min_alpha = std::min(min_alpha, a);
    }
    int num_alphas = std::count(alphas.begin(), alphas.end(), 1);

    if (num_alphas > max_unique_alphas || (min_alpha < max_min_alpha))
    {
      if (hist.size() >= 256)
      {
        itsOptions.truecolor = true;
        return;
      }
      // Now we want palette mode but no color reductions

      itsOptions.truecolor = false;

      // Identify mapping
      itsColorMap.clear();
      for (const auto &c : hist)
        itsColorMap.insert(ColorMap::value_type(c.color, c.color));

      return;
    }

    // Select the colors and perform the replacements. Subsequent operations
    // will use the ColorMap to produce the palette.

    ColorTree tree;
    itsColorMap.clear();

    if (itsOptions.maxcolors <= 0)
      build_tree(image, hist, tree, itsColorMap, itsOptions.quality);
    else
      build_tree(image,
                 hist,
                 tree,
                 itsColorMap,
                 itsOptions.quality,
                 itsOptions.maxcolors,
                 itsOptions.errorfactor);

    replace_colors(image, itsColorMap);
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

}  // namespace Giza

max_stars_repo_name: fmidev/smartmet-library-giza

max_issues_repo_name: fmidev/smartmet-library-giza

max_forks_repo_name: fmidev/smartmet-library-giza


text:
// Copyright (C) 2020 T. Zachary Laine
//
// 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_TEXT_DETAIL_UTILITY_HPP
#define BOOST_TEXT_DETAIL_UTILITY_HPP

#include <boost/text/config.hpp>

#include <boost/assert.hpp>
#include <boost/algorithm/cxx14/mismatch.hpp>

#include <ostream>

#include <cstddef>
#include <cstring>
#include <climits>

namespace boost { namespace text { namespace detail {

#ifdef BOOST_TEXT_NO_CXX14_CONSTEXPR

        inline std::ptrdiff_t strlen(char const * c_str) noexcept
        {
            return ::strlen(c_str);
        }

#else

        inline constexpr std::ptrdiff_t strlen(char const * c_str) noexcept
        {
            BOOST_ASSERT(c_str);
            std::size_t retval = 0;
            while (*c_str) {
                ++retval;
                ++c_str;
            }
            return retval;
        }

#endif

        template<typename OStream>
        void insert_fill_chars(OStream & os, std::streamsize n)
        {
            int const chunk_size = 8;
            using char_type = typename OStream::char_type;
            char_type fill_chars[chunk_size];
            std::fill_n(fill_chars, chunk_size, os.fill());
            for (; chunk_size <= n && os.good(); n -= chunk_size) {
                os.write(fill_chars, chunk_size);
            }
            if (0 < n && os.good())
                os.write(fill_chars, n);
        }

        template<typename OStream>
        void pad_width_before(OStream & os, std::streamsize size)
        {
            const bool align_left =
                (os.flags() & std::ostream::adjustfield) == std::ostream::left;
            if (align_left)
                return;
            auto const alignment_size = os.width() - size;
            insert_fill_chars(os, alignment_size);
            os.width(0);
        }

        template<typename OStream>
        void pad_width_after(OStream & os, std::streamsize size)
        {
            const bool align_left =
                (os.flags() & std::ostream::adjustfield) == std::ostream::left;
            if (!align_left)
                return;
            auto const alignment_size = os.width() - size;
            insert_fill_chars(os, alignment_size);
            os.width(0);
        }

        inline BOOST_TEXT_CXX14_CONSTEXPR char const *
        strchr(char const * first, char const * last, char c) noexcept
        {
            while (first != last) {
                if (*first == c)
                    return first;
                ++first;
            }
            return last;
        }

        inline BOOST_TEXT_CXX14_CONSTEXPR char const *
        strrchr(char const * first, char const * last, char c) noexcept
        {
            char const * it = last;
            while (first != it) {
                if (*--it == c)
                    return it;
            }
            return last;
        }

        template<typename T>
        constexpr T min_(T lhs, T rhs) noexcept
        {
            return lhs < rhs ? lhs : rhs;
        }

        template<typename T>
        constexpr T max_(T lhs, T rhs) noexcept
        {
            return lhs < rhs ? rhs : lhs;
        }

#ifdef BOOST_TEXT_NO_CXX14_CONSTEXPR

        inline int compare_impl(
            char const * l_first,
            char const * l_last,
            char const * r_first,
            char const * r_last) noexcept
        {
            auto const iters =
                algorithm::mismatch(l_first, l_last, r_first, r_last);
            if (iters.first == l_last) {
                if (iters.second == r_last)
                    return 0;
                else
                    return -1;
            } else if (iters.second == r_last) {
                return 1;
            } else if (*iters.first < *iters.second) {
                return -1;
            } else {
                return 1;
            }
        }

#else

        inline constexpr int compare_impl(
            char const * l_first,
            char const * l_last,
            char const * r_first,
            char const * r_last) noexcept
        {
            auto const l_size = l_last - l_first;
            auto const r_size = r_last - r_first;
            BOOST_ASSERT(l_size <= INT_MAX);
            BOOST_ASSERT(r_size <= INT_MAX);

            int retval = 0;

            int const size = (int)detail::min_(l_size, r_size);
            if (size != 0) {
                char const * l_it = l_first;
                char const * l_it_end = l_first + size;
                char const * r_it = r_first;
                while (l_it != l_it_end) {
                    char const l_c = *l_it;
                    char const r_c = *r_it;
                    if (l_c < r_c)
                        return -1;
                    if (r_c < l_c)
                        return 1;
                    ++l_it;
                    ++r_it;
                }
            }

            if (retval == 0) {
                if (l_size < r_size)
                    return -1;
                if (l_size == r_size)
                    return 0;
                return 1;
            }

            return retval;
        }

#endif

        template<typename Iter1, typename Iter2>
        int generalized_compare(
            Iter1 l_first, Iter1 l_last, Iter2 r_first, Iter2 r_last) noexcept
        {
            auto const iters =
                algorithm::mismatch(l_first, l_last, r_first, r_last);
            if (iters.first == l_last) {
                if (iters.second == r_last)
                    return 0;
                else
                    return -1;
            } else if (iters.second == r_last) {
                return 1;
            } else if (*iters.first < *iters.second) {
                return -1;
            } else {
                return 1;
            }
        }
}}}

#endif


text: #include <boost/accumulators/accumulators_fwd.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino