text:
//
// Created by Andrew Bailey on 5/23/20.
//

#ifndef EMBED_FAST5_TESTS_SRC_BASEKMERTESTS_HPP_
#define EMBED_FAST5_TESTS_SRC_BASEKMERTESTS_HPP_

// embed source
#include "BaseKmer.hpp"
#include "TestFiles.hpp"
//boost
#include <boost/filesystem.hpp>
// gtest
#include <gtest/gtest.h>
#include <gmock/gmock.h>

using namespace boost::filesystem;
using namespace std;
using namespace embed_utils;
using namespace test_files;

TEST (BaseKmerTests, test_Event) {
  Redirect a(true, true);
  Event e(1, 2);
  EXPECT_EQ(1, e.descaled_event_mean);
  EXPECT_EQ(2, e.posterior_probability);
}

TEST (BaseKmerTests, test_PosKmer) {
  Redirect a(true, true);
  Event e(1, 2);
  Event e2(1.1, 2.2);
  PosKmer k("ATGCC", 1);
  k.add_event(e);
  k.add_event(e2);
  k.add_event(1.02, 2.1);
  EXPECT_EQ("ATGCC", k.kmer);
  EXPECT_FLOAT_EQ(2.2, k.events.front().posterior_probability);
  EXPECT_EQ(1, k.num_events());
  PosKmer k2("ATGCC", 2);
  k2.add_event(e);
  k2.add_event(e2);
  k2.add_event(1.02, 2.1);
  EXPECT_EQ("ATGCC", k2.kmer);
  EXPECT_FLOAT_EQ(2.2, k2.events.back().posterior_probability);
  EXPECT_EQ(2, k2.num_events());
}

TEST (BaseKmerTests, test_PosKmer_kde) {
  Redirect a(true, true);
  PosKmer k("ATGCC");
  k.add_event(1, 1);
  k.add_event(2, 0.5);
  k.add_event(3, 1);
  k.add_event(4, 0.5);
  k.add_event(5, 1);
  k.add_event(6, 0.5);
  k.add_event(7, 1);
  k.add_event(8, 0.5);
  k.add_event(9, 1);
  k.add_event(10, 1);
  EXPECT_EQ(10, k.num_events());
  ASSERT_THROW(k.get_hist(0,10,10), AssertionFailureException);
  vector<uint64_t> hist{1,1,1,1,1,1,1,1,1,1};
  ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,10.1,10)));
  ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,10.1,10, 0.5)));
  hist = {1,0,1,0,1,0,1,0,1,1};
  ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,10.1,10, 0.51)));
  hist = {0,1,1,1,1,1,1,1,1,1,1};
  ASSERT_THAT(hist, ElementsAreArray(k.get_hist(0,11,11)));
}

TEST (BaseKmerTests, test_Position) {
  Redirect a(true, true);
  string kmer = "ATGCC";
  Event e(1, 2);
  Event e2(1.1, 2.2);
  Event e3 = e;
  shared_ptr<PosKmer> k = make_shared<PosKmer>(kmer, 1);
  k->add_event(e);
  k->add_event(e2);
  shared_ptr<PosKmer> k2 = k;
  Position p(1);
  p.add_kmer(move(k));
  ASSERT_THROW({(p.add_kmer)(k2);}, AssertionFailureException);
  p.soft_add_kmer_event(kmer, e3);
  EXPECT_EQ(kmer, p.get_pos_kmer(kmer)->kmer);
  EXPECT_EQ(1, p.position);
  EXPECT_FLOAT_EQ(2.2, p.get_pos_kmer(kmer)->events.front().posterior_probability);
}

TEST (BaseKmerTests, test_ContigStrand) {
  Redirect a(true, true);
  string kmer = "ATGCC";
  Event e(1, 2);
  Event e2(1.1, 2.2);
  shared_ptr<PosKmer> k = make_shared<PosKmer>(kmer, 1);
  k->add_event(e);
  k->add_event(e2);
  string contig = "asd";
  string strand = "+";
  uint64_t num_positions = 10;
  ContigStrand cs(contig, strand, num_positions, "t");
  EXPECT_EQ(num_positions, cs.positions.capacity());
  EXPECT_EQ("asd", cs.get_contig());
  EXPECT_EQ("+", cs.get_strand());
  for (uint64_t i=0; i < num_positions; i++){
    EXPECT_EQ(i, cs.positions[i].position);
  }
  uint64_t pos = 1;
  cs.add_kmer(pos, k);
  EXPECT_FLOAT_EQ(2.2, cs.positions[pos].get_pos_kmer(kmer)->events.front().posterior_probability);
  EXPECT_FLOAT_EQ(2.2, cs.get_position(pos).get_pos_kmer(kmer)->events.front().posterior_probability);
  float c = 2;
  float b = 3.3;
  cs.add_event(pos, kmer, c, b);
  EXPECT_FLOAT_EQ(3.3, cs.get_position(pos).get_pos_kmer(kmer)->events.front().posterior_probability);
}

TEST (BaseKmerTests, test_Kmer) {
  Redirect a(true, true);
  Event e(1, 2);
  Event e2(1.1, 2.2);
  shared_ptr<PosKmer> k = make_shared<PosKmer>("ATGCC", 1);

  k->add_event(e);
  k->add_event(e2);
  k->add_event(1.02, 2.1);
  EXPECT_EQ("ATGCC", k->kmer);
  EXPECT_FLOAT_EQ(2.2, k->events.front().posterior_probability);
  EXPECT_EQ(1, k->num_events());
  Kmer kmer("ATGCC");
  string contig_strand = "asdf+t";
  uint64_t pos = 1;
  kmer.add_pos_kmer(contig_strand, pos, k);
  EXPECT_EQ(contig_strand, get<0>(kmer.contig_positions[0]));
  EXPECT_EQ(pos, get<1>(kmer.contig_positions[0]));
  EXPECT_EQ(k, kmer.get_pos_kmer(contig_strand, pos));
  EXPECT_TRUE(kmer.has_pos_kmer(contig_strand, pos));
  EXPECT_FALSE(kmer.has_pos_kmer(contig_strand, 2));
  kmer.soft_add_pos_kmer(contig_strand, pos, k);
  EXPECT_EQ(1, kmer.contig_positions.size());
  EXPECT_EQ(1, kmer.pos_kmer_map.size());
  ContigStrandPosition csp = kmer.split_pos_kmer_map_key("asdf+t1234");
  EXPECT_EQ("asdf", csp.contig);
  EXPECT_EQ("+", csp.strand);
  EXPECT_EQ("t", csp.nanopore_strand);
  EXPECT_EQ(1234, csp.position);

}

TEST (BaseKmerTests, test_ByKmer_kde) {
  Redirect a(true, true);
  shared_ptr<PosKmer> k = make_shared<PosKmer>("ATGCC");
  k->add_event(1, 1);
  k->add_event(2, 0.5);
  k->add_event(3, 1);
  k->add_event(4, 0.5);
  k->add_event(5, 1);
  k->add_event(6, 0.5);
  k->add_event(7, 1);
  k->add_event(8, 0.5);
  k->add_event(9, 1);
  k->add_event(10, 1);
  shared_ptr<PosKmer> k2 = make_shared<PosKmer>("ATGCC");
  k2->add_event(1, 1);
  k2->add_event(2, 0.5);
  k2->add_event(3, 1);
  k2->add_event(4, 0.5);
  k2->add_event(5, 1);
  k2->add_event(6, 0.5);
  k2->add_event(7, 1);
  k2->add_event(8, 0.5);
  k2->add_event(9, 1);
  k2->add_event(10, 1);
  Kmer kmer("ATGCC");
  kmer.add_pos_kmer("asdf", 1, k);
  kmer.add_pos_kmer("asdf", 2, k2);
  ASSERT_THROW(kmer.get_hist(0,10,10), AssertionFailureException);
  vector<uint64_t> hist{2,2,2,2,2,2,2,2,2,2};
  ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,10.1,10)));
  ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,10.1,10, 0.5)));
  hist = {2,0,2,0,2,0,2,0,2,2};
  ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,10.1,10, 0.51)));
  hist = {0,2,2,2,2,2,2,2,2,2,2};
  ASSERT_THAT(hist, ElementsAreArray(kmer.get_hist(0,11,11)));
}

TEST (BaseKmerTests, test_ByKmer) {
  Redirect a(true, true);
  Event e(1, 2);
  Event e2(1.1, 2.2);
  shared_ptr<PosKmer> k = make_shared<PosKmer>("ATGCC", 1);
  k->add_event(e);
  k->add_event(e2);
  k->add_event(1.02, 2.1);
  EXPECT_EQ("ATGCC", k->kmer);
  EXPECT_FLOAT_EQ(2.2, k->events.front().posterior_probability);
  EXPECT_EQ(1, k->num_events());
  string contig_strand = "asdf";
  uint64_t pos = 1;
  uint64_t kmer_length = 5;
  ByKmer by_kmer({'A', 'C', 'T', 'G'}, kmer_length);
  for (auto &k: all_string_permutations("ACTG", kmer_length)) {
    by_kmer.get_kmer(k);
  }
  ASSERT_THROW(by_kmer.get_kmer("AAFAA"), AssertionFailureException);
  by_kmer.add_kmer_ptr(contig_strand, pos, k);
  EXPECT_EQ(1, by_kmer.get_kmer("ATGCC").pos_kmer_map.size());
  by_kmer.add_kmer_ptr(contig_strand, pos, k);
  EXPECT_EQ(1, by_kmer.get_kmer("ATGCC").pos_kmer_map.size());
}

#endif //EMBED_FAST5_TESTS_SRC_BASEKMERTESTS_HPP_


text:
////////////////////////////////////////////////////////////////
// Orkid Media Engine
// Copyright 1996-2020, Michael T. Mayers.
// Distributed under the Boost Software License - Version 1.0 - August 17, 2003
// see http://www.boost.org/LICENSE_1_0.txt
////////////////////////////////////////////////////////////////

#include <ork/pch.h>
#include <ork/reflect/IDeserializer.h>
#include <ork/reflect/Command.h>

#include <ork/reflect/properties/ObjectProperty.h>
#include <ork/stream/IOutputStream.h>
#include <ork/rtti/Category.h>
#include <ork/rtti/downcast.h>
#include <ork/object/Object.h>
#include <boost/uuid/uuid_io.hpp>
////////////////////////////////////////////////////////////////
namespace ork::reflect::serdes {
////////////////////////////////////////////////////////////////
IDeserializer::~IDeserializer() {
}
////////////////////////////////////////////////////////////////
void IDeserializer::trackObject(
    boost::uuids::uuid id, //
    object_ptr_t instance) {
  std::string uuids = boost::uuids::to_string(id);
  auto it           = _reftracker.find(uuids);
  OrkAssert(it == _reftracker.end());
  _reftracker[uuids] = instance;
} // namespace ork::reflect::serdesvoidIDeserializer::trackObject(boost::uuids::uuidid,object_ptr_tinstance)
////////////////////////////////////////////////////////////////
object_ptr_t IDeserializer::findTrackedObject(boost::uuids::uuid id) const {
  std::string uuids = boost::uuids::to_string(id);
  auto it           = _reftracker.find(uuids);
  OrkAssert(it != _reftracker.end());
  return it->second;
}
////////////////////////////////////////////////////////////////
} // namespace ork::reflect::serdes

ext: cpp

max_stars_repo_name: tweakoz/orkid

max_issues_repo_name: tweakoz/orkid

max_forks_repo_name: tweakoz/orkid


text:
#define BOOST_TEST_MODULE device_array

#include <algorithm>

#include <boost/test/unit_test.hpp>

#include <boost/aura/copy.hpp>
#include <boost/aura/device.hpp>
#include <boost/aura/device_array.hpp>
#include <boost/aura/environment.hpp>

#include <test/test.hpp>

#include <boost/core/ignore_unused.hpp>

using namespace boost::aura;

// _____________________________________________________________________________

BOOST_AUTO_TEST_CASE(basic)
{
        initialize();
        {
                device d(AURA_UNIT_TEST_DEVICE);
                feed f(d);
                for (auto numel : {1024, 1024 * 128})
                {
                        device_array<float> ar0(numel, d);
                        ar0.zero(f);
                        {
                                auto m0 = ar0.map(f);

                                // Fill map with values.
                                std::fill(m0.begin(), m0.end(), 42.0f);
                        }
                        std::vector<float> vec(numel, 0.0f);
                        boost::aura::copy(ar0, vec, f);
                        f.synchronize();

                        BOOST_CHECK(
                                std::all_of(
                                        vec.begin(),
                                        vec.end(),
                                        [](float v) { return v == 42.0f; }
                                )
                        );
                }
        }
        finalize();
}

max_stars_repo_name: sschaetz/aura

max_issues_repo_name: sschaetz/aura

max_forks_repo_name: sschaetz/aura


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

#include <boost/foreach.hpp>
#include <wx/textdlg.h>
#include <wx/valnum.h>
#include <wx/valtext.h>
#include <wx/xrc/xmlres.h>
#include "../GdaConst.h"
#include "../logger.h"
#include "../Project.h"
#include "../DialogTools/WebViewHelpWin.h"
#include "LowessParamDlg.h"

LowessParamFrame::LowessParamFrame(double f, int iter, double delta_factor,
                                   Project* project_)
: wxFrame((wxWindow*) 0, wxID_ANY, "LOWESS Smoother Parameters",
          wxDefaultPosition, wxSize(400, -1), wxDEFAULT_FRAME_STYLE),
LowessParamObservable(f, iter, delta_factor),
project(project_)
{
	LOG_MSG("Entering LowessParamFrame::LowessParamFrame");

	wxPanel* panel = new wxPanel(this);
	panel->SetBackgroundColour(*wxWHITE);
	SetBackgroundColour(*wxWHITE);

	wxButton* help_btn = new wxButton(panel,
                                      XRCID("ID_HELP_BTN"),
                                      "Help",
                                      wxDefaultPosition,
                                      wxDefaultSize,
                                      wxBU_EXACTFIT);
	wxButton* apply_btn = new wxButton(panel,
                                       XRCID("ID_APPLY_BTN"),
                                       "Apply",
                                       wxDefaultPosition,
                                       wxDefaultSize,
                                       wxBU_EXACTFIT);
	wxButton* reset_defaults_btn = new wxButton(panel,
                                                XRCID("ID_RESET_DEFAULTS_BTN"),
                                                "Reset",
                                                wxDefaultPosition,
                                                wxDefaultSize,
                                                wxBU_EXACTFIT);

	wxStaticText* f_stat_t = new wxStaticText(panel, wxID_ANY, "Bandwidth:");
	f_text = new wxTextCtrl(panel,
                            XRCID("ID_F_TEXT"),
                            wxString::Format("%.2f", GetF()),
                            wxDefaultPosition,
                            wxSize(100, -1),
                            wxTE_PROCESS_ENTER);
	f_text->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
	Connect(XRCID("ID_F_TEXT"), wxEVT_TEXT,
            wxCommandEventHandler(LowessParamFrame::OnFTextChange));
    Connect(XRCID("ID_F_TEXT"), wxEVT_COMMAND_TEXT_ENTER,
            wxCommandEventHandler(LowessParamFrame::OnApplyBtn));

	wxStaticText* iter_stat_t = new wxStaticText(panel, wxID_ANY, "Iterations:");
	iter_text = new wxTextCtrl(panel,
                               XRCID("ID_ITER_TEXT"),
                               wxString::Format("%d", GetIter()),
                               wxDefaultPosition,
                               wxSize(100, -1),
                               wxTE_PROCESS_ENTER);
	iter_text->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
	Connect(XRCID("ID_ITER_TEXT"),
            wxEVT_TEXT,
            wxCommandEventHandler(LowessParamFrame::OnIterTextChange));
    Connect(XRCID("ID_ITER_TEXT"), wxEVT_COMMAND_TEXT_ENTER,
            wxCommandEventHandler(LowessParamFrame::OnApplyBtn));

	wxStaticText* delta_factor_stat_t =
		new wxStaticText(panel, wxID_ANY, "Delta Factor:");
	delta_factor_text = new wxTextCtrl(panel,
                                       XRCID("ID_DELTA_FACTOR_TEXT"),
                                       wxString::Format("%.4f", GetDeltaFactor()),
                                       wxDefaultPosition,
                                       wxSize(100, -1),
                                       wxTE_PROCESS_ENTER);
	delta_factor_text->SetValidator(wxTextValidator(wxFILTER_NUMERIC));

	Connect(XRCID("ID_DELTA_FACTOR_TEXT"),
            wxEVT_TEXT,
            wxCommandEventHandler(LowessParamFrame::OnDeltaFactorTextChange));
    Connect(XRCID("ID_DELTA_FACTOR_TEXT"), wxEVT_COMMAND_TEXT_ENTER,
            wxCommandEventHandler(LowessParamFrame::OnApplyBtn));
	Connect(XRCID("ID_HELP_BTN"),
            wxEVT_BUTTON,
            wxCommandEventHandler(LowessParamFrame::OnHelpBtn));
	Connect(XRCID("ID_APPLY_BTN"),
            wxEVT_BUTTON,
            wxCommandEventHandler(LowessParamFrame::OnApplyBtn));
	Connect(XRCID("ID_RESET_DEFAULTS_BTN"),
            wxEVT_BUTTON,
            wxCommandEventHandler(LowessParamFrame::OnResetDefaultsBtn));

	// Arrange above widgets in panel using sizers.
	// Top level panel sizer will be panel_h_szr
	// Below that will be panel_v_szr
	// panel_v_szr will directly receive widgets

	wxFlexGridSizer* fg_sizer = new wxFlexGridSizer(3, 2, 3, 3);
	fg_sizer->Add(f_stat_t, 0, wxALIGN_CENTRE_VERTICAL | wxALIGN_RIGHT);
	fg_sizer->Add(f_text, 0, wxALIGN_CENTRE_VERTICAL);
	fg_sizer->Add(iter_stat_t, 0, wxALIGN_CENTRE_VERTICAL | wxALIGN_RIGHT);
	fg_sizer->Add(iter_text, 0, wxALIGN_CENTRE_VERTICAL);
	fg_sizer->Add(delta_factor_stat_t, 0, wxALIGN_CENTRE_VERTICAL|wxALIGN_RIGHT);
	fg_sizer->Add(delta_factor_text, 0, wxALIGN_CENTRE_VERTICAL);

	wxBoxSizer* btns_row1_h_szr = new wxBoxSizer(wxHORIZONTAL);
	btns_row1_h_szr->Add(help_btn, 0, wxALIGN_CENTER_VERTICAL);
	btns_row1_h_szr->AddSpacer(8);
	btns_row1_h_szr->Add(reset_defaults_btn, 0, wxALIGN_CENTER_VERTICAL);
	btns_row1_h_szr->AddSpacer(8);
	btns_row1_h_szr->Add(apply_btn, 0, wxALIGN_CENTER_VERTICAL);

	wxBoxSizer* panel_v_szr = new wxBoxSizer(wxVERTICAL);
	panel_v_szr->Add(fg_sizer, 0,
									 wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
	panel_v_szr->AddSpacer(2);

	panel_v_szr->Add(btns_row1_h_szr, 0,
									 wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

	wxBoxSizer* panel_h_szr = new wxBoxSizer(wxHORIZONTAL);
	panel_h_szr->Add(panel_v_szr, 1, wxEXPAND);

	panel->SetSizer(panel_h_szr);

	// Top Sizer for Frame
	wxBoxSizer* top_h_sizer = new wxBoxSizer(wxHORIZONTAL);
	top_h_sizer->Add(panel, 1, wxEXPAND|wxALL, 8);

	SetSizerAndFit(top_h_sizer);

	Show(true);

	LOG_MSG("Exiting LowessParamFrame::LowessParamFrame");
}

LowessParamFrame::~LowessParamFrame()
{
	LOG_MSG("In LowessParamFrame::~LowessParamFrame");
	notifyObserversOfClosing();
}

void LowessParamFrame::OnHelpBtn(wxCommandEvent& ev)
{
	LOG_MSG("In LowessParamFrame::OnHelpBtn");
	WebViewHelpWin* win = new WebViewHelpWin(project, GetHelpPageHtml(), NULL,
                                             wxID_ANY, _("LOWESS Smoother Help"));
}

void LowessParamFrame::OnApplyBtn(wxCommandEvent& ev)
{
	LOG_MSG("In LowessParamFrame::OnApplyBtn");
	UpdateParamsFromFields();
	notifyObservers();
}

void LowessParamFrame::OnResetDefaultsBtn(wxCommandEvent& ev)
{
	LOG_MSG("In LowessParamFrame::OnResetDefaultsBtn");
	f = Lowess::default_f;
	iter = Lowess::default_iter;
	delta_factor = Lowess::default_delta_factor;
	f_text->ChangeValue(wxString::Format("%.2f", GetF()));
	iter_text->ChangeValue(wxString::Format("%d", GetIter()));
	delta_factor_text->ChangeValue(wxString::Format("%.4f", GetDeltaFactor()));

    OnApplyBtn(ev);
}

void LowessParamFrame::OnFTextChange(wxCommandEvent& ev)
{
}

void LowessParamFrame::OnIterTextChange(wxCommandEvent& ev)
{
}

void LowessParamFrame::OnDeltaFactorTextChange(wxCommandEvent& ev)
{
}

void LowessParamFrame::closeAndDeleteWhenEmpty()
{
	Close(true);
}

void LowessParamFrame::UpdateParamsFromFields()
{
	LOG_MSG("Entering LowessParamFrame::UpdateParamsFromFields");
	Lowess temp_l(GetF(), GetIter(), GetDeltaFactor());
	{
		wxString s = f_text->GetValue();
		double v;
		if (s.ToDouble(&v))
			temp_l.SetF(v);
		f = temp_l.GetF();
		wxString sf = wxString::Format("%.2f", GetF());
		f_text->ChangeValue(sf);
	}
	{
		wxString s = iter_text->GetValue();
		long v;
		if (s.ToLong(&v))
			temp_l.SetIter((long) v);
		iter = temp_l.GetIter();
		wxString sf = wxString::Format("%d", GetIter());
		iter_text->ChangeValue(sf);
	}
	{
		wxString s = delta_factor_text->GetValue();
		double v;
		if (s.ToDouble(&v))
			temp_l.SetDeltaFactor(v);
		delta_factor = temp_l.GetDeltaFactor();
		wxString sf = wxString::Format("%.4f", GetDeltaFactor());
		delta_factor_text->ChangeValue(sf);
	}
	LOG_MSG("Exiting LowessParamFrame::UpdateParamsFromFields");
}

wxString LowessParamFrame::GetHelpPageHtml() const
{
	wxString s;
	s << "<!DOCTYPE html>";
	s << "";
	s << "";
	s << "  ";
	s << "";
	s << "";

	s << "
LOWESS Smoother Overview
";
	s << "
";
	s << "The LOWESS smoother algorithm uses locally-weighted polynomial ";
	s << "regression.  This program is based on the function called ";
	s << "“lowess” in the R stats package.  An internet search ";
	s << "for “lowess stats R” will bring up the relevent ";
	s << "R manual page.  The parameters documented below are respectively ";
	s << "refered to as “f”, “iter” and ";
	s << "“delta” in the R lowess manual page.";
	s << "
";

	s << "
Bandwidth
";
	s << "
";
	s << "The proportion of points in the plot that ";
	s << "influence smoothing at each value. Larger values give ";
	s << "more smoothness.";
	s << "
";

	s << "
Iterations
";
	s << "
";
	s << "The number of “robustifying” iterations which ";
	s << "should be performed. ";
	s << "Using smaller values of iter will speed up the smoothing.";
	s << "
";

	s << "
Delta Factor
";
	s << "
";
	s << "Delta Factor is multiplied by the range of values ";
	s << "in the x-coordinates to produce the internal parameter delta. ";
	s << "Small values of delta ";
	s << "speed up computation: instead of computing the local polynomial ";
	s << "fit at each data point it is not computed for points within ";
	s << "delta of the last computed point, and linear interpolation is ";
	s << "used to fill in the fitted values for the skipped points.";
	s << "
";

	s << "";
	s << "";
	return s;
}

max_stars_repo_name: chenyoujie/GeoDa

max_issues_repo_name: chenyoujie/GeoDa

max_forks_repo_name: chenyoujie/GeoDa


text:
#ifndef RESIZE_HPP
#define RESIZE_HPP

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

#include <string>
#include <vector>

// Boost
#include <boost/property_tree/ptree.hpp>

// Exiv2
#include <exiv2/exiv2.hpp>

// Local
#include "./operation.hpp"

// Resize images that are maximum 10,000 x 10,000 pixels
// At the max this will use 3.2GB of memory (a 100MP image)
// This can be overridden at build time
#ifndef ARION_RESIZE_MAX_PIXELS
#define ARION_RESIZE_MAX_PIXELS 100000000
#endif
enum {
  ResizeTypeInvalid = -1,
  ResizeTypeFixedWidth = 0,
  ResizeTypeFixedHeight = 1,
  ResizeTypeSquare = 2,
  ResizeTypeFill = 3
};

enum {
  ResizeStatusDidNotTry = 0,
  ResizeStatusPending = 1,
  ResizeStatusSuccess = 2,
  ResizeStatusError = 3
};

enum {
  ResizeGravitytCenter = 0,
  ResizeGravityNorth = 1,
  ResizeGravitySouth = 2,
  ResizeGravityWest = 3,
  ResizeGravityEast = 4,
  ResizeGravityNorthWest = 5,
  ResizeGravityNorthEast = 6,
  ResizeGravitySouthWest = 7,
  ResizeGravitySouthEast = 8
};

enum {
  ResizeWatermarkTypeStandard = 0,
  ResizeWatermarkTypeAdaptive = 1,
};

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class Resize : public Operation {
 public:

  Resize();
  virtual ~Resize();

  virtual void setup(const boost::property_tree::ptree &params);
  virtual bool run();
  virtual bool getJpeg(std::vector<unsigned char> &data);

  void setType(const std::string &type);
  void setHeight(unsigned height);
  void setWidth(unsigned width);
  void setQuality(unsigned quality);
  void setInterpolation(const std::string &interpolation);
  void setGravity(std::string gravity);
  void setSharpenAmount(unsigned sharpenAmount);
  void setSharpenRadius(float radius);
  void setPreserveMeta(bool preserveMeta);
  void setWatermarkUrl(const std::string &watermarkUrl);
  void setWatermarkType(const std::string &watermarkType);
  void setWatermarkAmount(float watermarkAmount);
  void setWatermarkMinMax(float watermarkMin, float watermarkMax);
  void setOutputUrl(const std::string &outputUrl);

  std::string getOutputFile() const;
  bool getPreserveMeta() const;
  bool getStatus() const;
  void outputStatus(std::ostream &s, unsigned indent) const;

#ifdef JSON_PRETTY_OUTPUT
  virtual void serialize(rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) const;
#else
  virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer> &writer) const;
#endif

 private:

  int getAspectHeight(int resizeWidth, double aspect) const;
  int getAspectWidth(int resizeHeight, double aspect) const;

  void computeSizeSquare();
  void computeSizeWidth();
  void computeSizeHeight();
  void computeSizeFill();

  void readType(const boost::property_tree::ptree &params);
  void readGravity(const boost::property_tree::ptree &params);

  void validateType(const std::string &type);
  void validateGravity(const std::string &gravity);
  void validateWatermarkUrl(const std::string &watermarkUrl);
  void validateWatermarkType(const std::string &watermarkType);
  void validateOutputUrl(const std::string &outputUrl);
  void validateWatermarkAmount(float watermarkAmount);
  void validateWatermarkMinMax(float watermarkMin, float watermarkMax);
  void validateQuality(unsigned quality);
  void validateSharpenAmount(unsigned sharpenAmount);
  void validateSharpenRadius(float sharpenRadius);

  void applyWatermark();

  int mType;
  unsigned mHeight;
  unsigned mWidth;
  unsigned mQuality;
  int mInterpolation;
  unsigned mGravity;
  bool mPreFilter;
  unsigned mSharpenAmount;
  float mSharpenRadius;
  bool mPreserveMeta;
  std::string mWatermarkFile;
  unsigned mWatermarkType;
  double mWatermarkAmount;
  double mWatermarkMin;
  double mWatermarkMax;
  std::string mOutputFile;

  cv::Mat mImageResized;
  cv::Mat mImageResizedFinal;

  cv::Size mSize;
  cv::Mat mImageToResize;

  int mStatus;
  std::string mErrorMessage;

};

#endif // RESIZE_HPP

ext: hpp

max_stars_repo_name: snapwire-media/arion

max_issues_repo_name: snapwire-media/arion

max_forks_repo_name: snapwire-media/arion


text:
#include <iostream>
#include <ros/ros.h>
#include <std_msgs/Float64MultiArray.h>
// boost for boost::bind passing extra arguments
#include <boost/bind/bind.hpp>

#include "simple_sim/world.h"
#include "simple_sim/initVehicle.h"

using namespace simple_sim_world;

void dummycallback(const std_msgs::Float64MultiArray::ConstPtr& arr){
  return;
}

bool initVehicleCallback(simple_sim::initVehicle::Request &req,
    simple_sim::initVehicle::Response &res, world& worldObj)
{
  // initialize world object with id from req
  ROS_INFO("Got here with id: %d\n",(int)req.id);
  // check if ID is unique
  if (!(worldObj.is_known_vehicle((long)req.id)))
  {
    //set flag
    res.success = true;
    // add to list
    worldObj.init_vehicle((long)req.id);
  }
  else
  {
    // if the ID is already in use, return false
    res.success = false;
  }
  // return true to denote successful completion of service
  return true;
}

int main(int argc, char** argv){
  // run ros
  ros::init(argc,argv,"simple_world");
  // roc handle object
  ros::NodeHandle node;

  // placeholder world object
  world worldObj;

  // init vehicle service
  int i = 0;
  ros::ServiceServer service = node.advertiseService<simple_sim::initVehicle::Request,
      simple_sim::initVehicle::Response>("initVehicle",
    boost::bind(initVehicleCallback,_1,_2, worldObj));
  // subscribe to simple_vel messages
  ros::Subscriber sub = node.subscribe("simple_vel", 1, dummycallback);
  // set rate
  ros::Rate r(10); // 10 hz
  int loopCounter = 0;
  while (ros::ok()){
    loopCounter++;
    if (loopCounter==10){
      // print status
      ROS_INFO("This is the world node at time t = %f.\n",ros::Time::now().toSec());
      //reset
      loopCounter = 0;
    }
    // spin once
    ros::spinOnce();
    // sleep to try to get steady execution
    r.sleep();
  }
}


text:
#include <frovedis.hpp>

#define BOOST_TEST_MODULE FrovedisTest
#include <boost/test/unit_test.hpp>

using namespace frovedis;
using namespace std;

int sum(int a, int b){return a + b;}

BOOST_AUTO_TEST_CASE( frovedis_test )
{
  int argc = 1;
  char** argv = NULL;
  use_frovedis use(argc, argv);

  // filling sample input vector
  std::vector<std::pair<int,int>> v;
  v.push_back(std::make_pair(1,10));
  v.push_back(std::make_pair(4,10));
  v.push_back(std::make_pair(3,10));
  v.push_back(std::make_pair(2,10));
  v.push_back(std::make_pair(3,20));
  v.push_back(std::make_pair(2,20));
  v.push_back(std::make_pair(4,20));
  v.push_back(std::make_pair(1,20));

  // filling expected output vector
  std::vector<std::pair<int,int>> ref_out;
  ref_out.push_back(std::make_pair(1,30));
  ref_out.push_back(std::make_pair(2,30));
  ref_out.push_back(std::make_pair(3,30));
  ref_out.push_back(std::make_pair(4,30));

  // testing reduce_by_key
  auto d1 = frovedis::make_dvector_scatter(v);
  auto d2 = d1.reduce_by_key<int,int>(sum);
  auto r = d2.as_dvector().sort().gather();

  BOOST_CHECK(r == ref_out);
}

ext: cc

max_stars_repo_name: XpressAI/frovedis

max_issues_repo_name: XpressAI/frovedis

max_forks_repo_name: XpressAI/frovedis


text:
#ifndef ASLAM_KEYPOINT_BASE_HPP
#define ASLAM_KEYPOINT_BASE_HPP

#include <Eigen/Core>
#include <aslam/DescriptorBase.hpp>
#include <aslam/KeypointBase.hpp>
#include <aslam/KeypointIdentifier.hpp>
#include <aslam/Time.hpp>
#include <aslam/frontend_ids.hpp>
#include <sm/kinematics/UncertainHomogeneousPoint.hpp>
#include <sm/kinematics/UncertainVector.hpp>
#include <sm/serialization_macros.hpp>

namespace aslam {

// Forward declaration.
class Descriptor;

class KeypointBase {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    KeypointBase();
    virtual ~KeypointBase();

    virtual Eigen::VectorXd vsMeasurement() const = 0;
    virtual Eigen::VectorXd vsY() const { return vsMeasurement(); }
    virtual void vsSetMeasurement(const Eigen::VectorXd& m) = 0;
    virtual double vsMahalonibisDistance(const Eigen::VectorXd& y) const = 0;

    virtual Eigen::MatrixXd vsInverseMeasurementCovariance() const = 0;
    virtual Eigen::MatrixXd vsInvR() const { return vsInverseMeasurementCovariance(); }
    virtual void vsSetInverseMeasurementCovariance(const Eigen::MatrixXd& invR) = 0;

    virtual size_t dimension() const = 0;

    /// \brief get the keypoint descriptor
    virtual const DescriptorBase* descriptor() const = 0;

    /// \brief get the keypoint descriptor
    virtual boost::shared_ptr<DescriptorBase> descriptorPtr() const = 0;

    /// \brief set the keypoint descriptor
    virtual void setDescriptor(const DescriptorBase& descriptor) = 0;

    /// \brief set the keypoint descriptor
    ///        the keypoint takes ownership of the pointer
    virtual void setDescriptorRawPtr(DescriptorBase* descriptor) = 0;

    /// \brief set the keypoint descriptor
    ///        the keypoint takes ownership of the pointer
    virtual void setDescriptorPtr(boost::shared_ptr<DescriptorBase> descriptor) = 0;

    /// \breif get/set the trace id
    virtual void setTraceId(const size_t traceId) = 0;
    virtual size_t getTraceId() = 0;

    ///////////////////////////////////////////////////
    // The landmark
    ///////////////////////////////////////////////////

    /// \brief get the landmark
    virtual const sm::kinematics::UncertainHomogeneousPoint& landmark() const = 0;
    virtual const sm::kinematics::UncertainHomogeneousPoint* landmarkPtr() const = 0;

    /// \brief set the landmark
    virtual void setLandmark(const sm::kinematics::UncertainHomogeneousPoint& landmark) = 0;

    /// \brief get the landmark id
    virtual const LandmarkId& landmarkId() const = 0;

    /// \brief set the landmark id
    virtual void setLandmarkId(const LandmarkId& landmarkId) = 0;

    /// \brief is the landmark initialized
    virtual bool isLandmarkInitialized() const = 0;

    /// \brief is the landmark enabled
    bool isLandmarkEnabled() const;

    /// \brief disable the landmark
    void disableLandmark();
    /// \brief enable the landmark
    void enableLandmark();
    /// \brief reset and clear the landmark.
    virtual void clearLandmark() = 0;

    ///////////////////////////////////////////////////
    // The back projection
    ///////////////////////////////////////////////////

    /// \brief set the back projection
    virtual void setBackProjection(const sm::kinematics::UncertainVector3& v) = 0;

    /// \brief set the back projection
    virtual void setBackProjectionVector(const Eigen::Vector3d& v) = 0;

    /// \brief get the back projection pointer
    virtual const sm::kinematics::UncertainVector3* backProjection() const = 0;

    /// \brief is the back projection initialized?
    virtual bool isBackProjectionSet() const = 0;

    /// \brief clear the back projeciton
    virtual void clearBackProjection() = 0;

  private:
    bool _landmarkEnabled;
};

}  // namespace aslam

#endif /* ASLAM_KEYPOINT_BASE_HPP */

max_stars_repo_name: chengfzy/kalibr

max_issues_repo_name: chengfzy/kalibr

max_forks_repo_name: chengfzy/kalibr


text:
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
//   license.txt   (http://opensource.org/licenses/MIT)

#pragma once

#include "BufferedDataManager.hpp"

#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>

namespace sim_mob
{

/**
 * Templatized wrapper for locked objects.
 *
 * \author Seth N. Hetu
 *
 * A Locked datum handle multiple readers and a single writer through locking. The "set" and "get"
 *  methods ensure mutual exclusion. The "flip" method is an artifact of BufferedBase and does nothing.
 *
 * The spoken semantics of this template are sensible; for example:
 *   Locked<int>
 * ...is a "Locked int".
 *
 * \note
 * Do not delete this class until we decide what to do with it. See Shared.hpp for more information.
 *
 *  \todo It seems that Locked<primitive> shouldn't have to lock on get(), but I'll have to look into this.
 *
 *   \par
 *   I extended BufferedBase so that Buffered and Locked objects are effectively indistinguishable. Currently,
 *   we will definitely use locked types in the mid-term simulator. But a modeler might want to use a Locked
 *   type in the short-term for, say, fast, infrequent inter-agent communication that shouldn't be delayed a turn.
 *   In this case, the engine should allow it.
 *
 *   \par
 *   Note that assigning a Locked class to a BufferedDataManager is wasteful, but effectively harmless.
 *
 *   \par
 *   ~Seth
 */
template <typename T>
class Locked : public BufferedBase
{
public:
    /**
     * Create a new Locked data type.
     *
     * @param value The initial value.
     */
    explicit Locked (const T& value = T()) : BufferedBase(), current_ (value) {}
    virtual ~Locked() {}

    /**
     * Retrieve the current value.
     */
    const T& get() const {
        boost::shared_lock<boost::shared_mutex> lock_(mutex_);

        return current_;
    }

    /**
     * Set the current value.
     */
    void set (const T& value) {
        boost::upgrade_lock<boost::shared_mutex> lock_(mutex_);
        boost::upgrade_to_unique_lock<boost::shared_mutex> unique_(lock_);

        current_ = value;
    }

    /**
     * Evaluates as the current value.
     *
     * Used in an expression, the object will be evaluated as its current value.  Example:
     *     \code
     *     enum Color { GREEN, YELLOW, RED };
     *     Locked<Color> color;
     *     ...
     *     switch (color)
     *     {
     *     case GREEN: ... break;
     *     case YELLOW: ... break;
     *     case RED: ... break;
     *     }
     *     \endcode
     *
     * Another example:
     *     \code
     *     Locked<uint32_t> passenger_count;
     *     ...
     *     if (passenger_count == 10) ...
     *     std::cout << "There are " << passenger_count << " passengers on the bus\n";
     *     \endcode
     *
     *  Take care that this conversion is not called when \p T is big struct.
     */
    operator T() const
    {
        return get();
    }

protected:
    //Included for compatibility with BufferedBase. Does nothing.
    void flip() {}

    //Shared ownership of reading, exclusive ownership of writing.
    mutable boost::shared_mutex mutex_;

    //Value
    T current_;

};

}


text:
/* Copyright Institute of Sound and Vibration Research - All rights reserved */

#include "visr_renderer.hpp"

// 'error' and 'post' defined as a macro in the Max/MSP API and gets in the way of boost.
#undef error
#undef post

#include "options.hpp"

#include <libefl/basic_matrix.hpp>

#include <libpanning/LoudspeakerArray.h>

#include <libpml/initialise_parameter_library.hpp>

#include <libvisr/signal_flow_context.hpp>

#include <libsignalflows/baseline_renderer.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include <ciso646>
#include <cstdlib>
#include <sstream>

#include <maxmspexternals/libmaxsupport/argument_list.hpp>
#include <maxmspexternals/libmaxsupport/class_registrar.hpp>

/* Super-safe determination of the MAX define for setting the operating system. */
#ifdef __APPLE_CC__
#ifndef MAC_VERSION
#define MAC_VERSION
#undef WIN_VERSION
#endif
#else
#ifdef _MSC_VER
#ifndef WIN_VERSION
#define WIN_VERSION
#endif
#undef MAC_VERSION
#endif
#endif

#define MAXAPI_USE_MSCRT
#include "ext.h"
#include "z_dsp.h"
#include "ext_obex.h"

// Some loony (Max/MSP?) obviously defines max, thus hiding any C++/STL functions of the same name.
#undef max
#undef min // same for min(), although there is no Min/MSP around.

namespace visr
{
namespace maxmsp
{
namespace visr_renderer
{

VisrRenderer::VisrRenderer( t_pxobject & maxProxy, short argc, t_atom *argv )
 : ExternalBase( maxProxy )
 , mConfigInitialised( false )
 , mArrayConfiguration( new panning::LoudspeakerArray )
{
  pml::initialiseParameterLibrary();

  object_post( reinterpret_cast<t_object *>(getMaxProxy()), "VisrRenderer::VisrRenderer() constructor called." );
  try
  {
    ArgumentList args( argc, argv );

    Options cmdLineOptions;
    std::stringstream errMsg;
    switch( cmdLineOptions.parse( static_cast<int>(args.argc()), args.argv(), errMsg ) )
    {
    case Options::ParseResult::Failure:
      object_error( reinterpret_cast<t_object *>(getMaxProxy()), "Error while parsing command line options: ", errMsg.str().c_str() );
      return;
    case Options::ParseResult::Help:
    {
      std::stringstream str;
      cmdLineOptions.printDescription( str );
      object_error( reinterpret_cast<t_object *>(getMaxProxy()), str.str().c_str() );
      return;
    }
    case Options::ParseResult::Version:
      return;
    case Options::ParseResult::Success:
      break; // carry on
    }
    mNumberOfObjects = cmdLineOptions.getOption<std::size_t>( "input-channels" );
    mNumberOfOutputs = cmdLineOptions.getOption<std::size_t>( "output-channels" );
    mNumberOfEqSections = cmdLineOptions.getDefaultedOption( "object-eq-sections", 0 );

    boost::filesystem::path const arrayConfigPath( cmdLineOptions.getOption<std::string>( "array-config" ) );
    if( !exists( arrayConfigPath ) )
    {
      std::stringstream err; err << "The specified loudspeaker array configuration file \""
        << arrayConfigPath.string( ) << "\" does not exist.";
      throw std::invalid_argument( err.str() );
    }
    mArrayConfiguration->loadXmlFile( arrayConfigPath.string() );

    /* Set up the filter matrix for the diffusion filters. */
    std::size_t const diffusionFilterLength = 63; // fixed filter length of the filters in the compiled-in matrix
    std::size_t const diffusionFiltersInFile = 64; // Fixed number of filters in file.
    // First create a filter matrix containing all filters from a initializer list that is compiled into the program.
    efl::BasicMatrix<SampleType> allDiffusionCoeffs( diffusionFiltersInFile,
      diffusionFilterLength,
#include "../../apps/baseline_renderer/files/quasiAllpassFIR_f64_n63_initializer_list.txt"
      , cVectorAlignmentSamples );
    std::size_t const numberOfLoudspeakers = mArrayConfiguration->getNumRegularSpeakers( );
    mDiffusionFilters.reset( new efl::BasicMatrix<SampleType>( numberOfLoudspeakers,
      allDiffusionCoeffs.numberOfColumns(),
      cVectorAlignmentSamples ) );
    for( std::size_t idx( 0 ); idx < numberOfLoudspeakers; ++idx )
    {
      efl::vectorCopy( allDiffusionCoeffs.row( idx ), mDiffusionFilters->row( idx ), diffusionFilterLength, cVectorAlignmentSamples );
    }

    mSceneReceiverPort = cmdLineOptions.getDefaultedOption<std::size_t>( "scene-port", 4242 );
    mTrackingConfiguration = cmdLineOptions.getDefaultedOption<std::string>( "tracking", std::string( ) );

    mReverbConfiguration= cmdLineOptions.getDefaultedOption<std::string>( "reverb-config", std::string() );

    // Creating the inlets
    dsp_setup( getMaxProxy(), (int)mNumberOfObjects );

    // Creating the outlets
    for( std::size_t chIdx = 0; chIdx < mNumberOfOutputs; ++chIdx )
    {
      // Again: Using plainObject->mMaxProxy would require a less nasty cast.
      outlet_new( reinterpret_cast<t_object *>(getMaxProxy()), "signal" );
    }
  }
  catch( std::exception const & ex )
  {
    object_error( reinterpret_cast<t_object *>(getMaxProxy()), "Error in constructor: ", ex.what() );
    return;
  }
  mConfigInitialised = true;
}

VisrRenderer::~VisrRenderer()
{
}

/*virtual*/ void VisrRenderer::getFloat( double f )
{
  // At the moment we do not support any run-time control inputs.
  int inlet = getMaxProxy()->z_in;
#if 1 // whether to show debug messages at all
  {
    std::stringstream stream;
    stream << "VisrRenderer::applyFloat() called with inlet = " << inlet << ", f=" << f << "." << std::endl;
    post( stream.str().c_str() );
  }
#endif
//  switch( inlet )
  {
//  default:
    object_post( reinterpret_cast<t_object *>(getMaxProxy( )), "getFloat(): Received message for unsupported inlet %d.", inlet );
  }
}

/*virtual*/ void VisrRenderer::initDsp( t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags )
{
  if( not mConfigInitialised )
  {
    error( "VisrRenderer::initDsp(): Configuration in constructor failed, therefore dspInit() cannot be performed." );
    return;
  }
  long const period = maxvectorsize;
  // Request the actual buffer size
  if( maxvectorsize > std::numeric_limits<short>::max() )
  {
    error( "The maximum vector length is larger than the maximum value to be returned by the \"count\" variable." );
  }
  *count = static_cast<short>(period);

  try
  {
    SamplingFrequencyType const samplingFrequency = static_cast<SamplingFrequencyType>(std::round( samplerate ));

    // Assume a fixed length for the interpolation period.
    // Ideally, this roughly matches the update rate of the scene sender.
    // Provide a special case where the period is longer than the default period.
    // In this case the signal flow would produce an exception to avoid a 'staircased' gain trajectory.
    const std::size_t cInterpolationLength = std::max( 2048l, period );

    mContext.reset( new SignalFlowContext{ static_cast<std::size_t>(period), samplingFrequency} );

    /*
    explicit BaselineRenderer( SignalFlowContext const & context,
      char const * name,
      CompositeComponent * parent,
      panning::LoudspeakerArray const & loudspeakerConfiguration,
      std::size_t numberOfInputs,
      std::size_t numberOfOutputs,
      std::size_t interpolationPeriod,
      efl::BasicMatrix<SampleType> const & diffusionFilters,
      std::string const & trackingConfiguration,
      std::size_t sceneReceiverPort,
      std::size_t numberOfObjectEqSections,
      std::string const & reverbConfig,
      bool frequencyDependentPanning );
*/
    mFlow.reset( new signalflows::BaselineRenderer( *mContext, "VisrRenderer", nullptr,
                                                    *mArrayConfiguration,
                                                    mNumberOfObjects, mNumberOfOutputs,
                                                    cInterpolationLength,
                                                    *mDiffusionFilters,
                                                    mTrackingConfiguration,
                                                    mSceneReceiverPort,
                                                    mNumberOfEqSections,
                                                    mReverbConfiguration,
                                                    false /* no frequency-dependent panning */) );
    mFlowWrapper.reset( new maxmsp::SignalFlowWrapper<double>( *mFlow ) );
  }
  catch( std::exception const & e )
  {
    std::stringstream errMsg;
    errMsg << "Error while initialising the signal flow: " << e.what();
    object_error( reinterpret_cast<t_object *>(getMaxProxy( )), errMsg.str( ).c_str( ));
    return;
  }
}

/*virtual*/ void VisrRenderer::perform( t_object *dsp64, double **ins,
                                        long numins, double **outs, long numouts,
                                        long sampleframes, long flags, void *userparam )
{
  if( numins != mNumberOfObjects )
  {
    error( "VisrRenderer::perform(): Parameter \"numins\" does not match the number of configured input channels." );
  }
  if( numouts != mNumberOfOutputs )
  {
    error( "VisrRenderer::perform(): Parameter \"numouts\" does not match the number of configured output channels." );
  }
  if( sampleframes != static_cast<long>(mContext->period()) )
  {
    error( "VisrRenderer::perform( ): The number of requested samples %d  does not match the given block length." );
  }
  try
  {
    mFlowWrapper->processBlock( ins, outs );
  }
  catch( std::exception const & e )
  {
    error( "Error while initialising the signal flow %s", e.what() );
    return;
  }
}

/*virtual*/ void VisrRenderer::assist( void *b, long msg, long arg, char *dst )
{
  if( msg == ASSIST_INLET )
  {
    switch( arg )
    { // if there is more than one inlet or outlet, a switch is necessary
    case 1: sprintf( dst, "(float/signal2 Input) Scalar gain value (linear scale)" ); break;
    default: sprintf( dst, "(signal %ld) Input", arg + 1 ); break;
    }
  }
  else if( msg == ASSIST_OUTLET )
  {
    sprintf( dst, "(signal %ld) Output", arg + 1 );
  }
}

} // namespace visr_renderer
} // namespace maxmsp
} // namespace visr

extern "C"
{
/****************************/
// Initialization routine MAIN
int C74_EXPORT main()
{
  post( "visr::maxmsp::VisrRenderer::main() called." );

  visr::maxmsp::ClassRegistrar<visr::maxmsp::visr_renderer::VisrRenderer>( "visr_renderer~" );

  post("visr::maxmsp::VisrRenderer::main() finished.");

  return 0;
}
} // extern "C"


text:
/*
 * libasiotap - A portable TAP adapter extension for Boost::ASIO.
 * Copyright (C) 2010-2011 Julien KAUFFMANN <julien.kauffmann@freelan.org>
 *
 * This file is part of libasiotap.
 *
 * libasiotap is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * libasiotap is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 *
 * If you intend to use libasiotap in a commercial software, please
 * contact me : we may arrange this for a small fee or no fee at all,
 * depending on the nature of your project.
 */

/**
 * \file dhcp_proxy.cpp
 * \author Julien KAUFFMANN <julien.kauffmann@freelan.org>
 * \brief An DHCP proxy class.
 */

#include "osi/dhcp_proxy.hpp"

#include "osi/ethernet_helper.hpp"
#include "osi/ipv4_helper.hpp"
#include "osi/udp_helper.hpp"
#include "osi/bootp_helper.hpp"
#include "osi/dhcp_helper.hpp"

#include "osi/ethernet_builder.hpp"
#include "osi/ipv4_builder.hpp"
#include "osi/udp_builder.hpp"
#include "osi/bootp_builder.hpp"
#include "osi/dhcp_builder.hpp"

#include <boost/foreach.hpp>

namespace asiotap
{
	namespace osi
	{
		namespace
		{
			bool is_bootp_request(const_helper<bootp_frame> bootp_helper)
			{
				return (bootp_helper.operation() == BOOTP_BOOTREQUEST);
			}

			bool bootp_is_ethernet(const_helper<bootp_frame> bootp_helper)
			{
				return ((bootp_helper.hardware_type() == BOOTP_HARDWARE_TYPE_ETHERNET) && (bootp_helper.hardware_length() == ETHERNET_ADDRESS_SIZE));
			}

			proxy<dhcp_frame>::ethernet_address_type bootp_get_ethernet_address(const_helper<bootp_frame> bootp_helper)
			{
				proxy<dhcp_frame>::ethernet_address_type result;

				std::memcpy(result.data(), boost::asio::buffer_cast<const void*>(bootp_helper.chaddr()), result.size());

				return result;
			}

			boost::asio::ip::address_v4 prefix_length_to_netmask_v4(unsigned int netmask)
			{
				if (netmask <= 0)
				{
					return boost::asio::ip::address_v4::any();
				}
				else
				{
					if (netmask > 32)
					{
						netmask = 32;
					}

					uint32_t numeric_netmask = (1 << (32 - netmask)) - 1;

					return boost::asio::ip::address_v4(~numeric_netmask);
				}
			}
		}

		const boost::posix_time::time_duration proxy<dhcp_frame>::DEFAULT_LEASE_TIME = boost::posix_time::hours(1);

		boost::optional<boost::asio::const_buffer> proxy<dhcp_frame>::process_frame(
				const_helper<ethernet_frame> ethernet_helper,
				const_helper<ipv4_frame> ipv4_helper,
				const_helper<udp_frame> udp_helper,
				const_helper<bootp_frame> bootp_helper,
				const_helper<dhcp_frame> dhcp_helper,
				boost::asio::mutable_buffer response_buffer
		) const
		{
			// This implementation is partial and far from being perfect.
			// In a ideal world, there should be some udp_socket and a real (complete) DHCP server implementation.

			if (is_bootp_request(bootp_helper) && bootp_is_ethernet(bootp_helper))
			{
				const ethernet_address_type ethernet_address_source = bootp_get_ethernet_address(bootp_helper);

				const entry_map_type::const_iterator entry = m_entry_map.find(ethernet_address_source);

				// A matching entry was found.
				if (entry != m_entry_map.end())
				{
					const_helper<dhcp_frame>::const_iterator message_type_option = dhcp_helper.find(dhcp_option::dhcp_message_type);

					if (message_type_option != dhcp_helper.end())
					{
						bool info = false;

						const_helper<dhcp_frame>::const_iterator requested_ip_address_option = dhcp_helper.find(dhcp_option::requested_ip_address);

						size_t payload_size;

						builder<dhcp_frame> dhcp_builder(response_buffer);

						switch (message_type_option->value_as<uint8_t>())
						{
							case DHCP_DISCOVER_MESSAGE:
								dhcp_builder.add_option(dhcp_option::dhcp_message_type, DHCP_OFFER_MESSAGE);
								break;

							case DHCP_REQUEST_MESSAGE:
								if (requested_ip_address_option != dhcp_helper.end())
								{
									const boost::asio::ip::address_v4 requested_ip_address(ntohl(requested_ip_address_option->value_as<uint32_t>()));

									if (requested_ip_address != entry->second.address)
									{
										dhcp_builder.add_option(dhcp_option::dhcp_message_type, DHCP_NEGATIVE_ACKNOWLEDGMENT_MESSAGE);
									}
									else
									{
										dhcp_builder.add_option(dhcp_option::dhcp_message_type, DHCP_ACKNOWLEDGMENT_MESSAGE);
									}
								}
								else
								{
									dhcp_builder.add_option(dhcp_option::dhcp_message_type, DHCP_NEGATIVE_ACKNOWLEDGMENT_MESSAGE);
								}
								break;

							case DHCP_INFORMATIONAL_MESSAGE:
								dhcp_builder.add_option(dhcp_option::dhcp_message_type, DHCP_ACKNOWLEDGMENT_MESSAGE);
								info = true;
								break;
						}

						dhcp_builder.add_option(dhcp_option::server_identifier, boost::asio::buffer(m_software_address.to_bytes()));

						if (!info)
						{
							const uint32_t lease_time = htonl(m_lease_time.total_seconds());
							dhcp_builder.add_option(dhcp_option::ip_address_lease_time, &lease_time, sizeof(lease_time));
						}

						BOOST_FOREACH(dhcp_option_helper<const_helper_tag>& dhcp_option_helper, dhcp_helper)
						{
							switch (dhcp_option_helper.tag())
							{
								case dhcp_option::parameter_request_list:
									if (dhcp_option_helper.has_length())
									{
										const uint8_t* options = boost::asio::buffer_cast<const uint8_t*>(dhcp_option_helper.value());
										const size_t options_count = boost::asio::buffer_size(dhcp_option_helper.value());

										for (size_t i = 0; i < options_count; ++i)
										{
											switch (static_cast<dhcp_option::dhcp_option_tag>(options[i]))
											{
												case dhcp_option::subnet_mask:
													dhcp_builder.add_option(dhcp_option::subnet_mask, boost::asio::buffer(prefix_length_to_netmask_v4(entry->second.prefix_length).to_bytes()));
													break;

												default:
													break;
											}
										}
									}
									break;

								default:
									break;
							}
						}

						dhcp_builder.add_option(dhcp_option::end);
						dhcp_builder.complete_padding(60);
						payload_size = dhcp_builder.write();

						builder<bootp_frame> bootp_builder(response_buffer, payload_size);

						payload_size = bootp_builder.write(
						                   BOOTP_BOOTREPLY,
						                   bootp_helper.hardware_type(),
						                   bootp_helper.hardware_length(),
						                   bootp_helper.hops(),
						                   bootp_helper.xid(),
						                   bootp_helper.seconds(),
						                   bootp_helper.flags(),
						                   boost::asio::ip::address_v4::any(),
						                   info ? boost::asio::ip::address_v4::any() : entry->second.address,
						                   m_software_address,
						                   boost::asio::ip::address_v4::any(),
						                   boost::asio::buffer(entry->first),
						                   boost::asio::const_buffer(NULL, 0),
						                   boost::asio::const_buffer(NULL, 0)
						               );

						builder<udp_frame> udp_builder(response_buffer, payload_size);

						payload_size = udp_builder.write(udp_helper.destination(), udp_helper.source());

						builder<ipv4_frame> ipv4_builder(response_buffer, payload_size);

						payload_size = ipv4_builder.write(
						                   ipv4_helper.tos(),
						                   ipv4_helper.identification(),
						                   ipv4_helper.flags(),
						                   ipv4_helper.position_fragment(),
						                   ipv4_helper.ttl(),
						                   ipv4_helper.protocol(),
						                   m_software_address,
						                   ipv4_helper.source()
						               );

						udp_builder.update_checksum(ipv4_builder.get_helper());

						builder<ethernet_frame> ethernet_builder(response_buffer, payload_size);

						payload_size = ethernet_builder.write(ethernet_helper.sender(), boost::asio::buffer(m_hardware_address), ethernet_helper.protocol());

						return boost::make_optional<boost::asio::const_buffer>(response_buffer + (boost::asio::buffer_size(response_buffer) - payload_size));
					}
				}
			}

			return boost::optional<boost::asio::const_buffer>();
		}
	}
}

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL


text:
#include <string>
#include <iostream>

#include <boost/bimap.hpp>

int main() {
  boost::bimap<boost::bimaps::tagged<int, struct id>, boost::bimaps::tagged<std::string, struct name>> bm;
  bm.by<id>().insert(std::make_pair(1, "samus"));
  bm.by<id>().insert(std::make_pair(2, "adam"));

  bm.by<name>().insert(std::make_pair("link", 10));
  bm.by<name>().insert(std::make_pair("zelda", 11));

  for (const auto& iter: bm) {
    std::cout << iter.left << "->" << iter.right << std::endl;
  }

  return 0;
}

max_stars_repo_name: kanganabhargava/learning-c-cpp

max_issues_repo_name: kanganabhargava/learning-c-cpp

max_forks_repo_name: kanganabhargava/learning-c-cpp


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

/**
 \author liljekrans
 \file Trakstar.cpp
 \date Oct 27, 2011
 \brief Class for TrakStar Sensor reading
 */

#include "stdafx.h"
#include "ATC3DG.h"
#include "Trakstar.hpp"
#include <iostream>
#include <vector>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

#include <rw/rw.hpp>

#include <sys/time.h>

using namespace std;
using namespace rw::common;

namespace {

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
//
//  MACROS for simplifying the procedure calls
//
// This macro will set a system parameter and call the error handler if there is
// an error reported. Note These macros do not print to the standard output the
// set value

#define SET_SYSTEM_PARAMETER(type, value, l)                                    \
        {                                                                           \
            type##_TYPE buffer = value;                                             \
            _errorCode = SetSystemParameter(type, &buffer, sizeof(buffer));         \
            if(_errorCode!=BIRD_ERROR_SUCCESS) errorHandler(_errorCode, l);         \
        }

#define SET_SENSOR_PARAMETER(sensor, type, value, l)                            \
        {                                                                           \
            type##_TYPE buffer = value;                                             \
            type##_TYPE *pBuffer = &buffer;                                         \
            _errorCode = SetSensorParameter(sensor, type, pBuffer, sizeof(buffer)); \
            if(_errorCode!=BIRD_ERROR_SUCCESS) errorHandler(_errorCode, l);         \
        }

#define SET_TRANSMITTER_PARAMETER(xmtr, type, value, l)                         \
        {                                                                           \
            type##_TYPE buf = value;                                                \
            type##_TYPE *pBuf = &buf;                                               \
            _errorCode = SetTransmitterParameter(xmtr, type, pBuf, sizeof(buf));        \
            if(_errorCode!=BIRD_ERROR_SUCCESS) errorHandler(_errorCode, l);         \
        }

// In order for the above macros to compile without error it is necessary
// to provide typedefs for all the XXX_TYPEs that are generated by "type##_TYPE"
typedef short SELECT_TRANSMITTER_TYPE;
typedef double POWER_LINE_FREQUENCY_TYPE;
// AGC_MODE_TYPE already defined as an enumerated type
typedef double MEASUREMENT_RATE_TYPE;
typedef short REPORT_RATE_TYPE;
typedef double MAXIMUM_RANGE_TYPE;
typedef BOOL METRIC_TYPE;
// DATA_FORMAT_TYPE already defined as an enumerated type
typedef DOUBLE_ANGLES_RECORD ANGLE_ALIGN_TYPE;
typedef DOUBLE_ANGLES_RECORD REFERENCE_FRAME_TYPE;
typedef BOOL XYZ_REFERENCE_FRAME_TYPE;
// HEMISPHERE_TYPE already defined as an enumerated type
typedef BOOL FILTER_AC_WIDE_NOTCH_TYPE;
typedef BOOL FILTER_AC_NARROW_NOTCH_TYPE;
typedef double FILTER_DC_ADAPTIVE_TYPE;
typedef ADAPTIVE_PARAMETERS FILTER_ALPHA_PARAMETERS_TYPE;
typedef BOOL FILTER_LARGE_CHANGE_TYPE;
typedef QUALITY_PARAMETERS QUALITY_TYPE;

}

// forward declaration of error handler
void errorHandler(int error, int lineNum);
timespec diff(timespec start, timespec end);

Trakstar::Trakstar() {

	_initStatus = -1;
}

Trakstar::~Trakstar() {
	// First stop polling
	stopPolling();
	_initThread.join();
	CloseBIRDSystem();
}

void Trakstar::InitializeSystem(bool block) {

	// Initialize system by calling _InitializeBird in a thread
	_initThread = boost::thread(boost::bind(&Trakstar::InitializeBird, this));
	if (block)
		_initThread.join();
}

/**
 * Initialize System by calling library function InitializeBIRDSystem.
 * Should run on plugin startup and thus start in a thread so it doesn't increase startup time
 */
int Trakstar::InitializeBird() {
	int initStatusLocal = TRAKSTAR_STATUS_STOPPED;

	// Set initStatusLocal to "initializing"
	initStatusLocal = TRAKSTAR_STATUS_INITIALIZING;

	// Update _initStatus immediately
	_initStatus = initStatusLocal;

	// Initialize Bird system
	std::cout << "Initializing Trakstar System... This takes some seconds."
			<< endl;

	_errorCode = InitializeBIRDSystem();
	if (_errorCode != BIRD_ERROR_SUCCESS) {
		errorHandler(_errorCode, __LINE__);
		initStatusLocal = TRAKSTAR_STATUS_STOPPED; // Failed. Not initialized

		ROS_ERROR_STREAM("ERROR WHEN INITIALIZING TRAKSTAR");
		ROS_ERROR_STREAM("  error code: " << _errorCode);
		ROS_ERROR_STREAM("  Maybe you forgot to start ATCdaemon64?");
		ROS_FATAL("Trakstar cannot function if not ATCdaemon64 is running! closing!");

	} else {
		//Log::log().info() << "Initialization successfull." << endl;
		std::cout << "Initialization successfull." << endl;

		// Set system parameters

		// Measurement rate, 80 is standard
		//SET_SYSTEM_PARAMETER( MEASUREMENT_RATE, 80, __LINE__ );

		// Metric (use millimeters)
		SET_SYSTEM_PARAMETER( METRIC, true, __LINE__);

		// Range
		//SET_SYSTEM_PARAMETER(MAXIMUM_RANGE,	72.0, __LINE__);

		// Report Rate (how fast does the box prepare new data). reportRate / ( 3*measure_rate ).
		// the RR is actually a report rate devisor. higher => slower report rate.
		// eg. reportrate = 120: 120 / (3*80) = 0.500seconds per update when using GetSynchronousRecord.
		// if using Asynchronous updates, identical values will be read if GetAsynch.. is called faster than data is prepared.
		// Similarly 1 / (3*80) = 4ms per update or approx. 240hz
		//SET_SYSTEM_PARAMETER( REPORT_RATE, 1, __LINE__ ); // 1 is default:

		//SET_SYSTEM_PARAMETER( POWER_LINE_FREQUENCY, 50, __LINE__ );

		_errorCode = GetBIRDSystemConfiguration(&_ATC3DG);
		if (_errorCode != BIRD_ERROR_SUCCESS) {
			errorHandler(_errorCode, __LINE__);
			initStatusLocal = TRAKSTAR_STATUS_STOPPED; // Failed. Not initialized
		} else {
			std::cout << "Trakstar system configuration information read."
					<< endl;
			std::cout << "Number Boards          = " << _ATC3DG.numberBoards
					<< endl;
			std::cout << "Number Sensors         = " << _ATC3DG.numberSensors
					<< endl;
			std::cout << "Number Transmitters    = "
					<< _ATC3DG.numberTransmitters << endl << endl;

			std::cout << "System AGC mode	     = " << _ATC3DG.agcMode << endl;
			std::cout << "Maximum Range          = " << _ATC3DG.maximumRange
					<< endl;
			std::cout << "Measurement Rate       = " << _ATC3DG.measurementRate
					<< endl;
			std::cout << "Metric Mode            = " << _ATC3DG.metric << endl;
			std::cout << "Line Frequency         = "
					<< _ATC3DG.powerLineFrequency << endl;
			std::cout << "Transmitter ID Running = "
					<< _ATC3DG.transmitterIDRunning << endl;

			// Transmitter set:

			DOUBLE_ANGLES_RECORD anglesRecord = { 0, 0, 180 };

			SET_TRANSMITTER_PARAMETER(0, REFERENCE_FRAME, anglesRecord,
					__LINE__);
			SET_TRANSMITTER_PARAMETER(0, XYZ_REFERENCE_FRAME, true, __LINE__);

			// We now know the number of sensors attached. Setup _record etc.
			_rawValues.resize(_ATC3DG.numberSensors);
			_records.resize(_ATC3DG.numberSensors);
			_recordsTmp.resize(_ATC3DG.numberSensors);

			//
			// GET TRANSMITTER CONFIGURATION
			//
			// The call to GetTransmitterConfiguration() performs a similar task to the
			// GetSensorConfiguration() call. It also returns a status in the filled
			// structure which indicates whether a transmitter is attached to this
			// port or not. In a single transmitter system it is only necessary to
			// find where that transmitter is in order to turn it on and use it.
			//
			_pXmtr.resize(_ATC3DG.numberTransmitters);
			for (int i = 0; i < _ATC3DG.numberTransmitters; i++) {
				_errorCode = GetTransmitterConfiguration(i, &_pXmtr[i]);
				if (_errorCode != BIRD_ERROR_SUCCESS) {
					errorHandler(_errorCode, __LINE__);
					initStatusLocal = TRAKSTAR_STATUS_STOPPED; // Failed. Not initialized
				} else {

					// We have successfully initialized the system.
					initStatusLocal = TRAKSTAR_STATUS_STARTED;
				}
			}

			// Setup sensors
			_pSensor.resize(_ATC3DG.numberSensors);
			for (int i = 0; i < _ATC3DG.numberSensors; i++) {
				_errorCode = GetSensorConfiguration(i, &_pSensor[i]);
				if (_errorCode != BIRD_ERROR_SUCCESS)
					errorHandler(_errorCode, __LINE__);

				// Hemisphere, top..
				SET_SENSOR_PARAMETER(i, HEMISPHERE, TOP, __LINE__);

				// Data format
				SET_SENSOR_PARAMETER(i, DATA_FORMAT, TRAKSTAR_RECORDS_ENUM_TYPE,
						__LINE__);

				// filtering

			}
			// Read sensor's configuration
			if (0) {
				cout << "Sensor's configuration:" << endl;
				for (int i = 0; i < _ATC3DG.numberSensors; i++) {
					cout << "Sensor " << (i + 1) << ":" << endl;
					//
					// DATA_FORMAT
					//
					{
						DATA_FORMAT_TYPE buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i, DATA_FORMAT, pBuffer,
								sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						printf("DATA_FORMAT: %d\n", buffer);
					}
					//
					// ANGLE_ALIGN
					//
					{
						DOUBLE_ANGLES_RECORD buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i, ANGLE_ALIGN, pBuffer,
								sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						printf("ANGLE_ALIGN: %6.2f, %6.2f, %6.2f\n", buffer.a,
								buffer.e, buffer.r);
					}
					//
					// HEMISPHERE
					//
					{
						HEMISPHERE_TYPE buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i, HEMISPHERE, pBuffer,
								sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						printf("HEMISPHERE: %4x\n", buffer);
					}
					//
					// FILTER_AC_WIDE_NOTCH
					//
					{
						BOOL buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i, FILTER_AC_WIDE_NOTCH,
								pBuffer, sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						cout << "FILTER_AC_WIDE_NOTCH: " << buffer << endl;
					}
					//
					// FILTER_AC_NARROW_NOTCH
					//
					{
						BOOL buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i,
								FILTER_AC_NARROW_NOTCH, pBuffer,
								sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						cout << "FILTER_AC_NARROW_NOTCH: " << buffer << endl;
					}
					//
					// FILTER_DC_ADAPTIVE
					//
					{
						double buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i, FILTER_DC_ADAPTIVE,
								pBuffer, sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						printf("FILTER_DC_ADAPTIVE: %5.2f\n", buffer);
					}
					//
					// FILTER_ALPHA_PARAMETERS
					//
					{
						ADAPTIVE_PARAMETERS buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i,
								FILTER_ALPHA_PARAMETERS, pBuffer,
								sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						printf("FILTER_ALPHA_PARAMETERS:\n");
						printf(
								"    Alpha max   %5d, %5d, %5d, %5d, %5d, %5d, %5d\n",
								buffer.alphaMax[0], buffer.alphaMax[1],
								buffer.alphaMax[2], buffer.alphaMax[3],
								buffer.alphaMax[4], buffer.alphaMax[5],
								buffer.alphaMax[6]);
						printf(
								"    Alpha Min   %5d, %5d, %5d, %5d, %5d, %5d, %5d\n",
								buffer.alphaMin[0], buffer.alphaMin[1],
								buffer.alphaMin[2], buffer.alphaMin[3],
								buffer.alphaMin[4], buffer.alphaMin[5],
								buffer.alphaMin[6]);
						printf(
								"    Vm          %5d, %5d, %5d, %5d, %5d, %5d, %5d\n",
								buffer.vm[0], buffer.vm[1], buffer.vm[2],
								buffer.vm[3], buffer.vm[4], buffer.vm[5],
								buffer.vm[6]);
						printf("    On/Off      %5d\n", buffer.alphaOn);
					}
					//
					// FILTER_LARGE_CHANGE
					//
					{
						BOOL buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i, FILTER_LARGE_CHANGE,
								pBuffer, sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						printf("FILTER_LARGE_CHANGE: %d\n", buffer);
					}
					//
					// QUALITY
					//
					{
						QUALITY_PARAMETERS buffer, *pBuffer = &buffer;
						_errorCode = GetSensorParameter(i, QUALITY, pBuffer,
								sizeof(buffer));
						if (_errorCode != BIRD_ERROR_SUCCESS)
							errorHandler(_errorCode, __LINE__);
						printf("QUALITY: %d, %d, %d, %d\n", buffer.error_offset,
								buffer.error_sensitivity, buffer.error_slope,
								buffer.filter_alpha);
					}

				}
			}
		}
	}

	_initStatus = initStatusLocal;
	return _errorCode;
}

int Trakstar::getInitStatus() {
	return _initStatus;
}

int Trakstar::getNumberSensorsAttached() {
	if (_initStatus)
		return _sensorsAttached;
	else
		return -1;
}

bool Trakstar::startPolling() {

	// If we were running. Stop first, and then start.
	if (!_flagStopPoll) {
		stopPolling();
	}

	bool ret = false;
	// Search for transmitters. Turn the first one on. (there is only one)
	for (short id = 0; id < _ATC3DG.numberTransmitters; id++) {
		if (_pXmtr[id].attached) {

			// Transmitter selection is a system function.
			// Using the SELECT_TRANSMITTER parameter we send the id of the
			// transmitter that we want to run with the SetSystemParameter() call
			_errorCode = SetSystemParameter(SELECT_TRANSMITTER, &id,
					sizeof(id));
			if (_errorCode != BIRD_ERROR_SUCCESS) {

				errorHandler(_errorCode, __LINE__);

				return ret;
			}

			break;
		}
	}

	// Set the data format type for each attached sensor.
	for (int i = 0; i < _ATC3DG.numberSensors; i++) {
		DATA_FORMAT_TYPE type = TRAKSTAR_RECORDS_ENUM_TYPE;
		_errorCode = SetSensorParameter(i, DATA_FORMAT, &type, sizeof(type));
		if (_errorCode != BIRD_ERROR_SUCCESS)
			errorHandler(_errorCode, __LINE__);
	}

	// Count how many sensors are attached by fetching a single record from all and reading status
	_errorCode = GetSynchronousRecord(ALL_SENSORS, &_rawValues[0],
			sizeof(_rawValues[0]) * _rawValues.size());
	if (_errorCode != BIRD_ERROR_SUCCESS)
		errorHandler(_errorCode, __LINE__);

	// Read sensorStatus
	_sensorsAttached = 0;
	cout << "Attached sensors: ";
	bool firstRun = true;
	for (int i = 0; i < _ATC3DG.numberSensors; i++) {
		unsigned int status = GetSensorStatus(i);

		if ((status & NOT_ATTACHED) == 0) {
			_sensorsAttached++;
			if (!firstRun) {
				cout << ", ";
			} else {
				firstRun = false;
			}

			cout << (i + 1);

		}
	}
	cout << endl;

	_flagStopPoll = false;
	// Start polling thread
	_pollThread = boost::thread(boost::bind(&Trakstar::pollData, this));

	ret = true;

	return ret;
}

void Trakstar::pollData() {
	// For measuring measurement-cycle-rate
	//timespec time1, time2;

	while (1) {

		if (!_flagStopPoll) {

			// Sleep to enable other threads to read data.
			boost::this_thread::sleep(boost::posix_time::milliseconds(2));

			// scan the sensors (all) (blocking call - if REPORT_RATE is low, this will also block RWS plugin ( = lag)
			// , because it reads the values using mutex)

			_errorCode = GetSynchronousRecord(ALL_SENSORS, &_rawValues[0],
					sizeof(_rawValues[0]) * _rawValues.size());
			if (_errorCode != BIRD_ERROR_SUCCESS)
				errorHandler(_errorCode, __LINE__);

			// Measure how fast we are polling
			// Will output eg. "time: 240.000 hz" per cycle and often crash the GUI at those speeds.
			//clock_gettime(CLOCK_REALTIME, &time2);
			//cout << "time: " << 1/ (((double)diff(time1,time2).tv_sec) + ((double)diff(time1,time2).tv_nsec / 1000000000)) << " hz" << endl;
			//clock_gettime(CLOCK_REALTIME, &time1);

			// Get status of sensors (only updates after a Get***Record call)
			//cout << "status: ";
			for (short id = 0; id < _ATC3DG.numberSensors; id++) {

				// get the status of the last data record
				// only report the data if everything is okay

				ULONG status = GetSensorStatus(id);

				// Set default state
				_recordsTmp[id].status = status;
				_recordsTmp[id].valid = false;
				//cout << status << ", ";
				if (status == VALID_STATUS) {
					_analogButtonOn = (bool) (_rawValues[id].button);
					_recordsTmp[id].analogButtonOn = _analogButtonOn;

					// Copy raw data into records
					_recordsTmp[id].pos[0] = _rawValues[id].x;
					_recordsTmp[id].pos[1] = _rawValues[id].y;
					_recordsTmp[id].pos[2] = _rawValues[id].z;
					_recordsTmp[id].rot(3) = _rawValues[id].q[0]; // Scalar component
					_recordsTmp[id].rot(0) = _rawValues[id].q[1]; // qx
					_recordsTmp[id].rot(1) = _rawValues[id].q[2]; // qy
					_recordsTmp[id].rot(2) = _rawValues[id].q[3]; // qz
					_recordsTmp[id].time = _rawValues[id].time;
					_recordsTmp[id].quality = _rawValues[id].quality * 1.0
							/ 65536.0;
					_recordsTmp[id].valid = true;

				} else if (status == (SATURATED | GLOBAL_ERROR)) {
					cout << "Sensor[" << id << "] is saturated." << endl;
				} else if (status == (OUT_OF_MOTIONBOX | GLOBAL_ERROR)) {
					//cout << "Sensor[" << id << "] is out of range." << endl;
					// Don't spam this...
				} else if (status == (NOT_ATTACHED | GLOBAL_ERROR)) {
					// Don't tell us that a sensor is not attached. We probably(hopefully!) know
					// This would be a place to debug for sensor-data not read if that error present.
					//cout << "Not attached sensor" << endl;

				} else if (status == (NO_TRANSMITTER_RUNNING | GLOBAL_ERROR)) {
					//cout << "Transmitter not ready." << endl;
				} else {
					cout << "Sensor[" << id << "]: status not valid: "
							<< status - 1 << endl;
				}
			}

			//cout << endl;

			// Mutex is scoped and is thus released automatically.
			{
				// Get mutex so data can be updated
				boost::mutex::scoped_lock lock(_mutexSensorValues);
				_records = _recordsTmp;
			}
		} else {
			break;
		}
	}

}

void Trakstar::stopPolling() {

	// Signal to _poll to stop polling
	_flagStopPoll = true;
	_pollThread.join();

	// Get active transmitter
	short buffer, *pBuffer = &buffer;
	_errorCode = GetSystemParameter(SELECT_TRANSMITTER, pBuffer,
			sizeof(buffer));
	if (_errorCode != BIRD_ERROR_SUCCESS) {
		errorHandler(_errorCode, __LINE__);
		return;
	}

	// Stop transmitter if one was turned on
	if (buffer != -1) {
		short id = -1;
		_errorCode = SetSystemParameter(SELECT_TRANSMITTER, &id, sizeof(id));
		if (_errorCode != BIRD_ERROR_SUCCESS)
			errorHandler(_errorCode, __LINE__);
	}
}

std::vector<Trakstar::PoseData> Trakstar::getData(void) {

	// Wait until we can get mutex
	boost::mutex::scoped_lock lock(_mutexSensorValues);
	// Mutex is scoped and is thus released automatically.
	/*cout << "status: ";
	 for (int i = 0; i < _records.size(); i++) {
	 cout << _records[i].status << ", ";
	 }
	 cout << endl;*/
	return _records;
}

std::string Trakstar::getSensorStatusString(int errorCode) {
	if (errorCode == VALID_STATUS) {
		return "OK";

	} else if (errorCode & NOT_ATTACHED) {
		return "NOT CONNECTED";

	} else if (errorCode & OUT_OF_MOTIONBOX) {
		return "RANGE";

	} else if (errorCode & SATURATED) {
		return "SATURATED";
	}

	// else
	stringstream ss;
	ss << "e" << errorCode;
	return ss.str();
}

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// This is a simplified error handler.
// This error handler takes the error code and passes it to the GetErrorText()
// procedure along with a buffer to place an error message string.
// This error message string can then be output to a user display device
// like the console
// Specific error codes should be parsed depending on the application.
//
void errorHandler(int error, int lineNum) {
	char buffer[1024];
	int currentError = error;
	int nextError;

	do {
		nextError = GetErrorText(currentError, buffer, sizeof(buffer),
				SIMPLE_MESSAGE);
		std::cout << buffer << endl;
		currentError = nextError;
	} while (currentError != BIRD_ERROR_SUCCESS);
}

timespec diff(timespec start, timespec end) {
	timespec temp;
	if ((end.tv_nsec - start.tv_nsec) < 0) {
		temp.tv_sec = end.tv_sec - start.tv_sec - 1;
		temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
	} else {
		temp.tv_sec = end.tv_sec - start.tv_sec;
		temp.tv_nsec = end.tv_nsec - start.tv_nsec;
	}
	return temp;
}


text:
/*=============================================================================
    Copyright (c) 2009 Hartmut Kaiser

    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)
==============================================================================*/
#if !defined(BOOST_FUSION_NVIEW_ITERATOR_SEP_23_2009_0948PM)
#define BOOST_FUSION_NVIEW_ITERATOR_SEP_23_2009_0948PM

#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/sequence/intrinsic/end.hpp>
#include <boost/fusion/support/category_of.hpp>
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/iterator_base.hpp>

#include <boost/fusion/view/nview/detail/advance_impl.hpp>
#include <boost/fusion/view/nview/detail/at_impl.hpp>
#include <boost/fusion/view/nview/detail/begin_impl.hpp>
#include <boost/fusion/view/nview/detail/deref_impl.hpp>
#include <boost/fusion/view/nview/detail/distance_impl.hpp>
#include <boost/fusion/view/nview/detail/end_impl.hpp>
#include <boost/fusion/view/nview/detail/equal_to_impl.hpp>
#include <boost/fusion/view/nview/detail/next_impl.hpp>
#include <boost/fusion/view/nview/detail/prior_impl.hpp>
#include <boost/fusion/view/nview/detail/size_impl.hpp>
#include <boost/fusion/view/nview/detail/value_at_impl.hpp>
#include <boost/fusion/view/nview/detail/value_of_impl.hpp>

namespace boost {
namespace fusion {
struct nview_iterator_tag;
struct random_access_traversal_tag;

template <typename Sequence, typename Pos>
struct nview_iterator : iterator_base<nview_iterator<Sequence, Pos>> {
  typedef nview_iterator_tag fusion_tag;
  typedef random_access_traversal_tag category;

  typedef Sequence sequence_type;
  typedef Pos first_type;

  BOOST_CONSTEXPR
      BOOST_FUSION_GPU_ENABLED explicit nview_iterator(Sequence &in_seq)
      : seq(in_seq) {}

  Sequence &seq;

private:
  // silence MSVC warning C4512: assignment operator could not be generated
  nview_iterator &operator=(nview_iterator const &);
};

} // namespace fusion
} // namespace boost

#ifdef BOOST_FUSION_WORKAROUND_FOR_LWG_2408
namespace std {
template <typename Sequence, typename Pos>
struct iterator_traits<::boost::fusion::nview_iterator<Sequence, Pos>> {};
} // namespace std
#endif

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include "stdafx.h"
#include "ParameterModel.h"
#include <boost/lexical_cast.hpp>

ParameterModel::ParameterModel (bool isGlobal_, QObject* parent)
    : QAbstractTableModel (parent), isGlobal(isGlobal_){
    rangeInfo.defaultInit ();
    rangeInfo.setNumScanDimensions (1);
    rangeInfo.setNumRanges (0, 1);
}

int ParameterModel::rowCount (const QModelIndex& /*parent*/) const{
    return parameters.size();
}

int ParameterModel::columnCount (const QModelIndex& /*parent*/) const{
    int maxRanges = 0;
    for (auto dimRange : rangeInfo.data){
        if (dimRange.size () > maxRanges){
            maxRanges = dimRange.size ();
        }
    }
    int baseCols = (isGlobal ? 2 : 5 + maxRanges*3);
    return baseCols;
}

QVariant ParameterModel::data (const QModelIndex& index, int role) const{
    int row = index.row ();
    int col = index.column ();
    auto param = parameters[row];
    try {
        switch (role) {
		case Qt::FontRole:{
			if (param.overwritten) {
				QFont font;
				font.setBold (true);
				return QVariant(font);
			}
			return QVariant (); // default
		}
		case Qt::ForegroundRole: { // text color
			if (param.overwritten) {
				return QVariant (QBrush (QColor (255, 0, 0)));
			}
			return QVariant (); // default
		}
		case Qt::BackgroundRole: { // background color
            if (!param.constant && !param.active) {
                return QVariant(QBrush(QColor(250, 250, 210)));
            }
			if (param.constant && param.active) {
                return QVariant(QBrush(QColor(31, 148, 7)));
			}
            if (!param.constant && param.active) {
                return QVariant(QBrush(QColor(255, 255, 0)));
            }
			return QVariant (); // default
		}
        case Qt::EditRole:
            if (!isGlobal && col >= 5) {
                auto rangeNum = int (col - 5) / 3;
                switch ((col - 5) % 3) {
					case 0:
						return qstr (param.ranges[rangeNum].initialValue, 9, true);
					case 1:
						return qstr (param.ranges[rangeNum].finalValue, 9, true);
                }
            } // purposely don't break as this is only different for these two.
        case Qt::DisplayRole:
            if (isGlobal) {
                switch (col) {
                case 0:
                    return qstr(param.name);
                case 1:
                    return qstr (param.constantValue, 9, true);
                default:
                    return QVariant ();
                }
            }
            else {
                switch (col) {
                case 0:
                    return qstr (param.name);
                case 1:
                    return qstr (param.constant ? "Const." : "Var.");
                case 2:
                    return qstr (param.scanDimension);
                case 3:
                    return param.constant ? qstr (param.constantValue, 9, true) : "---";
                case 4:
                    return qstr (param.parameterScope);
                default:
                    if (param.constant) {
                        return QString ("---");
                    }
                    auto rangeNum = int (col - 5) / 3;
                    std::string lEnd = rangeInfo (param.scanDimension, rangeNum).leftInclusive ? "[" : "(";
                    std::string rEnd = rangeInfo (param.scanDimension, rangeNum).rightInclusive ? "]" : ")";
                    switch ((col - 5) % 3) {
						case 0:
							return qstr(lEnd + str (param.ranges[rangeNum].initialValue,9,true));
						case 1:
							return qstr (str(param.ranges[rangeNum].finalValue, 9, true) + rEnd);
						case 2:
							return qstr (rangeInfo (param.scanDimension, rangeNum).variations);
                    }
                    return QVariant ();
                }
            }
        }
    }
    catch (ChimeraError& err){
        errBox (err.trace ());
    }
    return QVariant ();
}

QVariant ParameterModel::headerData (int section, Qt::Orientation orientation, int role) const {
    if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
        if (isGlobal) {
            if (section > 1) return QVariant ();
            auto headers = std::vector<std::string> ({ "Symbol", "Value" });
            return QString (headers[section].c_str());
        } else {
            auto headers = std::vector<std::string> ({ " Sym. ", " Type ", " Dim ", " Val. ", " Scope " });
            for (auto rangeInc : range (5)){
                headers.push_back (str (rangeInc + 1) + ". {");
                headers.push_back ("}");
                headers.push_back ("#");
            }
            if (section >= headers.size()) return QVariant ();
            return QString (headers[section].c_str ());
        }
    }
    else if (role == Qt::DisplayRole && orientation == Qt::Vertical) {
        return QString (cstr (section));
    }
    return QVariant ();
}

Qt::ItemFlags ParameterModel::flags (const QModelIndex& index) const {
    if (index.column () == 1 && !isGlobal || // the "const. / var. option is togglable, not editable.
		(index.column() >= preRangeColumns && parameters[index.row()].constant) || // variation values for constants
		index.column() == 3 && !isGlobal && !parameters[index.row()].constant) { // const value for variables
        return QAbstractTableModel::flags (index);
    }
	return Qt::ItemIsEditable | QAbstractTableModel::flags (index);
};

bool ParameterModel::setData (const QModelIndex& index, const QVariant& value, int role){
    if (role == Qt::EditRole) {
        try {
            auto& param = parameters[index.row ()];
            if (isGlobal) {
                switch (index.column ()) {
                    case 0: // always convert name and scope to lowercase.
                        param.name = str (value.toString (), 13, false, true);
                        break;
                    case 1:
                        param.constantValue = boost::lexical_cast<double>(cstr (value.toString ()));
                        break;
                }
            }
            else {
                switch (index.column ()) {
                    case 0: // always convert name and scope to lowercase.
                        param.name = str (value.toString (), 13, false, true);
                        break;
                    case 1: // constant vs. variable toggle
                        break;
                    case 2:
                        param.scanDimension = boost::lexical_cast<int> (cstr(value.toString ()));
                        if (param.scanDimension+1 > rangeInfo.numScanDimensions ()){
                            rangeInfo.setNumScanDimensions (param.scanDimension+1);
                        }
                        break;
                    case 3:
                        param.constantValue = boost::lexical_cast<double> (cstr(value.toString ()));
                        break;
                    case 4:// always convert name and scope to lowercase.
                        param.parameterScope = str (value.toString (), 13, false, true);
                        break;
                    default:
                        auto rangeNum = int (index.column() - 5) / 3;
                        std::string lEnd = rangeInfo (param.scanDimension, rangeNum).leftInclusive ? "[" : "(";
                        std::string rEnd = rangeInfo (param.scanDimension, rangeNum).rightInclusive ? "]" : ")";

                        switch ((index.column () - 5) % 3) {
							case 0:
								param.ranges[rangeNum].initialValue = boost::lexical_cast<double>(cstr(value.toString ()));
								break;
							case 1:
								param.ranges[rangeNum].finalValue = boost::lexical_cast<double>(cstr (value.toString ()));
								break;
							case 2:
								rangeInfo (param.scanDimension, rangeNum).variations
									= boost::lexical_cast<unsigned int>(cstr (value.toString ()));
                        }
                }
            }
        }
        catch (boost::bad_lexical_cast&) {
            // hmm
        }
        emit paramsChanged ();
        return true;
    }
    return false;
}

void ParameterModel::setParams (std::vector<parameterType> newParams) {
    beginResetModel ();
    parameters = newParams;
    endResetModel();
    emit paramsChanged ();
}

std::vector<parameterType>& ParameterModel::getParams () {
    return parameters;
}

ScanRangeInfo ParameterModel::getRangeInfo (){
    return rangeInfo;
}

void ParameterModel::setRangeInfo (ScanRangeInfo info){
    beginResetModel ();
    rangeInfo = info;
    endResetModel ();
}

void ParameterModel::checkScanDimensionConsistency () {
    for (auto& param : parameters) {
        if (param.scanDimension >= rangeInfo.numScanDimensions ()) {
            param.scanDimension = 0;
        }
    }
}

void ParameterModel::checkVariationRangeConsistency () {
	bool flag = true;
    for (auto var : parameters) {
        if (var.ranges.size () != rangeInfo.numRanges (var.scanDimension)) {
            if (flag) {
                errBox ("The number of variation ranges of a parameter, " + var.name + ", (and perhaps others) did "
                    "not match the official number. The code will force the parameter to match the official number.");
				flag = false; // only dislpay the error message once.
            }
            var.ranges.resize (rangeInfo.numRanges (var.scanDimension));
        }
    }
}

void ParameterModel::setVariationRangeNumber (int num, unsigned short dimNumber){
    // -2 for the two +- columns
    int currentVariableRangeNumber = (columnCount () - preRangeColumns) / 3;
    checkScanDimensionConsistency ();
    checkVariationRangeConsistency ();
    if (rangeInfo.numRanges (dimNumber) != currentVariableRangeNumber) {
        errBox ("somehow, the number of ranges the ParameterSystem object thinks there are and the actual number "
            "displayed are off! The numbers are " + str (rangeInfo.numRanges (dimNumber)) + " and "
            + str (currentVariableRangeNumber) + " respectively. The program will attempt to fix this, but "
            "data may be lost.");
        while (rangeInfo.numRanges (dimNumber) != currentVariableRangeNumber) {
            if (rangeInfo.numRanges (dimNumber) > currentVariableRangeNumber) {
                rangeInfo.dimensionInfo (dimNumber).pop_back ();
                for (auto& param : parameters) {
                    param.ranges.pop_back ();
                }
            }
            else {
                rangeInfo.dimensionInfo (dimNumber).push_back (defaultRangeInfo);
                for (auto& param : parameters) {
                    param.ranges.pop_back ();
                }
            }
        }
    }
    if (currentVariableRangeNumber < num) {
        while (currentVariableRangeNumber < num) {
            /// add a range.
            rangeInfo.dimensionInfo (dimNumber).push_back (defaultRangeInfo);
            for (unsigned varInc = 0; varInc < parameters.size (); varInc++) {
                indvParamRangeInfo tempInfo{ 0,0 };
                parameters[varInc].ranges.push_back (tempInfo);
            }
            currentVariableRangeNumber++;
        }
    }
    else if (currentVariableRangeNumber > num) {
        while (currentVariableRangeNumber > num) {
            // delete a range.
            if (rangeInfo.dimensionInfo (dimNumber).size () == 1) {
                return;	// can't delete last range
            }
            for (auto& param : parameters) {
                param.ranges.pop_back ();
            }
            rangeInfo.dimensionInfo (dimNumber).pop_back ();
            currentVariableRangeNumber--;
        }
    }
    setParams (parameters);
    setRangeInfo (rangeInfo);
}

max_stars_repo_name: zzpwahaha/Chimera-Control-Trim

max_issues_repo_name: zzpwahaha/Chimera-Control-Trim

max_forks_repo_name: zzpwahaha/Chimera-Control-Trim