text:
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#include <string>
#include <iostream>
#include <vector>
//#include "include/pybind11/pybind11.h"
//#include "include/pybind11/numpy.h"
//#include "include/pybind11/stl.h"
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <fstream>

struct TriTraits : public OpenMesh::DefaultTraits
{
  /// Use double precision points
  typedef OpenMesh::Vec3d Point;
  /// Use double precision Normals
  typedef OpenMesh::Vec3d Normal;
  /// Use double precision TexCood2D
  typedef OpenMesh::Vec2d TexCoord2D;
};

/// Simple Name for Mesh
typedef OpenMesh::TriMesh_ArrayKernelT<TriTraits>  TriMesh;

namespace py=pybind11;

// compute matrix exp
Eigen::Matrix3d exp(Eigen::Matrix3d angle_cross_axis){
        Eigen::Matrix3d test=angle_cross_axis+angle_cross_axis.transpose();
        if(test.norm()>1e-6)
        {
            std::cout<<"rotation_log_exp::exp3::input matrix isn't skew-matrix!!!"<<std::endl;
            return Eigen::Matrix3d::Identity();
        }

        Eigen::Vector3d angle_axis;
        angle_axis(0)=angle_cross_axis(2,1);
        angle_axis(1)=angle_cross_axis(0,2);
        angle_axis(2)=angle_cross_axis(1,0);
        double angle=sqrt(angle_axis(0)*angle_axis(0)+angle_axis(1)*angle_axis(1)+angle_axis(2)*angle_axis(2));
        if(angle<1e-6)
            return Eigen::Matrix3d::Identity();
        Eigen::Matrix3d cross_axis=angle_cross_axis/angle;

        test=cross_axis+cross_axis.transpose();
        if(test.norm()>1e-6)
        {
            std::cout<<"rotation_log_exp::exp2::input matrix isn't skew-matrix!!!"<<std::endl;
            return Eigen::Matrix3d::Identity();
        }

        return Eigen::Matrix3d::Identity()+sin(angle)*cross_axis+(1.0-cos(angle))*cross_axis*cross_axis;
}

py::array_t<double> get_mesh(std::string file, py::array_t<double> feature_input){
    TriMesh ref_mesh_;
    if(!OpenMesh::IO::read_mesh(ref_mesh_, file)){
        std::cerr<<"Read Mesh error"<<std::endl;
    }
    int nver=ref_mesh_.n_vertices();
    OpenMesh::EPropHandleT<double> LB_weights;
    ref_mesh_.add_property(LB_weights);

    // compute LB weight
    TriMesh::EdgeIter e_it, e_end(ref_mesh_.edges_end());
    TriMesh::HalfedgeHandle    h0, h1, h2;
    TriMesh::VertexHandle      v0, v1;
    TriMesh::Point             p0, p1, p2, d0, d1;
    TriMesh::Scalar w;
    for (e_it=ref_mesh_.edges_begin(); e_it!=e_end; e_it++)
    {
        w  = 0.0;
        if(ref_mesh_.is_boundary(*e_it))
        {
            h0 = ref_mesh_.halfedge_handle(e_it.handle(),0);
            if(ref_mesh_.is_boundary(h0))
                h0 = ref_mesh_.opposite_halfedge_handle(h0);

            v0 = ref_mesh_.to_vertex_handle(h0);
            v1 = ref_mesh_.from_vertex_handle(h0);
            p0 = ref_mesh_.point(v0);
            p1 = ref_mesh_.point(v1);
            h1 = ref_mesh_.next_halfedge_handle(h0);
            p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h1));
            d0 = (p0-p2).normalize();
            d1 = (p1-p2).normalize();
            w += 2.0 / tan(acos(std::min(0.99, std::max(-0.99, (d0|d1)))));
            if(std::isnan(w))
                std::cout<<"Some weight NAN"<<std::endl;
            ref_mesh_.property(LB_weights,e_it) = w;
            continue;
        }
        h0 = ref_mesh_.halfedge_handle(e_it.handle(),0);
        v0 = ref_mesh_.to_vertex_handle(h0);
        p0 = ref_mesh_.point(v0);

        h1 = ref_mesh_.opposite_halfedge_handle(h0);
        v1 = ref_mesh_.to_vertex_handle(h1);
        p1 = ref_mesh_.point(v1);

        h2 = ref_mesh_.next_halfedge_handle(h0);
        p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h2));
        d0 = (p0 - p2).normalize();
        d1 = (p1 - p2).normalize();
        w += 1.0/ tan(acos(std::max(-1.0, std::min(1.0, dot(d1,d0) ))));

        h2 = ref_mesh_.next_halfedge_handle(h1);
        p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h2));
        d0 = (p0 - p2).normalize();
        d1 = (p1 - p2).normalize();
        w += 1.0 / tan(acos(std::max(-1.0, std::min(1.0, dot(d1,d0)))));

        if(std::isnan(w))
            std::cout<<"Some weight is NAN"<<std::endl;
        ref_mesh_.property(LB_weights,e_it) = w;
    }

    // prepare Sparse A_ matrix
    Eigen::SparseMatrix<double> A_;
    A_.resize(3*nver,3*nver);
    std::vector<Eigen::Triplet<double> > tripletlist;
    TriMesh::VertexIter v_it = ref_mesh_.vertices_begin();
    for(;v_it!=ref_mesh_.vertices_end();v_it++)
    {
        // fix one point
        TriMesh::VertexEdgeIter ve_iter = ref_mesh_.ve_iter(*v_it);
        int center_id = (*v_it).idx();
        double center_val[3]={0.0,0.0,0.0};
        for(;ve_iter.is_valid();ve_iter++)
        {
            double w = ref_mesh_.property(LB_weights,*ve_iter);
            TriMesh::VertexHandle to_v = ref_mesh_.to_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));
            if(to_v.idx() == center_id)
                to_v = ref_mesh_.from_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));
            for(int i =0;i<3;i++)
            {
                center_val[i]+=w;
                tripletlist.push_back(Eigen::Triplet<double>(3*center_id+i,3*to_v.idx()+i,-w));
//                outfile << 3*center_id + i << " " << 3*to_v.idx()+i << " "<< -w << '\n';
            }
        }
        for(int i =0;i<3;i++)
        {
            tripletlist.push_back(Eigen::Triplet<double>(3*center_id+i,3*center_id+i,center_val[i]));
        }
    }
    A_.setFromTriplets(tripletlist.begin(),tripletlist.end());
    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double> > A_solver_;
    A_solver_.compute(A_);
    // prepare T_matrix
    py::buffer_info feature_array = feature_input.request();
    std::vector<Eigen::Matrix3d> T_array;
    for(int i =0; i<ref_mesh_.n_vertices(); i++)
    {
        Eigen::Matrix3d logR;
        logR<<0,((double*)feature_array.ptr)[9*i+6],((double*)feature_array.ptr)[9*i+7],-((double*)feature_array.ptr)[9*i+6],0,((double*)feature_array.ptr)[9*i+8],-((double*)feature_array.ptr)[9*i+7],-((double*)feature_array.ptr)[9*i+8],0;
        Eigen::Matrix3d S;
        S<<((double*)feature_array.ptr)[9*i+0],((double*)feature_array.ptr)[9*i+1],((double*)feature_array.ptr)[9*i+2],((double*)feature_array.ptr)[9*i+1],((double*)feature_array.ptr)[9*i+3],((double*)feature_array.ptr)[9*i+4],((double*)feature_array.ptr)[9*i+2],((double*)feature_array.ptr)[9*i+4],((double*)feature_array.ptr)[9*i+5];
        T_array.push_back(exp(logR)*S);
    }

    // compute b_
    Eigen::VectorXd b_;
    b_.resize(3*nver);
    b_.setZero();
    v_it = ref_mesh_.vertices_begin();
    for(;v_it!=ref_mesh_.vertices_end();v_it++)
    {
        TriMesh::VertexEdgeIter ve_iter = ref_mesh_.ve_iter(*v_it);
        Eigen::Vector3d temp(0.0,0.0,0.0);
        for(;ve_iter.is_valid();ve_iter++)
        {
            TriMesh::VertexHandle v0 = ref_mesh_.to_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));
            if(v0.idx() == (*v_it).idx())
                v0 = ref_mesh_.from_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));
            OpenMesh::Vec3d Pj,Pk;
            Pj = ref_mesh_.point(*v_it);
            Pk = ref_mesh_.point(v0);
            Eigen::Vector3d e1jk(Pj[0]-Pk[0],Pj[1]-Pk[1],Pj[2]-Pk[2]);
            double cjk = ref_mesh_.property(LB_weights,*ve_iter);

            temp+= cjk*( T_array[v0.idx()] + T_array[(*v_it).idx()] )*e1jk;
        }
        temp*=0.5;
        b_.block<3,1>(3*(*v_it).idx(),0) = temp;
    }

    // solve
    Eigen::VectorXd out;
    out.resize(3*nver);
    out = A_solver_.solve(b_);

    // std::vector<double> P_;
        // std::cout<<"dahsdas"<<std::endl;

    // std::memcpy(P_.data(), out.data(), out.size()*sizeof(double));
    // Eigen::VectorXd::Map(&P_[0], out.size()) = out;
    std::vector<double> P_(out.data(), out.data()+out.size());
    auto result = py::array_t<double>(P_.size());
    auto result_buffer = result.request();
    double *result_ptr = (double *)result_buffer.ptr;

    std::memcpy(result_ptr, P_.data(), P_.size()*sizeof(double));

    // std::cout<<result[0]<<std::endl;
    return result;

    // for(int i =0; i< P_.rows(); i++)
    // std::cout<<P_[i]<<std::endl;
    // std::vector<size_t> strides = {sizeof(double)};
    // std::vector<size_t> shape = {feature_array.shape[0]/3};
    // size_t ndim = 1;
    // return py::array(py::buffer_info(P_.data(), sizeof(double), py::format_descriptor<double>::value, ndim, feature_array.shape, strides));
    // return py::array(nver, P_.data());
}
 PYBIND11_MODULE(get_mesh, m){
    m.doc() = "get mesh";
    m.def("get_mesh", &get_mesh, "get_mesh");
 }


text:
/*
 *  Distributed under the MIT License (See accompanying file /LICENSE )
 */
#include <doctest/doctest.h>  // for ResultBuilder

#include <array>                             // for operator==
#include <boost/multiprecision/cpp_int.hpp>  // for cpp_int
#include <ostream>                           // for operator<<
#include <tuple>                             // for tuple
#include <type_traits>                       // for move

#include "projgeom/ck_plane.hpp"            // for ellck, hyck
#include "projgeom/common_concepts.h"       // for Value_type
#include "projgeom/fractions.hpp"           // for operator*
#include "projgeom/persp_plane.hpp"         // for persp_eucl...
#include "projgeom/pg_common.hpp"           // for cross
#include "projgeom/pg_line.hpp"             // for pg_line
#include "projgeom/pg_object.hpp"           // for operator*
#include "projgeom/pg_point.hpp"            // for pg_point
#include "projgeom/proj_plane.hpp"          // for coincident
#include "projgeom/proj_plane_measure.hpp"  // for x_ratio
// #include <iostream>

using namespace fun;

static const auto Zero = doctest::Approx(0).epsilon(0.01);

/**
 * @brief
 *
 * @param[in] a
 * @return true
 * @return false
 */
template <typename T> inline auto ApproxZero(const T& a) -> bool {
    return a[0] == Zero && a[1] == Zero && a[2] == Zero;
}

template <typename PG> void chk_ck(const PG& myck) {
    using P = typename PG::point_t;
    using K = Value_type<P>;

    auto a1 = P{1, -2, 3};
    auto a2 = P{4, 0, 6};
    auto a3 = P{-7, 1, 2};
    const auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};
    const auto trilateral = tri_dual(triangle);
    const auto& [l1, l2, l3] = trilateral;
    const auto [t1, t2, t3] = myck.tri_altitude(triangle);

    auto o = myck.orthocenter(triangle);
    const auto tau = myck.reflect(l1);
    const auto Q = std::tuple{myck.tri_quadrance(triangle)};
    const auto S = std::tuple{myck.tri_spread(trilateral)};

    const auto a4 = P{3, 0, 2};

    if constexpr (Integral<K>) {
        CHECK(incident(l1, a2));
        CHECK(myck.is_perpendicular(t1, l1));
        CHECK(coincident(t1 * t2, t3));
        CHECK(o == t2 * t3);
        CHECK(a1 == myck.orthocenter(std::tuple{std::move(o), std::move(a2), std::move(a3)}));
        CHECK(tau(tau(a4)) == a4);
        // CHECK(myck.spread(l2, l2) == K(0));
        // CHECK(myck.spread(l3, l3) == K(0));
        // CHECK(myck.quadrance(a1, a1) == K(0));
        CHECK(check_sine_law(Q, S));
        CHECK(check_sine_law(S, Q));
    } else {
        CHECK(l1.dot(a2) == Zero);
        CHECK(l1.dot(myck.perp(t1)) == Zero);
        CHECK(t1.dot(t2 * t3) == Zero);
        CHECK(ApproxZero(cross(o, t2 * t3)));
        const auto o2 = myck.orthocenter(std::tuple{std::move(o), std::move(a2), std::move(a3)});
        CHECK(ApproxZero(cross(a1, o2)));
        CHECK(ApproxZero(cross(tau(tau(a4)), a4)));
        CHECK(myck.measure(l2, l2) == Zero);
        CHECK(myck.measure(l3, l3) == Zero);
        CHECK(myck.measure(a1, a1) == Zero);
        const auto& [q1, q2, q3] = Q;
        const auto& [s1, s2, s3] = S;

        const auto r1 = q1 * s2 - q2 * s1;
        const auto r2 = q2 * s3 - q3 * s2;
        CHECK(r1 == Zero);
        CHECK(r2 == Zero);
    }
}

template <typename P, typename L = typename P::dual>
requires Projective_plane_prim<P, L>  // c++20 concept
struct myck : ck<P, L, myck> {
    [[nodiscard]] constexpr auto perp(const P& v) const -> L {
        return L(-2 * v[0], v[1], -2 * v[2]);
    }

    [[nodiscard]] constexpr auto perp(const L& v) const -> P { return P(-v[0], 2 * v[1], -v[2]); }

    template <Projective_plane2 _P>
    [[nodiscard]] constexpr auto measure(const _P& a1, const _P& a2) const {
        auto x = x_ratio(a1, a2, this->perp(a2), this->perp(a1));
        // using Q_t = decltype(x);
        return 1 - x;
    }
};

TEST_CASE("CK plane chk_ck (int)") {
    // using boost::multiprecision::cpp_int;
    // namespace mp = boost::multiprecision;
    using boost::multiprecision::cpp_int;

    chk_ck(myck<pg_point<cpp_int>>());
    chk_ck(myck<pg_line<cpp_int>>());
    chk_ck(ellck<pg_point<cpp_int>>());
    chk_ck(ellck<pg_line<cpp_int>>());
    chk_ck(hyck<pg_point<cpp_int>>());
    chk_ck(hyck<pg_line<cpp_int>>());

    auto Ire = pg_point<cpp_int>{0, 1, 1};
    auto Iim = pg_point<cpp_int>{1, 0, 0};
    auto l_inf = pg_line<cpp_int>{0, -1, 1};

    auto P = persp_euclid_plane{std::move(Ire), std::move(Iim), std::move(l_inf)};
    chk_ck(P);
}

TEST_CASE("CK plane chk_ck (float)") {
    chk_ck(myck<pg_point<double>>());
    chk_ck(myck<pg_line<double>>());
    chk_ck(ellck<pg_point<float>>());
    chk_ck(ellck<pg_line<float>>());
    chk_ck(hyck<pg_point<double>>());
    chk_ck(hyck<pg_line<double>>());

    auto Ire = pg_point{0., 1., 1.};
    auto Iim = pg_point{1., 0., 0.};
    auto l_inf = pg_line{0., -1., 1.};

    auto P = persp_euclid_plane{std::move(Ire), std::move(Iim), std::move(l_inf)};
    chk_ck(P);
}

ext: cpp


text:
#include "hs_logdevice.h"
#include <boost/stacktrace.hpp>
#include <signal.h>

std::string* new_hs_std_string(std::string&& str) {
  auto value = new std::string;
  *value = str;
  return value;
}

// Copy string contents.
//
// Note that
// 1. this will not append the "\0" to the end of the memory.
// 2. you need to free the result manually.
char* copyString(const std::string& str) {
  char* result = reinterpret_cast<char*>(malloc(sizeof(char) * str.size()));
  memcpy(result, str.data(), sizeof(char) * str.size());
  return result;
}

extern "C" {

std::string* hs_cal_std_string_off(std::string* str, HsInt idx) {
  return str + idx;
}

void delete_vector_of_string(std::vector<std::string>* ss) { delete ss; }
void delete_vector_of_cint(std::vector<int>* ss) { delete ss; }

HsInt get_vector_of_string_size(std::vector<std::string>* ss) {
  return ss->size();
}

std::string* get_vector_of_string_data(std::vector<std::string>* ss) {
  return ss->data();
}

// End
}

max_stars_repo_name: Swilder-M/hstream

max_issues_repo_name: Swilder-M/hstream

max_forks_repo_name: Swilder-M/hstream


text:
// MIT License
//
// Copyright (c) 2019 ibis-ssl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by hans on 2019/10/24.
//
#include <world_model/ball_info.h>
#include <world_model/world_model.h>
#include <boost/numeric/interval.hpp>
#include <field_analysis/CMD14TDP_3/conditions.h>
#include <utils/interval.h>
#include <world_model/tool.h>

namespace condition {

    float ShootConditions::getSuccessRate(const WorldModel &world_model, Point target) {
        PassRestriction restriction;
        restriction.maximum_vel = 8.0f;
        restriction.minimum_vel = 0.0f;
        float total_rate = 1.0f;
        float rate;

        std::clamp(rate = getC1SuccessRate(world_model, target, restriction), 0.f, 1.f);
        total_rate *= rate;

        std::clamp(rate = getC2SuccessRate(world_model, target, restriction), 0.f, 1.f);
        total_rate *= rate;

//        std::clamp(rate = getC3SuccessRate(world_model, target, restriction),0.f,1.f);
//        total_rate *= rate;
//
        std::clamp(rate = getC4SuccessRate(world_model, target, restriction), 0.f, 1.f);
        total_rate *= rate;

        return total_rate;
    }

    float ShootConditions::getSuccessRate(int map_id, const WorldModel &world_model, Point target) {
        PassRestriction restriction;
        restriction.maximum_vel = 8.0f;
        restriction.minimum_vel = 0.0f;
        float rate;
        switch (map_id) {
            case 1:
                rate = getC1SuccessRate(world_model, target, restriction);
                break;

            case 2:
                rate = getC2SuccessRate(world_model, target, restriction);
                break;
            case 3:
                rate = getC3SuccessRate(world_model, target, restriction);
                break;

            case 4:
                rate = getC4SuccessRate(world_model, target, restriction);
                break;
            default:
                return 0.f;
        }
        std::clamp(rate, 0.f, 1.f);
        return rate;
    }

    /*
     * xからのシュートが敵キーパーのブロックよりも早い
     */
    float ShootConditions::getC1SuccessRate(const WorldModel &world_model, Point target, PassRestriction &restriction) {
        //TODO : 書く
        auto goalie = world_model.enemys.getGoalie();
        float goalie_angle = tool::getAngle(goalie->pose.pos - target);
        float angle_1 = tool::getAngle(Constants::Their::Goal::lower() - target);
        float angle_2 = tool::getAngle(Constants::Their::Goal::upper() - target);
        float diff_angle = std::max(std::abs(angle_1 - goalie_angle), std::abs(angle_2 - goalie_angle));

        float dist = bg::distance(target, Constants::Their::Goal::center());
        return 15.f * diff_angle / (dist + 8.0f);
    }

    /*
     * xからゴールを見た時に十分な角度を占めている
     */
    float ShootConditions::getC2SuccessRate(const WorldModel &world_model, Point target, PassRestriction &restriction) {
        Interval goal_range;

        float lower_angle = tool::getAngle(Constants::Their::Goal::lower() - target);
        float upper_angle = tool::getAngle(Constants::Their::Goal::upper() - target);

        goal_range.append(lower_angle, upper_angle);

        for (auto robot : world_model.enemys.robots) {
            if (robot->is_disappeared) {
                continue;
            }
            //targetから見てゴール側にいる敵ロボットのみ．それ以外はスキップ
            if ((robot->pose.pos - target).dot((Constants::Their::Goal::center() - target).normalized()) < 0.f) {
                continue;
            }

            float d = bg::distance(robot->pose.pos, target);
            float r = (Constants::robot_radius() * d) /
                      std::sqrt(d * d - Constants::robot_radius() * Constants::robot_radius());
            Point v_vec = tool::getVerticalVec((robot->pose.pos - target).normalized());
            float angle_1 = tool::getAngle(robot->pose.pos - target - (v_vec * r));
            float angle_2 = tool::getAngle(robot->pose.pos - target + (v_vec * r));
            goal_range.erase(std::min(angle_1, angle_2), std::max(angle_1, angle_2));
        }

        float goal_angle = goal_range.getWidth();
        //27度あったらいい方
        return goal_angle / (M_PI * 0.15f);
    }

    /*
     * 敵にシュートをブロックされない
     */
    float ShootConditions::getC3SuccessRate(const WorldModel &world_model, Point target, PassRestriction &restriction) {
        //TODO : 書く
        return 1.f;
    }

    /*
     * 敵にボールを奪われない
     */
    float ShootConditions::getC4SuccessRate(const WorldModel &world_model, Point target, PassRestriction &restriction) {
        float min_dist = 1000.f, dist;
        for (auto robot : world_model.enemys.robots) {
            dist = bg::distance(target, robot->pose.pos);
            min_dist = std::min(min_dist, dist);
        }
        return min_dist / 2.f;
    }
}


text:
/*
 * BufferManager.cpp
 *
 *  Created on: 2011-4-8
 *      Author: liupu
 */

#include "BufferManager.h"
#include "../EntityIDBuffer.h"
#include <boost/thread/mutex.hpp>

BufferManager* BufferManager::instance = NULL;

BufferManager::BufferManager()
{
	// TODO Auto-generated constructor stub
	for (int i = 0; i < INIT_BUFFERS; i++) {
		EntityIDBuffer* buffer = new EntityIDBuffer;
		bufferPool.push_back(buffer);
		cleanBuffer.push_back(buffer);
	}
	usedBuffer.clear();
	bufferCnt = INIT_BUFFERS;
}

BufferManager::~BufferManager()
{
	// TODO Auto-generated destructor stub
}

bool BufferManager::expandBuffer()
{
	for (int i = 0; i < INCREASE_BUFFERS; i++) {
		EntityIDBuffer* buffer = new EntityIDBuffer;
		if (buffer == NULL) {
			bufferCnt += i;
			return false;
		}
		bufferPool.push_back(buffer);
		cleanBuffer.push_back(buffer);
	}

	bufferCnt += INCREASE_BUFFERS;
	return true;
}

EntityIDBuffer* BufferManager::getNewBuffer()
{
	if (usedBuffer.size() == bufferPool.size()) {
		boost::mutex::scoped_lock lock(bufferMutex);
		if (expandBuffer() == false){
			return NULL;
		}
	}
	EntityIDBuffer* buffer = cleanBuffer.front();
	{
		cleanBuffer.erase(cleanBuffer.begin());;
		usedBuffer.push_back(buffer);
	}
	return buffer;
}

void BufferManager::destroyBuffers()
{
	for (size_t i = 0; i < bufferPool.size(); i++) {
		delete bufferPool[i];
	}

	usedBuffer.clear();
	cleanBuffer.clear();
}

Status BufferManager::freeBuffer(EntityIDBuffer* buffer)
{
	vector<EntityIDBuffer*>::iterator iter;
	iter = find(usedBuffer.begin(), usedBuffer.end(), buffer);
	if (iter != usedBuffer.end()) {
		boost::mutex::scoped_lock lock(bufferMutex);
		usedBuffer.erase(iter);
		cleanBuffer.push_back(*iter);
		(*iter)->empty();
		return OK;
	} else {
		return NOT_FOUND;
	}
}

Status BufferManager::reserveBuffer()
{
	usedBuffer.clear();
	cleanBuffer.clear();
	int i;
	for (i = 0; i < INIT_BUFFERS; i++) {
		bufferPool[i]->empty();
		cleanBuffer.push_back(bufferPool[i]);
	}

	vector<EntityIDBuffer*>::iterator iter = bufferPool.begin() + i;
	vector<EntityIDBuffer*>::iterator start = iter;
	for (; iter != bufferPool.end(); iter++) {
		delete *iter;
		*iter = NULL;
	}
	bufferPool.erase(start,iter);

	return OK;
}

BufferManager* BufferManager::getInstance()
{
	if (instance == NULL) {
		instance = new BufferManager;
	}

	return instance;
}

max_stars_repo_name: oeljeklaus-you/ParallelTripleBit

max_issues_repo_name: oeljeklaus-you/ParallelTripleBit

max_forks_repo_name: oeljeklaus-you/ParallelTripleBit


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

#include <boost/program_options/parsers.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/cmdline.hpp>
using namespace boost::program_options;

#include <iostream>
#include <sstream>
#include <vector>
#include <cassert>
using namespace std;

#include "minitest.hpp"

void test_ambiguous()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,c", value<string>(), "the output file")
        ("output,o", value<string>(), "the output file")
    ;

    const char* cmdline[] = {"program", "-c", "file", "-o", "anotherfile"};

    variables_map vm;
    try {
       store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
    }
    catch (ambiguous_option& e)
    {
        BOOST_CHECK_EQUAL(e.alternatives().size(), 2);
        BOOST_CHECK_EQUAL(e.get_option_name(), "-c");
        BOOST_CHECK_EQUAL(e.alternatives()[0], "cfgfile");
        BOOST_CHECK_EQUAL(e.alternatives()[1], "output");
    }
}

void test_ambiguous_long()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,c", value<string>(), "the output file")
        ("output,o", value<string>(), "the output file")
    ;

    const char* cmdline[] = {"program", "--cfgfile", "file", "--output", "anotherfile"};

    variables_map vm;
    try {
       store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
    }
    catch (ambiguous_option& e)
    {
        BOOST_CHECK_EQUAL(e.alternatives().size(), 2);
        BOOST_CHECK_EQUAL(e.get_option_name(), "--output");
        BOOST_CHECK_EQUAL(e.alternatives()[0], "output");
        BOOST_CHECK_EQUAL(e.alternatives()[1], "output");
    }
}

void test_ambiguous_multiple_long_names()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,foo,c", value<string>()->multitoken(), "the config file")
        ("output,foo,o", value<string>(), "the output file")
    ;

    const char* cmdline[] = {"program", "--foo", "file"};

    variables_map vm;
    try {
       store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
    }
    catch (ambiguous_option& e)
    {
        BOOST_CHECK_EQUAL(e.alternatives().size(), 2);
        BOOST_CHECK_EQUAL(e.get_option_name(), "--foo");
        BOOST_CHECK_EQUAL(e.alternatives()[0], "cfgfile");
        BOOST_CHECK_EQUAL(e.alternatives()[1], "output");
    }
}

void test_unknown_option()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "-c", "file", "-f", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
   }
   catch (unknown_option& e)
   {
      BOOST_CHECK_EQUAL(e.get_option_name(), "-f");
      BOOST_CHECK_EQUAL(string(e.what()), "unrecognised option '-f'");
   }
}

void test_multiple_values()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,o", value<string>(), "the output file")
      ;

   const char* cmdline[] = { "program", "-o", "fritz", "hugo", "--cfgfile", "file", "c", "-o", "text.out" };

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (validation_error& e)
   {
      // TODO: this is currently validation_error, shouldn't it be multiple_values ???
      //
      //   multiple_values is thrown only at one place untyped_value::xparse(),
      //    but I think this can never be reached
      //   because: untyped_value always has one value and this is filtered before reach specific
      //   validation and parsing
      //
      BOOST_CHECK_EQUAL(e.get_option_name(), "--cfgfile");
      BOOST_CHECK_EQUAL(string(e.what()), "option '--cfgfile' only takes a single argument");
   }
}

void test_multiple_occurrences()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "--cfgfile", "file", "-c", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (multiple_occurrences& e)
   {
      BOOST_CHECK_EQUAL(e.get_option_name(), "--cfgfile");
      BOOST_CHECK_EQUAL(string(e.what()), "option '--cfgfile' cannot be specified more than once");
   }
}

void test_multiple_occurrences_with_different_names()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,config-file,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "--config-file", "file", "--cfgfile", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (multiple_occurrences& e)
   {
      BOOST_CHECK( (e.get_option_name() == "--cfgfile") || (e.get_option_name() == "--config-file"));
      BOOST_CHECK(
         (string(e.what()) == "option '--cfgfile' cannot be specified more than once") ||
         (string(e.what()) == "option '--config-file' cannot be specified more than once")
      );
   }
}

void test_multiple_occurrences_with_non_key_names()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,config-file,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "--config-file", "file", "-c", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (multiple_occurrences& e)
   {
       BOOST_CHECK_EQUAL(e.get_option_name(), "--cfgfile");
       BOOST_CHECK_EQUAL(string(e.what()), "option '--cfgfile' cannot be specified more than once");
   }
}

void test_missing_value()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,o", value<string>(), "the output file")
    ;
    // missing value for option '-c'
    const char* cmdline[] = { "program", "-c", "-c", "output.txt"};

    variables_map vm;

    try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                       const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (invalid_command_line_syntax& e)
   {
      BOOST_CHECK_EQUAL(e.kind(), invalid_syntax::missing_parameter);
      BOOST_CHECK_EQUAL(e.tokens(), "--cfgfile");
   }
}

int main(int /*ac*/, char** /*av*/)
{
   test_ambiguous();
   test_ambiguous_long();
   test_ambiguous_multiple_long_names();
   test_unknown_option();
   test_multiple_values();
   test_multiple_occurrences();
   test_multiple_occurrences_with_different_names();
   test_multiple_occurrences_with_non_key_names();
   test_missing_value();

   return 0;
}


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

#include "write_projectq.hpp"

#include <fstream>

#include <boost/format.hpp>

#include <reversible/pauli_tags.hpp>
#include <reversible/target_tags.hpp>
#include <reversible/utils/circuit_utils.hpp>

namespace cirkit
{

/******************************************************************************
 * Types                                                                      *
 ******************************************************************************/

/******************************************************************************
 * Private functions                                                          *
 ******************************************************************************/

void write_controlled_gate( std::ostream& os, const std::string& indent, const gate& g, const std::string& gatename)
{
  const auto target = g.targets().front();

  std::string neg, beg, mid, end;
  for ( auto i = 0u; i < g.controls().size(); ++i )
  {
    if ( !g.controls()[i].polarity() )
    {
      neg += boost::str( boost::format( "%sX | qubits[%d]\n" ) % indent % g.controls()[i].line() );
    }
    beg += "C(";
    mid += boost::str( boost::format( "qubits[%d], " ) % g.controls()[i].line() );
    end += ")";
  }
  os << boost::format( "%s%s%s%s%s | (%squbits[%d])\n%s" ) % neg % indent % beg % gatename % end % mid % target % neg;
}

void write_projectq( const circuit& circ, std::ostream& os, const properties::ptr& settings )
{
  const auto check_identity = get( settings, "check_identity", true );
  const auto standalone = get( settings, "standalone", false );

  const auto n = circ.lines();
  if ( standalone )
  {
    os << "import itertools" << std::endl;
    os << "import sys" << std::endl << std::endl;

    os << "#!/usr/bin/env python3" << std::endl << std::endl;
    os << "import projectq" << std::endl;
    os << "from projectq.cengines import MainEngine" << std::endl;
    os << "from projectq.ops import H, C, CNOT, Toffoli, NOT, X, Measure, T, Tdag" << std::endl << std::endl;

    os << "import numpy as np" << std::endl << std::endl;

    os << "num_qubits = " << n << std::endl << std::endl;

    os << "def simulate(input):" << std::endl;
    os << "    eng = MainEngine()" << std::endl;
    os << "    qubits = eng.allocate_qureg(num_qubits)" << std::endl;
    os << "    for i, v in enumerate(input):" << std::endl;
    os << "        if v:" << std::endl;
    os << "            X | qubits[i]" << std::endl << std::endl;
  }

  std::string indent( ' ', standalone ? 4 : 0 );

  for ( const auto& g : circ )
  {
    const auto target = g.targets().front();

    if ( is_toffoli( g ) )
    {
      write_controlled_gate( os, indent, g, "NOT" );
    }
    else if ( is_hadamard( g ) )
    {
      os << boost::format( "%sH | qubits[%d]" ) % indent % target << std::endl;
    }
    else if ( is_pauli( g ) )
    {
      const auto pauli = boost::any_cast<pauli_tag>( g.type() );
      switch ( pauli.axis )
      {
      case pauli_axis::X:
        if ( pauli.root == 1u )
        {
          write_controlled_gate( os, indent, g, "X" );
        }
        else
        {
          os << "# unsupported X root" << std::endl;
        }
        break;
      case pauli_axis::Z:
        if ( pauli.root == 4u )
        {
          os << boost::format( "%s%s | qubits[%d]" ) % indent % ( pauli.adjoint ? "Tdag" : "T" ) % target << std::endl;
        }
        else if ( pauli.root == 1u )
        {
          write_controlled_gate( os, indent, g, "Z" );
        }
        else
        {
          os << "# unsupported Z root" << std::endl;
        }
        break;
      default:
        os << "# unsupported Pauli axis" << std::endl;
        break;
      }
    }
    else
    {
      os << "# unsupported gate" << std::endl;
    }
  }

  if ( standalone )
  {
    os << "    eng.flush()" << std::endl << std::endl;

    os << "    r = [[eng.backend.get_amplitude(p, qubits) for p in itertools.product('01', repeat = num_qubits)]]" << std::endl << std::endl;

    os << "    Measure | qubits" << std::endl << std::endl;

    os << "    return r" << std::endl << std::endl;

    os << "M = np.concatenate([simulate(input) for input in itertools.product([False, True], repeat = num_qubits)], axis = 0)" << std::endl << std::endl;

    os << "np.set_printoptions(linewidth = 200)" << std::endl;

    if ( check_identity )
    {
      os << boost::format( "print(np.array_equal(np.round(M), np.identity(%d)))" ) % ( 1 << n ) << std::endl;
    }
    else
    {
      os << "print(np.round(M))" << std::endl;
    }
  }
}

/******************************************************************************
 * Public functions                                                           *
 ******************************************************************************/

void write_projectq( const circuit& circ, const std::string& filename, const properties::ptr& settings )
{
  std::ofstream os( filename.c_str(), std::ofstream::out );

  write_projectq( circ, os, settings );

  os.close();
}

}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
// Author(s):         Inbae Jeong
// Maintainer:        Chansol Hong (cshong@rit.kaist.ac.kr)

#include "ai_base.hpp"

#include <boost/lexical_cast.hpp>
#include <boost/random/random_device.hpp>

#include <fstream>
#include <iostream>
#include <random>

class my_ai
  : public aiwc::ai_base
{
public:
  my_ai(std::string server_ip, std::size_t port, std::string realm, std::string key, std::string datapath, double dur)
    : aiwc::ai_base(std::move(server_ip), port, std::move(realm), std::move(key), std::move(datapath))
    , dur(dur)
  {
  }

private:
  void init()
  {
  }

  void update(const aiwc::frame& f)
  {
    if(f.reset_reason == aiwc::GAME_END) {
      return;
    }

    if(f.time >= last_changed + dur) {
      last_changed = f.time;
      std::mt19937 rng{boost::random_device{}()};
      std::uniform_real_distribution<double> dist(-1, 1);

      std::array<double, 10> wheels;
      for(int i = 0; i < 2*info.number_of_robots; i++)
        wheels[i] = info.max_linear_velocity[i/2]*dist(rng);
      set_wheel(wheels);
    }
  }

  void finish()
  {
    // You have less than 30 seconds before it's killed.
    std::ofstream ofs(datapath + "/result.txt");
    ofs << "my_result" << std::endl;
  }

private: // member variable
  double dur;
  double last_changed = -9999.;
};

int main(int argc, char *argv[])
{
  if(argc < 6) {
    std::cerr << "Usage " << argv[0] << " server_ip port realm key datapath" << std::endl;
    return -1;
  }

  const auto& server_ip = std::string(argv[1]);
  const auto& port      = boost::lexical_cast<std::size_t>(argv[2]);
  const auto& realm     = std::string(argv[3]);
  const auto& key       = std::string(argv[4]);
  const auto& datapath  = std::string(argv[5]);

  my_ai ai(server_ip, port, realm, key, datapath, 1.); // change velocity every second

  ai.run();

  return 0;
}

max_stars_repo_name: liujiajun/examples

max_issues_repo_name: liujiajun/examples

max_forks_repo_name: liujiajun/examples


text:
/* -*- c++ -*- */
/*
 * Copyright 2006,2010-2012 Free Software Foundation, Inc.
 *
 * This file is part of GNU Radio
 *
 * GNU Radio 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, or (at your option)
 * any later version.
 *
 * GNU Radio 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 GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "costas_loop_cc_impl.h"
#include <gnuradio/io_signature.h>
#include <gnuradio/expj.h>
#include <gnuradio/sincos.h>
#include <gnuradio/math.h>
#include <boost/format.hpp>

namespace gr {
  namespace digital {

    costas_loop_cc::sptr
    costas_loop_cc::make(float loop_bw, int order, bool use_snr)
    {
      return gnuradio::get_initial_sptr
	(new costas_loop_cc_impl(loop_bw, order, use_snr));
    }

    static int ios[] = { sizeof(gr_complex), sizeof(float), sizeof(float), sizeof(float) };
    static std::vector<int> iosig(ios, ios+sizeof(ios)/sizeof(int));

    costas_loop_cc_impl::costas_loop_cc_impl(float loop_bw, int order, bool use_snr)
      : sync_block("costas_loop_cc",
                   io_signature::make(1, 1, sizeof(gr_complex)),
                   io_signature::makev(1, 4, iosig)),
	blocks::control_loop(loop_bw, 1.0, -1.0),
	d_order(order), d_error(0), d_noise(1.0), d_phase_detector(NULL)
    {
      // Set up the phase detector to use based on the constellation order
      switch(d_order) {
      case 2:
        if(use_snr)
          d_phase_detector = &costas_loop_cc_impl::phase_detector_snr_2;
	else
          d_phase_detector = &costas_loop_cc_impl::phase_detector_2;
	break;

      case 4:
        if(use_snr)
          d_phase_detector = &costas_loop_cc_impl::phase_detector_snr_4;
	else
          d_phase_detector = &costas_loop_cc_impl::phase_detector_4;
	break;

      case 8:
        if(use_snr)
          d_phase_detector = &costas_loop_cc_impl::phase_detector_snr_8;
	else
          d_phase_detector = &costas_loop_cc_impl::phase_detector_8;
	break;

      default:
	throw std::invalid_argument("order must be 2, 4, or 8");
	break;
      }

      message_port_register_in(pmt::mp("noise"));
      set_msg_handler(
        pmt::mp("noise"),
        boost::bind(&costas_loop_cc_impl::handle_set_noise,
                    this, _1));
    }

    costas_loop_cc_impl::~costas_loop_cc_impl()
    {
    }

    float
    costas_loop_cc_impl::phase_detector_8(gr_complex sample) const
    {
      /* This technique splits the 8PSK constellation into 2 squashed
	 QPSK constellations, one when I is larger than Q and one
	 where Q is larger than I. The error is then calculated
	 proportionally to these squashed constellations by the const
	 K = sqrt(2)-1.

	 The signal magnitude must be > 1 or K will incorrectly bias
	 the error value.

	 Ref: Z. Huang, Z. Yi, M. Zhang, K. Wang, "8PSK demodulation for
	 new generation DVB-S2", IEEE Proc. Int. Conf. Communications,
	 Circuits and Systems, Vol. 2, pp. 1447 - 1450, 2004.
      */

      float K = (sqrt(2.0) - 1);
      if(fabsf(sample.real()) >= fabsf(sample.imag())) {
	return ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() -
		(sample.imag()>0 ? 1.0 : -1.0) * sample.real() * K);
      }
      else {
	return ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() * K -
		(sample.imag()>0 ? 1.0 : -1.0) * sample.real());
      }
    }

    float
    costas_loop_cc_impl::phase_detector_4(gr_complex sample) const
    {
      return ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() -
	      (sample.imag()>0 ? 1.0 : -1.0) * sample.real());
    }

    float
    costas_loop_cc_impl::phase_detector_2(gr_complex sample) const
    {
      return (sample.real()*sample.imag());
    }

    float
    costas_loop_cc_impl::phase_detector_snr_8(gr_complex sample) const
    {
      float K = (sqrt(2.0) - 1);
      float snr = abs(sample)*abs(sample) / d_noise;
      if(fabsf(sample.real()) >= fabsf(sample.imag())) {
	return ((blocks::tanhf_lut(snr*sample.real()) * sample.imag()) -
          (blocks::tanhf_lut(snr*sample.imag()) * sample.real() * K));
      }
      else {
	return ((blocks::tanhf_lut(snr*sample.real()) * sample.imag() * K) -
          (blocks::tanhf_lut(snr*sample.imag()) * sample.real()));
      }
    }

    float
    costas_loop_cc_impl::phase_detector_snr_4(gr_complex sample) const
    {
      float snr = abs(sample)*abs(sample) / d_noise;
      return ((blocks::tanhf_lut(snr*sample.real()) * sample.imag()) -
              (blocks::tanhf_lut(snr*sample.imag()) * sample.real()));
    }

    float
    costas_loop_cc_impl::phase_detector_snr_2(gr_complex sample) const
    {
      float snr = abs(sample)*abs(sample) / d_noise;
      return blocks::tanhf_lut(snr*sample.real()) * sample.imag();
    }

    float
    costas_loop_cc_impl::error() const
    {
      return d_error;
    }

    void
    costas_loop_cc_impl::handle_set_noise(pmt::pmt_t msg)
    {
      if(pmt::is_real(msg)) {
        d_noise = pmt::to_double(msg);
        d_noise = powf(10.0f, d_noise/10.0f);
      }
    }

    int
    costas_loop_cc_impl::work(int noutput_items,
			      gr_vector_const_void_star &input_items,
			      gr_vector_void_star &output_items)
    {
      const gr_complex *iptr = (gr_complex *) input_items[0];
      gr_complex *optr = (gr_complex *) output_items[0];
      float *freq_optr  = output_items.size() >= 2 ? (float *) output_items[1] : NULL;
      float *phase_optr = output_items.size() >= 3 ? (float *) output_items[2] : NULL;
      float *error_optr = output_items.size() >= 4 ? (float *) output_items[3] : NULL;

      gr_complex nco_out;

      std::vector<tag_t> tags;
      get_tags_in_range(tags, 0, nitems_read(0),
                        nitems_read(0)+noutput_items,
                        pmt::intern("phase_est"));

      for(int i = 0; i < noutput_items; i++) {
        if(tags.size() > 0) {
          if(tags[0].offset-nitems_read(0) == (size_t)i) {
            d_phase = (float)pmt::to_double(tags[0].value);
            tags.erase(tags.begin());
          }
        }

        nco_out = gr_expj(-d_phase);
        optr[i] = iptr[i] * nco_out;

        d_error = (*this.*d_phase_detector)(optr[i]);
        d_error = gr::branchless_clip(d_error, 1.0);

        advance_loop(d_error);
        phase_wrap();
        frequency_limit();

        if (freq_optr != NULL)
          freq_optr[i] = d_freq;
        if (phase_optr != NULL)
          phase_optr[i] = d_phase;
        if (error_optr != NULL)
          error_optr[i] = d_error;
      }

      return noutput_items;
    }

    void
    costas_loop_cc_impl::setup_rpc()
    {
#ifdef GR_CTRLPORT
      // Getters
      add_rpc_variable(
          rpcbasic_sptr(new rpcbasic_register_get<costas_loop_cc, float>(
	      alias(), "error",
	      &costas_loop_cc::error,
	      pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f),
	      "", "Error signal of loop", RPC_PRIVLVL_MIN,
              DISPTIME | DISPOPTSTRIP)));

      add_rpc_variable(
          rpcbasic_sptr(new rpcbasic_register_get<control_loop, float>(
	      alias(), "frequency",
	      &control_loop::get_frequency,
	      pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f),
	      "", "Frequency Est.", RPC_PRIVLVL_MIN,
              DISPTIME | DISPOPTSTRIP)));

      add_rpc_variable(
          rpcbasic_sptr(new rpcbasic_register_get<control_loop, float>(
	      alias(), "phase",
	      &control_loop::get_phase,
	      pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f),
	      "", "Phase Est.", RPC_PRIVLVL_MIN,
              DISPTIME | DISPOPTSTRIP)));

      add_rpc_variable(
          rpcbasic_sptr(new rpcbasic_register_get<control_loop, float>(
	      alias(), "loop_bw",
	      &control_loop::get_loop_bandwidth,
	      pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f),
	      "", "Loop bandwidth", RPC_PRIVLVL_MIN,
              DISPTIME | DISPOPTSTRIP)));

      // Setters
      add_rpc_variable(
          rpcbasic_sptr(new rpcbasic_register_set<control_loop, float>(
	      alias(), "loop_bw",
	      &control_loop::set_loop_bandwidth,
	      pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f),
	      "", "Loop bandwidth",
	      RPC_PRIVLVL_MIN, DISPNULL)));
#endif /* GR_CTRLPORT */
    }

  } /* namespace digital */
} /* namespace gr */

ext: cc


text:
#pragma once

#include <net/async.hpp>

#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/http/message.hpp>
#include <memory>
#include <future>
#include <functional>

namespace net {
class client;
class server;
}

namespace http {

using response_t = boost::beast::http::response<boost::beast::http::dynamic_body>;
using request_t = boost::beast::http::request<boost::beast::http::string_body>;

class connection {
    using stream_t = boost::beast::tcp_stream;
public:
    connection() = default;
    connection(boost::asio::io_context& io_ctx, const std::string& sni_hostname, boost::asio::ip::tcp::resolver::results_type resolve);
    explicit connection(boost::asio::ip::tcp::socket socket);
    ~connection();
    connection(const connection&) = delete;
    connection(connection&&) noexcept ;
    connection& operator=(const connection&) = delete;
    connection& operator=(connection&&) noexcept ;

    http::response_t send(const request_t& request);

    void close();

    explicit operator bool() const;

    std::future<void> handle_request(std::function<http::response_t(const http::request_t&)> func);

    class listener;

private:

    friend class net::client;
    friend class net::server;

    class connector;

    std::unique_ptr<stream_t> stream_;
    std::function<http::response_t(const request_t&)> on_request_;
    std::promise<void> next_response_;
    request_t next_request_;
    boost::beast::flat_buffer buffer_;
};

class connection::connector : public std::enable_shared_from_this<connection::connector> {
    stream_t stream_;
    std::string host_, port_;
public:
    connector(boost::asio::io_context& io_ctx, const std::string& host, const std::string& port);

    void on_resolve(boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type results);
    void on_connect(boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint);

    std::promise<connection> result; // NOLINT (cppcoreguidelines-non-private-member-variables-in-classes)
};

class connection::listener : public std::enable_shared_from_this<connection::listener> {
public:
    listener(boost::asio::io_context& io_ctx, const std::string& host, uint16_t port);
    std::future<connection> accept_next();
private:
    void on_accept(boost::beast::error_code ec, boost::asio::ip::tcp::socket socket);

    boost::asio::ip::tcp::acceptor acceptor_;
    std::promise<connection> connection_;
};

}

ext: hpp

max_stars_repo_name: shimondoodkin/net

max_issues_repo_name: shimondoodkin/net

max_forks_repo_name: shimondoodkin/net


text:
//===-- utility/BenchmarkEnvironment.cpp --------------------------------------------*- C++ -*-===//
//
//                                    S E R I A L B O X
//
// This file is distributed under terms of BSD license.
// See LICENSE.txt for more information
//
//===------------------------------------------------------------------------------------------===//
//
/// \file
/// This file provides the interface to define and register performance Unittests
///
//===------------------------------------------------------------------------------------------===//

#include "utility/BenchmarkEnvironment.h"
#include "serialbox/core/Logging.h"
#include "serialbox/core/STLExtras.h"
#include <boost/format.hpp>
#include <iostream>

namespace serialbox {

namespace unittest {

std::string Size::toString() const {
  std::stringstream ss;
  if(!dimensions.empty()) {
    ss << "[ ";
    for(std::size_t i = 0; i < dimensions.size() - 1; ++i)
      ss << dimensions[i] << ", ";
    ss << dimensions.back() << " ]";
  }
  return ss.str();
}

BenchmarkEnvironment* BenchmarkEnvironment::instance_ = nullptr;

BenchmarkEnvironment& BenchmarkEnvironment::getInstance() noexcept {
  if(!instance_)
    instance_ = new BenchmarkEnvironment;
  return (*instance_);
}

void BenchmarkEnvironment::SetUp() {
  bool hasError = false;
  std::string errStr;

  // Try to create a path to run our unittests in the form "$(pwd)/benchmark-tmp-dir/"
  try {
    directory_ = std::make_unique<filesystem::path>(filesystem::current_path() /
                                                    filesystem::path("benchmark-tmp-dir"));

    if(filesystem::exists(*directory_))
      serialbox::remove_all(*directory_);

    hasError = !filesystem::create_directories(*directory_);

    LOG(info) << "Creating unittest directory: " << directory_->string();
  } catch(filesystem::filesystem_error& e) {
    LOG(warning) << "unresolved filesystem::filesystem_error: " << e.what();
    hasError = true;
    errStr += e.what();
  }

  // If we encounterd an error we give up
  if(hasError) {
    std::cerr << "serialbox::BenchmarkEnvironment: failed to create benchmark directory: "
              << errStr;
    std::abort();
  }

  // Setup sizes
  sizes_ = {{{1024}}, {{512, 2}}, {{128, 128, 4}}};
}

void BenchmarkEnvironment::TearDown() {
  reportResults();
  try {
    auto numFiles = serialbox::remove_all(*directory_);
    LOG(info) << "Removed " << numFiles << " files";
  } catch(filesystem::filesystem_error& e) {
    LOG(warning) << e.what();
  }
}

void BenchmarkEnvironment::reportResults() const {
  const int TerminalLength = 78;

  std::string banner(TerminalLength, '-');
  std::cout << banner << "\n";

  if(results_.empty())
    std::cout << "    NO BENCHMARKS REPORTED\n";
  else
    for(const auto& result : results_) {
      std::cout << (boost::format("  %s\n") % result.name);
      std::cout << "  " << std::string(result.name.size(), '=') << "\n";
      std::string header =
          (boost::format("%-15s %-20s %15s") % "Mode" % "Size" % "Time (ms)").str();
      std::cout << "  " << header << "\n";
      std::cout << "  " << std::string(header.size(), '-') << "\n";

      for(const auto& timingPair : result.timingsWrite)
        std::cout << (boost::format("  %-15s %-20s %15.5f\n") % "Writing" %
                      timingPair.first.toString() % timingPair.second);

      for(const auto& timingPair : result.timingsRead)
        std::cout << (boost::format("  %-15s %-20s %15.5f\n") % "Reading" %
                      timingPair.first.toString() % timingPair.second);
      std::cout << "\n";
    }

  std::cout << banner << std::endl;
}

std::string BenchmarkEnvironment::testCaseName() const {
  const ::testing::TestInfo* testInfo = ::testing::UnitTest::GetInstance()->current_test_info();
  if(testInfo)
    return testInfo->test_case_name();
  return "UnknownTestCase";
}

std::string BenchmarkEnvironment::testName() const {
  const ::testing::TestInfo* testInfo = ::testing::UnitTest::GetInstance()->current_test_info();
  if(testInfo)
    return testInfo->name();
  return "UnknownTest";
}

} // namespace unittest

} // namespace serialbox

max_stars_repo_name: elsagermann/serialbox

max_issues_repo_name: elsagermann/serialbox

max_forks_repo_name: elsagermann/serialbox


text:
/*=========================================================================

Library:   UltrasoundScoliosis

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/

// Interson Array probe
//const double IntersonFrequencies[] = { 5.0, 7.5, 10.0 };
// Interson probe
//const double frequencies[] = { 2.5, 3.5, 5.0 };

#include "ScoliosisUI.h"

#include "ScoliosisServer.h"
#include "ScoliosisQueryNN.h"

#include "ITKQtHelpers.hxx"
#include "ITKFilterFunctions.h"
#include "itkTileImageFilter.h"
#include "itkImageFileWriter.h"

#include <sstream>
#include <iomanip>
#include <string>
#include <time.h>

#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

void ScoliosisUI::closeEvent( QCloseEvent *event )
{

#ifdef DEBUG_PRINT
  std::cout << "Close event called" << std::endl;
#endif
  intersonDevice.Stop();
}

ScoliosisUI::ScoliosisUI( int numberOfThreads, int bufferSize, QWidget *parent )
  : QMainWindow( parent ), ui( new Ui::MainWindow ),
  lastRendered( -1 ),
  mmPerPixel( 1 ), nnSocketConnection()
{

  start_server();

  //Setup the graphical layout on this current Widget
  ui->setupUi( this );

  this->setWindowTitle( "Ultrasound Scoliosis Monitoring" );

  //Links buttons and actions
  connect( ui->pushButton_ConnectProbe,
    SIGNAL( clicked() ), this, SLOT( ConnectProbe() ) );
  connect( ui->spinBox_Depth,
    SIGNAL( valueChanged( int ) ), this, SLOT( SetDepth() ) );
  connect( ui->dropDown_Frequency,
    SIGNAL( currentIndexChanged( int ) ), this, SLOT( SetFrequency() ) );
  //connect( ui->checkBox_doubler, SIGNAL( stateChanged(int) ), this,
  //         SLOT( SetDoubler() ) );

  connect(ui->generateIdentifierButton,
  SIGNAL(clicked()), this, SLOT(SetPatientID()));
  connect(ui->recordButton,
    SIGNAL(clicked()), this, SLOT(Record()));
  connect(ui->stopButton,
    SIGNAL(clicked()), this, SLOT(StopRecording()));

  intersonDevice.SetRingBufferSize( bufferSize );

  this->processing = new QTimer( this );
  this->processing->setSingleShot( false );
  this->processing->setInterval( 1000 );

  // Timer
  this->timer = new QTimer( this );
  this->timer->setSingleShot( true );
  this->timer->setInterval( 50 );
  this->connect( timer, SIGNAL( timeout() ), SLOT( UpdateImage() ) );

  this->updateConnectionUIsTimer = new QTimer(this);
  this->updateConnectionUIsTimer->setSingleShot(false);

  this->updateConnectionUIsTimer->setInterval(2000);
  this->connect(updateConnectionUIsTimer, SIGNAL ( timeout () ) , SLOT( UpdateConnectionUIs() ));
  this->updateConnectionUIsTimer->start();

  srand(time(NULL)); //for random patient IDs
  this->SetPatientID();
}

ScoliosisUI::~ScoliosisUI()
{
  //this->intersonDevice.Stop();
  delete ui;
}

void ScoliosisUI::ConnectProbe()
{
#ifdef DEBUG_PRINT
  std::cout << "Connect probe called" << std::endl;
#endif
  if( !intersonDevice.ConnectProbe( false ) )
  {
#ifdef DEBUG_PRINT
    std::cout << "Connect probe failed" << std::endl;
#endif
    return;
    //TODO: Show UI message
  }

  IntersonArrayDeviceRF::FrequenciesType fs = intersonDevice.GetFrequencies();
  ui->dropDown_Frequency->clear();
  for( unsigned int i = 0; i < fs.size(); i++ )
  {
    std::ostringstream ftext;
    ftext << std::setprecision( 1 ) << std::setw( 3 ) << std::fixed;
    ftext << fs[ i ] << " hz";
    ui->dropDown_Frequency->addItem( ftext.str().c_str() );
  }

  intersonDevice.GetHWControls().SetNewHardButtonCallback( &ProbeHardButtonCallback, this );

  mmPerPixel = intersonDevice.GetMmPerPixel();
  if( !intersonDevice.Start() )
  {
#ifdef DEBUG_PRINT
    std::cout << "Starting scan failed" << std::endl;
#endif
    return;
    //TODO: Show UI message
  }

  this->USConnected = true;

  this->ui->dropDown_Frequency->setCurrentIndex(1);
  this->SetFrequency();
  this->SetDepth();

  this->ui->l_probeConnected->setText("Probe Connected");

  this->timer->start();
}

void ScoliosisUI::Record()
{
  if (this->state == WaitingToRecord)
  {
    this->ui->generateIdentifierButton->setEnabled(false);
    this->ui->stopButton->setEnabled(true);
    this->ui->recordButton->setEnabled(false);
    this->scan_metadata.put("frequency", this->ui->dropDown_Frequency->currentIndex());
    this->scan_metadata.put("depth", this->ui->spinBox_Depth->value());

    boost::property_tree::ptree frame_metadata;
    this->scan_metadata.add_child("frame_metadata", frame_metadata);

    this->state = Recording;
    std::cout << "Recording" << std::endl;
  }
}
void ScoliosisUI::StopRecording()
{
  if (this->state == Recording)
  {
    this->ui->generateIdentifierButton->setEnabled(true);
    this->ui->stopButton->setEnabled(false);
    this->ui->recordButton->setEnabled(true);
    this->state = WritingToDisk;

    typedef itk::Image<IntersonArrayDeviceRF::ImageType::PixelType, 3> StackedImageType;

    typedef itk::TileImageFilter<IntersonArrayDeviceRF::ImageType, StackedImageType> FilterType;

    auto tiler = FilterType::New();
    itk::FixedArray< unsigned int, 3> layout;

    layout[0] = 1;
    layout[1] = 1;
    layout[2] = 0;

    tiler->SetLayout(layout);

    for (int i = 0; i < this->savedImages.size(); i++)
    {
      std::cerr << i << std::endl;
      tiler->SetInput(i, savedImages[i]);
    }
    IntersonArrayDeviceRF::ImageType::PixelType filler = 0;
    tiler->SetDefaultPixelValue(filler);

    tiler->Update();

    typedef itk::ImageFileWriter<StackedImageType> WriterType;

    auto writer = WriterType::New();

    writer->SetInput(tiler->GetOutput());
    writer->SetFileName("data\\" + this->patientID + "_" + std::to_string(++ this->scan_count) +  ".nrrd");

    writer->Update();

    this->savedImages.clear();

    boost::property_tree::write_json("data\\" + this->patientID + "_" +
      std::to_string(this->scan_count) + ".json", this->scan_metadata);
    this->scan_metadata.clear();

    this->state = WaitingToRecord;
  }
}

void ScoliosisUI::SetPatientID()
{
  if (this->state == WaitingToGenerateIdentifier)
  {
    this->state = WaitingToRecord;
    this->ui->recordButton->setEnabled(true);
  }
  if (this->state == WaitingToRecord)
  {
    this->patientID = "------";

    for (int j = 0; j < 3; j++)
    {
      patientID[j] = rand() % 26 + 65;
      patientID[j + 3] = rand() % 10 + 48;
    }

    ui->lineEdit->setText(QString(this->patientID.c_str()));
    this->scan_count = 0;
  }
}

void ScoliosisUI::UpdateImage()
{
  //display bmode image
  int currentIndex = intersonDevice.GetCurrentBModeIndex();
  if( currentIndex >= 0 && currentIndex != lastRendered )
  {
    lastRendered = currentIndex;
    IntersonArrayDeviceRF::ImageType::Pointer bmode =
      intersonDevice.GetBModeImage( currentIndex );

    QImage image = ITKQtHelpers::GetQImageColor<IntersonArrayDeviceRF::ImageType>(
      bmode,
      bmode->GetLargestPossibleRegion(),
      QImage::Format_RGB16
      );

    ui->label_BModeImage->setPixmap( QPixmap::fromImage( image ) );
    ui->label_BModeImage->setScaledContents( true );
    ui->label_BModeImage->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
    float theta, quality;
    if (this->NNConnected)
    {
      NetworkResponse resp = nnSocketConnection.QueryNN(bmode->GetBufferPointer());
      theta = resp.angleInRadians;

      ui->label_estimateCurrent->setText((std::to_string(theta) + " " +
        std::to_string((int)(100 * resp.maxOfPDF / 8))).c_str());
      ui->imageQuality->setValue((int)(100 * resp.maxOfPDF / 8));
      quality = resp.maxOfPDF;
    }
    if (this->state == Recording)
    {
      this->savedImages.push_back(bmode);

      boost::property_tree::ptree frame;
      frame.put("accelerometer_angle", server_roll);
      frame.put("nn_angle", theta);
      frame.put("nn_quality", quality);
      this->scan_metadata.get_child("frame_metadata").push_back(std::make_pair("", frame));
    }

    int secs = this->savedImages.size() / 15;
    ui->label_7->setText((std::to_string(secs / 60) + ":" +
      (secs % 60 < 10 ? "0" : "") + std::to_string(secs % 60)).c_str());
  }
  double r = server_roll;
  ui->label_ProbeToGround->setText(std::to_string(r).c_str());
  this->timer->start();
}

void ScoliosisUI::UpdateConnectionUIs()
{
  if (!this->NNConnected)
  {
    this->NNConnected = this->nnSocketConnection.Connect();
    if (this->NNConnected)
    {
      ui->l_nnConnected->setText("Neural Network Connected");
    }
  }
  if (server_roll != 0)
  { //Fixme
    trackerConnected = true;
    ui->l_phoneConnected->setText("Tracker Connected");
  }
  if (NNConnected && USConnected && trackerConnected && this->state == WaitingForInitialization)
  {
    this->state = WaitingToGenerateIdentifier;
    this->ui->generateIdentifierButton->setEnabled(true);
  }
}

void ScoliosisUI::SetFrequency()
{
  this->intersonDevice.SetFrequency(
    this->ui->dropDown_Frequency->currentIndex() );
}

void ScoliosisUI::SetDepth()
{
  int depth = this->intersonDevice.SetDepth(
    this->ui->spinBox_Depth->value() );
  this->ui->spinBox_Depth->setValue( depth );
}

void ScoliosisUI::SetDoubler()
{
  //this->intersonDevice.SetDoubler( this->ui->checkBox_doubler->isChecked() );
}

ext: cxx

max_stars_repo_name: HastingsGreer/UltrasoundScoliosis

max_issues_repo_name: HastingsGreer/UltrasoundScoliosis

max_forks_repo_name: HastingsGreer/UltrasoundScoliosis


text:
/*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.

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

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the Vodafone Group Services Ltd 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 "SQLTrafficElementStrings.h"

#include "DisturbanceElement.h"

#include "StringUtility.h"
#include "SQLStringStream.h"
#include "MapBits.h"

#include <boost/lexical_cast.hpp>

namespace SQLTrafficElementStrings {

MC2String createDeleteQuery( const MC2String& table,
                             const TrafficElementDatabase::
                             TrafficElements& removeElements ) {
   SQL::StringStream query;
   query << "DELETE FROM " << table.c_str() << " WHERE situationReference IN(";
   for ( TrafficElementDatabase::TrafficElements::const_iterator
            it = removeElements.begin();
         it != removeElements.end(); ++it ) {
      if ( it != removeElements.begin() ) {
         query << ", ";
      }
      query << (*it)->getSituationReference();
   }
   // add empty string for empty
   if ( removeElements.empty() ) {
      query << "''";
   }

   query << ")";

   return query.str();
}

void createDisturbanceValues( SQL::StringStream& stream,
                              const DisturbanceElement& element ) {
   stream << "("
          << element.getDisturbanceID() << ", "
          << element.getSituationReference() << ", "
          << element.getType() << ", "
          << element.getPhrase() << ", "
          << element.getEventCode() << ", "
          << element.getStartTime() << ", "
          << element.getEndTime() << ", "
          << element.getCreationTime() << ", "
          << element.getSeverity() << ", "
          << element.getDirection() << ", "
          << StringUtility::SQLEscapeSecure( element.getText() ) << ", "
          << element.getDeleted() << ", "
          << element.getFirstLocation() << ", "
          << element.getSecondLocation() << ", "
          << element.getExtent() << ", "
          << element.getCostFactor() << ", "
          << element.getQueueLength() << ")";
}

TrafficElementDatabase::TrafficElements::const_iterator
createAddQueryDisturbance(
      TrafficElementDatabase::TrafficElements::const_iterator begin,
      const TrafficElementDatabase::TrafficElements::const_iterator end,
      MC2String& queryString,
      const size_t queryMaxSize ) {
   SQL::StringStream query;
   query << "REPLACE INTO ISABDisturbance"
         << "(disturbanceID, situationReference, type, phrase, eventCode,"
         << " startTime, endTime, creationTime,"
         << " severity, direction, text, deleted, firstLocation,"
         << " secondLocation, extent, costFactor, queueLength)"
         <<  " VALUES";

   // For all disturbances; create table values
   bool processedElement = false;
   for ( ; begin != end; ++begin ) {
      // only write data that is from the underview maps, since the information
      // on the overview maps are based on this information.
      if ( MapBits::isUnderviewMap( (*begin)->getMapID() ) ) {
         // add "," after all new elements, except before the first and the
         // last element.
         if ( processedElement ) {
            query << ",";
         }

         // create disturbance values for current disturbance
         createDisturbanceValues( query, **begin );
         processedElement = true;
      }
      //  check the query size limit, this is done so we can be sure that the
      //  query size wont be bigger then the size set in 'max_allowed_packet'
      //  size in the data base.
      if ( query.str().size() > queryMaxSize ) {
         queryString = query.str();
         return ++begin;
      }
   }

   // needed since there is a possibillity that all the elements are not
   // from underview maps which results in a "empty" query.
   if ( processedElement ) {
      queryString = query.str();
   }

   return begin;
}

void createCoordValues( SQL::StringStream& stream,
                        const DisturbanceElement& element ) {
   typedef DisturbanceElement::RouteIndex2CoordMap RouteIndex2CoordMap;
   typedef DisturbanceElement::RouteIndex2AngleMap RouteIndex2AngleMap;
   const RouteIndex2CoordMap& latVector = element.getLatMap();
   const RouteIndex2CoordMap& lonVector = element.getLonMap();
   const RouteIndex2AngleMap& angleVector = element.getAngle();
   const DisturbanceElement::RouteIndex& indexVector = element.getRouteIndex();
   // For all route indexes; create coord table values
   for ( DisturbanceElement::RouteIndex::const_iterator
            indexIt = indexVector.begin();
         indexIt != indexVector.end();
         ++indexIt) {
      // add "," after all new elements, except the last
      if ( indexIt != indexVector.begin() ) {
         stream << ",";
      }
      RouteIndex2CoordMap::value_type::first_type routeIndex = *indexIt;
      RouteIndex2CoordMap::const_iterator latlonIt =
         latVector.find( routeIndex);

      RouteIndex2CoordMap::value_type::second_type latitude = latlonIt->second;
      latlonIt = lonVector.find( routeIndex );
      RouteIndex2CoordMap::value_type::second_type longitude = latlonIt->second;
      RouteIndex2AngleMap::const_iterator it = angleVector.find( routeIndex );
      RouteIndex2AngleMap::value_type::second_type angle = it->second;

      stream << "(" << element.getDisturbanceID()
             << ", " << element.getSituationReference() << ", "
             << latitude << ", " << longitude << ", " << angle << ", "
             << routeIndex << ")";

   }

}

TrafficElementDatabase::TrafficElements::const_iterator
createAddQueryCoords(
      TrafficElementDatabase::TrafficElements::const_iterator begin,
      const TrafficElementDatabase::TrafficElements::const_iterator end,
      MC2String& queryString,
      const size_t queryMaxSize ) {

   SQL::StringStream query;
   query << "REPLACE INTO ISABDisturbanceCoords("
         << "disturbanceID, situationReference, "
         << "latitude, longitude, angle, routeIndex) VALUES";

   // For all disturbances; create coord values for table
   bool processedElement = false;
   for ( ; begin != end; ++begin ) {
      // only write data that is from the underview maps, since the information
      // on the overview maps are based on this information.
      if ( MapBits::isUnderviewMap( (*begin)->getMapID() ) ) {
         // add "," after all new elements, except before the first and the
         // last element.
         if ( processedElement ) {
            query << ",";
         }

         // create coord values for current disturbance
         createCoordValues( query, **begin );
         processedElement = true;
      }

      //  check the query size limit, this is done so we can be sure that the
      //  query size wont be bigger then the size set in 'max_allowed_packet'
      //  size in the data base.
      if ( query.str().size() > queryMaxSize ) {
         queryString = query.str();
         return ++begin;
      }
   }

   // needed since there is a possibillity that all the elements are not
   // from underview maps which results in a "empty" query.
   if ( processedElement ) {
      queryString = query.str();
   }

   return begin;
}

} // SQLTrafficElementStrings

max_stars_repo_name: wayfinder/Wayfinder-Server

max_issues_repo_name: wayfinder/Wayfinder-Server

max_forks_repo_name: wayfinder/Wayfinder-Server


text:
/*! \file RenderViewer.inl
 *  \author Jared Hoberock
 *  \brief Inline file for RenderViewer.h.
 */

#include "RenderViewer.h"
#include "../renderers/MetropolisRenderer.h"
#include "../renderers/EnergyRedistributionRenderer.h"
#include "../records/GpuFilm.h"
#include "../records/GpuFilterFilm.h"

#include <boost/thread/thread.hpp>
using boost::thread;
using namespace boost;

RenderViewer
  ::RenderViewer(void)
    :Parent(),mDrawPreview(true),
     mExposure(0.0f),mGamma(1.0f),
     mDoTonemap(false),mMiddleGrey(0.5f)
{
  ;
} // end RenderViewer::RenderViewer()

void RenderViewer
  ::init(void)
{
  // first init the parent
  Parent::init();

  // no state file please
  setStateFileName(Parent::String(""));

  // init other stuff
  mTexture.create();

  // resize
  resize(512,512);

  shared_ptr<const RenderFilm> film = dynamic_pointer_cast<const RenderFilm,const Record>(mRenderer->getRecord());
  if(film.get() != 0)
  {
    resize(film->getWidth(), film->getHeight());
  } // end if
} // end RenderViewer::init()

void RenderViewer
  ::drawFilm(const shared_ptr<const RenderFilm> &f)
{
  // figure out which texture to use
  const glpp::Texture *texture = &mTexture;
  const GpuFilm<RenderFilm> *gpuFilm = dynamic_cast<const GpuFilm<RenderFilm> *>(f.get());
  if(gpuFilm != 0)
  {
    // XXX yuck fix this
    const_cast<GpuFilm<RenderFilm> *>(gpuFilm)->renderPendingDeposits();
    texture = &gpuFilm->mTexture;
  } // end if

  const float *data = reinterpret_cast<const float*>(&f->raster(0,0));
  GLenum datatype = GL_FLOAT_RGB16_NV;

  mTexture.init(datatype,
                width(), height(),
                0,
                GL_RGB, data);

  // choose which program to use
  Program &p = mDoTonemap ? mTexture2DRectTonemapProgram : mTexture2DRectGammaProgram;

  p.bind();

  // scale by 1/spp if we haven't finished the render
  float scale = 1.0f;
  if(mProgress.count() < mProgress.expected_count())
  {
    // XXX DESIGN kill this dynamic_cast somehow
    const MonteCarloRenderer *mc = dynamic_cast<const MonteCarloRenderer*>(mRenderer.get());
    if(mc)
    {
      float spp = mc->getNumSamples();
      spp /= (f->getWidth() * f->getHeight());
      scale = 1.0f / spp;
    } // end if
  } // end else

  p.setUniform1f("scale", powf(2.0f, mExposure) * scale);
  p.setUniform1f("gamma", mGamma);
  float meanLogL = f->getSumLogLuminance() / (f->getWidth() * f->getHeight());
  float Lwa = expf(meanLogL);
  p.setUniform1f("Lwa", Lwa);
  p.setUniform1f("Lwhite", f->getMaximumLuminance());
  p.setUniform1f("a", mMiddleGrey);

  printGLError(__FILE__, __LINE__);

  p.unbind();

  glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT);

  drawTexture(*texture, p);
  glPopAttrib();
} // end RenderViewer::draw()

void RenderViewer
  ::drawPhotons(const PhotonMap &photons)
{
  glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE);
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_LIGHTING);

  // scale by 1/spp if we haven't finished the render
  float scale = (width() * height());
  //if(mProgress.count() < mProgress.expected_count())
  {
    // XXX DESIGN kill this dynamic_cast somehow
    const MonteCarloRenderer *mc = dynamic_cast<const MonteCarloRenderer*>(mRenderer.get());
    if(mc)
    {
      scale /= mc->getNumSamples();
    } // end if
  } // end else

  mPassthroughGammaProgram.bind();
  mPassthroughGammaProgram.setUniform1f("scale", powf(2.0f, mExposure) * scale);
  mPassthroughGammaProgram.setUniform1f("gamma", mGamma);

  // draw dem photons
  glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
  glInterleavedArrays(GL_C3F_V3F, sizeof(Photon), &photons[0].mPower[0]);
  glDrawArrays(GL_POINTS, 0, photons.size());
  glPopClientAttrib();

  mPassthroughGammaProgram.unbind();

  glPopAttrib();
} // end RenderViewer::drawPhotons()

void RenderViewer
  ::draw(void)
{
  if(!mDrawPreview)
  {
    shared_ptr<const Record> rec = mRenderer->getRecord();

    shared_ptr<const RenderFilm> film = dynamic_pointer_cast<const RenderFilm,const Record>(rec);

    if(film.get())
    {
      // draw the film
      drawFilm(film);
    } // end if
    else
    {
      shared_ptr<const PhotonRecord> photons = dynamic_pointer_cast<const PhotonRecord, const Record>(rec);
      if(photons.get())
      {
        // draw the photons
        drawPhotons(*photons);
      } // end if
    } // end else
  } // end if
  else
  {
    drawScenePreview();
  } // end else
} // end RenderViewer::draw()

void RenderViewer
  ::drawScenePreview(void)
{
  Parent::draw();
} // end RenderViewer::drawScenePreview()

void RenderViewer
  ::keyPressEvent(KeyEvent *e)
{
  switch(e->key())
  {
    case 'R':
    {
      startRender();
      mDrawPreview = false;
      updateGL();
      break;
    } // end case Qt::Key_R

    case 'P':
    {
      mDrawPreview = !mDrawPreview;
      updateGL();
      break;
    } // end case Qt::Key_P

    case '(':
    {
      setGamma(std::max(mGamma - 0.1f, 0.1f));

      char msg[32];
      sprintf(msg, "Gamma: %f", mGamma);
      displayMessage(msg);
      updateGL();
      break;
    } // end case (

    case ')':
    {
      setGamma(mGamma + 0.1f);

      char msg[32];
      sprintf(msg, "Gamma: %f", mGamma);
      displayMessage(msg);
      updateGL();
      break;
    } // end case )

    case '{':
    {
      char msg[32];
      if(mDoTonemap)
      {
        mMiddleGrey -= 1.0f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        setExposure(mExposure - 1.0f);

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case '{'

    case '[':
    {
      char msg[32];
      if(mDoTonemap)
      {
        mMiddleGrey -= 0.01f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        setExposure(mExposure - 0.1f);

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case '['

    case '}':
    {
      char msg[32];

      if(mDoTonemap)
      {
        mMiddleGrey += 1.0f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        setExposure(mExposure + 1.0f);

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case '}'

    case ']':
    {
      char msg[32];

      if(mDoTonemap)
      {
        mMiddleGrey += 0.01f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        setExposure(mExposure + 0.1f);

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case ']'

    case 'T':
    {
      mDoTonemap = !mDoTonemap;
      updateGL();
      break;
    } // end case 'T'

    default:
    {
      Parent::keyPressEvent(e);
      break;
    } // end default
  } // end switch
} // end RenderViewer::keyPressEvent()

void RenderViewer
  ::resizeGL(int w, int h)
{
  Parent::resizeGL(w,h);

  char buffer[32];
  sprintf(buffer, "%d", width());
  std::string message = buffer;
  message += "x";
  sprintf(buffer, "%d", height());
  message += buffer;

  displayMessage(message);
  updateGL();
} // end RenderViewer::resizeGL()

class RenderThunk
{
  public:

  inline RenderThunk(Renderer *renderer,
                     Renderer::ProgressCallback *progress)
    :mRenderer(renderer),mProgress(progress)
  {
    ;
  }

  inline virtual ~RenderThunk(void){;};

  virtual void run(void)
  {
    (*this)();
  }

  void operator()(void)
  {
    mRenderer->render(*mProgress);
  }

  Renderer *mRenderer;
  Renderer::ProgressCallback *mProgress;
};

void RenderViewer
  ::setRenderer(shared_ptr<Renderer> r)
{
  mRenderer = r;

  shared_ptr<const Record> rec = mRenderer->getRecord();
  const RandomAccessFilm *image = dynamic_cast<const RandomAccessFilm*>(rec.get());
  if(image != 0)
  {
    resizeGL(image->getWidth(), image->getHeight());
  } // end if
} // end Renderer::setRenderer()

void RenderViewer
  ::startRender(void)
{
  // XXX make RenderThunk refer to a shared_ptr
  RenderThunk render = RenderThunk(mRenderer.get(), &mProgress);
  boost::thread renderThread(render);

  // update the visualization every second
  setAnimationPeriod(1000);

  // update the frame automatically
  startAnimation();
} // end RenderViewer::startRender()

void RenderViewer
  ::setExposure(float e)
{
  mExposure = e;
} // end RenderViewer::setExposure()

void RenderViewer
  ::setGamma(const float g)
{
  mGamma = g;
} // end RenderViewer::setGamma()

float RenderViewer
  ::getGamma(void) const
{
  return mGamma;
} // end RenderViewer::getGamma()

ext: inl

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
///////////////////////////////////////////////////////////////////////////////
//
// http://github.com/breese/aware
//
// Copyright (C) 2016 Bjorn Reese <breese@users.sourceforge.net>
//
// 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)
//
///////////////////////////////////////////////////////////////////////////////

#include <boost/bind.hpp>
#include <aware/bonjour/detail/throw_on_error.hpp>
#include <aware/bonjour/detail/service.hpp>
#include "dns_sd.hpp"

namespace aware
{
namespace bonjour
{
namespace detail
{

boost::asio::io_service::id service::id;

service::service(boost::asio::io_service& io)
    : boost::asio::io_service::service(io),
      connection(detail::handle::with_connection)
{
}

detail::handle& service::get_connection()
{
    return connection;
}

} // namespace detail
} // namespace bonjour
} // namespace aware


text:
//  (C) Copyright John Maddock 2005.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// Verify that the headers can be included, even if their contents
// aren't neccessarily usable by broken compilers.

#ifdef TEST_STD_HEADERS

#include <memory>
#include <array>
#include <complex>
#include <functional>
#include <random>
#include <regex>
#include <tuple>
#include <utility>
#include <type_traits>

#else

#include <boost/tr1/array.hpp>
#include <boost/tr1/complex.hpp>
#include <boost/tr1/functional.hpp>
#include <boost/tr1/memory.hpp>
#include <boost/tr1/random.hpp>
#include <boost/tr1/regex.hpp>
#include <boost/tr1/tuple.hpp>
#include <boost/tr1/type_traits.hpp>
#include <boost/tr1/utility.hpp>

#endif

max_stars_repo_name: lijgame/boost