<commit_before>#include "dataraptor.h"
#include "routing.h"
namespace navitia { namespace routing { namespace raptor {

void dataRAPTOR::load(const type::PT_Data &data)
{
    retour_constant.resize(data.route_points.size());
    retour_constant_reverse.resize(data.route_points.size());

    for(auto &r : retour_constant_reverse) {
        r.arrival = DateTime::min;
        r.departure = DateTime::min;
    }

    for(auto &r : retour_constant) {
        r.arrival = DateTime::inf;
        r.departure = DateTime::inf;
    }

    foot_path.clear();
    std::vector<list_connections> footpath_temp;
    footpath_temp.resize(data.route_points.size());

    //Construction des connexions entre routepoints
    //(sert pour les prolongements de service ainsi que les correpondances garanties
    for(type::RoutePointConnection rpc : data.route_point_connections) {
        footpath_rp_forward.insert(std::make_pair(rpc.departure_route_point_idx, rpc));
        footpath_rp_backward.insert(std::make_pair(rpc.destination_route_point_idx, rpc));
    }

    //Construction de la liste des marche à pied à partir des connexions renseignées
    for(type::Connection connection : data.connections) {
        footpath_temp[connection.departure_stop_point_idx][connection.destination_stop_point_idx] = connection;
    }

    for(type::Connection connection : data.connections) {
        if(footpath_temp[connection.destination_stop_point_idx].find(connection.departure_stop_point_idx) ==
           footpath_temp[connection.destination_stop_point_idx].end() ) {

            type::Connection inverse;
            inverse.duration = connection.duration;
            inverse.departure_stop_point_idx = connection.destination_stop_point_idx;
            inverse.destination_stop_point_idx = connection.departure_stop_point_idx;
            footpath_temp[inverse.departure_stop_point_idx][inverse.destination_stop_point_idx] = inverse;
        }
    }

    //On rajoute des connexions entre les stops points d'un même stop area si elles n'existent pas
    footpath_index.resize(data.stop_points.size());
    footpath_index.resize(data.stop_points.size());
    for(type::StopPoint sp : data.stop_points) {
        type::StopArea sa = data.stop_areas[sp.stop_area_idx];
        footpath_index[sp.idx].first = foot_path.size();

        int size = 0;
        for(auto conn : footpath_temp[sp.idx]) {
            foot_path.push_back(conn.second);
            ++size;
        }

        for(type::idx_t spidx2 : sa.stop_point_list) {
            if(sp.idx != spidx2 &&
                footpath_temp[sp.idx].find(spidx2) == footpath_temp[sp.idx].end()) {
                type::Connection c;
                c.departure_stop_point_idx = sp.idx;
                c.destination_stop_point_idx = spidx2;
                c.duration = 2 * 60;
                foot_path.push_back(c);
                ++size;
            }
        }
        footpath_index[sp.idx].second = size;
    }

    typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx;
    idx_vector_idx ridx_route;

    arrival_times.clear();
    departure_times.clear();
    st_idx_forward.clear();
    st_idx_backward.clear();
    first_stop_time.clear();
    vp_idx_forward.clear();
    vp_idx_backward.clear();

    //On recopie les validity patterns
    for(auto vp : data.validity_patterns)
        validity_patterns.push_back(vp.days);

    for(const type::Route & route : data.routes) {
        first_stop_time.push_back(arrival_times.size());
        nb_trips.push_back(route.vehicle_journey_list.size());
        for(unsigned int i=0; i < route.route_point_list.size(); ++i) {
            std::vector<type::idx_t> vec_stdix;
            for(type::idx_t vjidx : route.vehicle_journey_list) {
                vec_stdix.push_back(data.vehicle_journeys[vjidx].stop_time_list[i]);
            }
            std::sort(vec_stdix.begin(), vec_stdix.end(),
                      [&](type::idx_t stidx1, type::idx_t stidx2)->bool{
                        const type::StopTime & st1 = data.stop_times[stidx1];
                        const type::StopTime & st2 = data.stop_times[stidx2];
                        return (st1.departure_time % SECONDS_PER_DAY == st2.departure_time % SECONDS_PER_DAY && stidx1 < stidx2) ||
                               (st1.departure_time % SECONDS_PER_DAY <  st2.departure_time % SECONDS_PER_DAY);});
            ///Suppresion des montées interdites
            //std::remove_if(vec_stdix.begin(), vec_stdix.end(), [&](type::idx_t &st){return !data.stop_times[st].pick_up_allowed();});
            st_idx_forward.insert(st_idx_forward.end(), vec_stdix.begin(), vec_stdix.end());

            for(auto stidx : vec_stdix) {
                const auto & st = data.stop_times[stidx];
                departure_times.push_back(st.departure_time % SECONDS_PER_DAY);
                if(st.departure_time > SECONDS_PER_DAY) {
                    auto vp = data.validity_patterns[data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx].days;
                    vp >>=1;
                    auto it = std::find(validity_patterns.begin(), validity_patterns.end(), vp);
                    if(it == validity_patterns.end()) {
                        vp_idx_forward.push_back(validity_patterns.size());
                        validity_patterns.push_back(vp);
                    } else {
                        vp_idx_forward.push_back(it - validity_patterns.begin());
                    }
                } else {
                    vp_idx_forward.push_back(data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx);
                }
            }

            std::sort(vec_stdix.begin(), vec_stdix.end(),
                  [&](type::idx_t stidx1, type::idx_t stidx2)->bool{
                        const type::StopTime & st1 = data.stop_times[stidx1];
                        const type::StopTime & st2 = data.stop_times[stidx2];
                        return (st1.arrival_time % SECONDS_PER_DAY == st2.arrival_time % SECONDS_PER_DAY && stidx1 > stidx2) ||
                               (st1.arrival_time % SECONDS_PER_DAY >  st2.arrival_time % SECONDS_PER_DAY);});
            ///Suppresion des descentes interdites
            //std::remove_if(vec_stdix.begin(), vec_stdix.end(), [&](type::idx_t &st){return !data.stop_times[st].drop_off_allowed();});

            st_idx_backward.insert(st_idx_backward.end(), vec_stdix.begin(), vec_stdix.end());
            for(auto stidx : vec_stdix) {
                const auto & st = data.stop_times[stidx];
                arrival_times.push_back(st.arrival_time % SECONDS_PER_DAY);
                if(st.arrival_time > SECONDS_PER_DAY) {
                    auto vp = data.validity_patterns[data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx].days;
                    vp >>=1;;
                    auto it = std::find(validity_patterns.begin(), validity_patterns.end(), vp);
                    if(it == validity_patterns.end()) {
                        vp_idx_backward.push_back(validity_patterns.size());
                        validity_patterns.push_back(vp);
                    } else {
                        vp_idx_backward.push_back(it - validity_patterns.begin());
                    }
                } else {
                    vp_idx_backward.push_back(data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx);
                }
            }

        }
    }

     std::cout << "Nb data stop times : " << data.stop_times.size() << " stopTimes : " << arrival_times.size()
               << " nb foot path : " << foot_path.size() << " Nombre de stop points : " << data.stop_points.size() << "nb vp : " << data.validity_patterns.size() <<  std::endl;

}

                  }}}
<commit_msg>dataraptor : Vérification de l'appartenance d'un stop point à un stop area lors de la construction des footpath<commit_after>#include "dataraptor.h"
#include "routing.h"
namespace navitia { namespace routing { namespace raptor {

void dataRAPTOR::load(const type::PT_Data &data)
{
    retour_constant.resize(data.route_points.size());
    retour_constant_reverse.resize(data.route_points.size());

    for(auto &r : retour_constant_reverse) {
        r.arrival = DateTime::min;
        r.departure = DateTime::min;
    }

    for(auto &r : retour_constant) {
        r.arrival = DateTime::inf;
        r.departure = DateTime::inf;
    }

    foot_path.clear();
    std::vector<list_connections> footpath_temp;
    footpath_temp.resize(data.route_points.size());

    //Construction des connexions entre routepoints
    //(sert pour les prolongements de service ainsi que les correpondances garanties
    for(type::RoutePointConnection rpc : data.route_point_connections) {
        footpath_rp_forward.insert(std::make_pair(rpc.departure_route_point_idx, rpc));
        footpath_rp_backward.insert(std::make_pair(rpc.destination_route_point_idx, rpc));
    }

    //Construction de la liste des marche à pied à partir des connexions renseignées
    for(type::Connection connection : data.connections) {
        footpath_temp[connection.departure_stop_point_idx][connection.destination_stop_point_idx] = connection;
    }

    for(type::Connection connection : data.connections) {
        if(footpath_temp[connection.destination_stop_point_idx].find(connection.departure_stop_point_idx) ==
           footpath_temp[connection.destination_stop_point_idx].end() ) {

            type::Connection inverse;
            inverse.duration = connection.duration;
            inverse.departure_stop_point_idx = connection.destination_stop_point_idx;
            inverse.destination_stop_point_idx = connection.departure_stop_point_idx;
            footpath_temp[inverse.departure_stop_point_idx][inverse.destination_stop_point_idx] = inverse;
        }
    }

    //On rajoute des connexions entre les stops points d'un même stop area si elles n'existent pas
    footpath_index.resize(data.stop_points.size());
    footpath_index.resize(data.stop_points.size());
    for(type::StopPoint sp : data.stop_points) {
        if(sp.stop_area_idx != type::invalid_idx) {
            type::StopArea sa = data.stop_areas[sp.stop_area_idx];
            footpath_index[sp.idx].first = foot_path.size();

            int size = 0;
            for(auto conn : footpath_temp[sp.idx]) {
                foot_path.push_back(conn.second);
                ++size;
            }

            for(type::idx_t spidx2 : sa.stop_point_list) {
                if(sp.idx != spidx2 &&
                    footpath_temp[sp.idx].find(spidx2) == footpath_temp[sp.idx].end()) {
                    type::Connection c;
                    c.departure_stop_point_idx = sp.idx;
                    c.destination_stop_point_idx = spidx2;
                    c.duration = 2 * 60;
                    foot_path.push_back(c);
                    ++size;
                }
            }
            footpath_index[sp.idx].second = size;
        }
    }

    typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx;
    idx_vector_idx ridx_route;

    arrival_times.clear();
    departure_times.clear();
    st_idx_forward.clear();
    st_idx_backward.clear();
    first_stop_time.clear();
    vp_idx_forward.clear();
    vp_idx_backward.clear();

    //On recopie les validity patterns
    for(auto vp : data.validity_patterns)
        validity_patterns.push_back(vp.days);

    for(const type::Route & route : data.routes) {
        first_stop_time.push_back(arrival_times.size());
        nb_trips.push_back(route.vehicle_journey_list.size());
        for(unsigned int i=0; i < route.route_point_list.size(); ++i) {
            std::vector<type::idx_t> vec_stdix;
            for(type::idx_t vjidx : route.vehicle_journey_list) {
                vec_stdix.push_back(data.vehicle_journeys[vjidx].stop_time_list[i]);
            }
            std::sort(vec_stdix.begin(), vec_stdix.end(),
                      [&](type::idx_t stidx1, type::idx_t stidx2)->bool{
                        const type::StopTime & st1 = data.stop_times[stidx1];
                        const type::StopTime & st2 = data.stop_times[stidx2];
                        return (st1.departure_time % SECONDS_PER_DAY == st2.departure_time % SECONDS_PER_DAY && stidx1 < stidx2) ||
                               (st1.departure_time % SECONDS_PER_DAY <  st2.departure_time % SECONDS_PER_DAY);});
            ///Suppresion des montées interdites
            //std::remove_if(vec_stdix.begin(), vec_stdix.end(), [&](type::idx_t &st){return !data.stop_times[st].pick_up_allowed();});
            st_idx_forward.insert(st_idx_forward.end(), vec_stdix.begin(), vec_stdix.end());

            for(auto stidx : vec_stdix) {
                const auto & st = data.stop_times[stidx];
                departure_times.push_back(st.departure_time % SECONDS_PER_DAY);
                if(st.departure_time > SECONDS_PER_DAY) {
                    auto vp = data.validity_patterns[data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx].days;
                    vp >>=1;
                    auto it = std::find(validity_patterns.begin(), validity_patterns.end(), vp);
                    if(it == validity_patterns.end()) {
                        vp_idx_forward.push_back(validity_patterns.size());
                        validity_patterns.push_back(vp);
                    } else {
                        vp_idx_forward.push_back(it - validity_patterns.begin());
                    }
                } else {
                    vp_idx_forward.push_back(data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx);
                }
            }

            std::sort(vec_stdix.begin(), vec_stdix.end(),
                  [&](type::idx_t stidx1, type::idx_t stidx2)->bool{
                        const type::StopTime & st1 = data.stop_times[stidx1];
                        const type::StopTime & st2 = data.stop_times[stidx2];
                        return (st1.arrival_time % SECONDS_PER_DAY == st2.arrival_time % SECONDS_PER_DAY && stidx1 > stidx2) ||
                               (st1.arrival_time % SECONDS_PER_DAY >  st2.arrival_time % SECONDS_PER_DAY);});
            ///Suppresion des descentes interdites
            //std::remove_if(vec_stdix.begin(), vec_stdix.end(), [&](type::idx_t &st){return !data.stop_times[st].drop_off_allowed();});

            st_idx_backward.insert(st_idx_backward.end(), vec_stdix.begin(), vec_stdix.end());
            for(auto stidx : vec_stdix) {
                const auto & st = data.stop_times[stidx];
                arrival_times.push_back(st.arrival_time % SECONDS_PER_DAY);
                if(st.arrival_time > SECONDS_PER_DAY) {
                    auto vp = data.validity_patterns[data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx].days;
                    vp >>=1;;
                    auto it = std::find(validity_patterns.begin(), validity_patterns.end(), vp);
                    if(it == validity_patterns.end()) {
                        vp_idx_backward.push_back(validity_patterns.size());
                        validity_patterns.push_back(vp);
                    } else {
                        vp_idx_backward.push_back(it - validity_patterns.begin());
                    }
                } else {
                    vp_idx_backward.push_back(data.vehicle_journeys[st.vehicle_journey_idx].validity_pattern_idx);
                }
            }

        }
    }

     std::cout << "Nb data stop times : " << data.stop_times.size() << " stopTimes : " << arrival_times.size()
               << " nb foot path : " << foot_path.size() << " Nombre de stop points : " << data.stop_points.size() << "nb vp : " << data.validity_patterns.size() <<  std::endl;

}

                  }}}
<|endoftext|>


<commit_before>
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include "Application.h"

#include <memory>

#include <gloperate-qtapplication/Viewer.h>

int main(int argc, char * argv[])
{
    Application app(argc, argv);

    std::unique_ptr<gloperate_qtapplication::Viewer> viewer(new gloperate_qtapplication::Viewer()); // make_unique is C++14
    viewer->show();

    return app.exec();
}
<commit_msg>Use dark theme in cgwhite<commit_after>
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include "Application.h"

#include <memory>

#include <gloperate-qtapplication/Viewer.h>

#include <widgetzeug/dark_fusion_style.hpp>

int main(int argc, char * argv[])
{
    Application app(argc, argv);

    widgetzeug::enableDarkFusionStyle();

    std::unique_ptr<gloperate_qtapplication::Viewer> viewer(new gloperate_qtapplication::Viewer()); // make_unique is C++14
    viewer->show();

    return app.exec();
}
<|endoftext|>


<commit_before>#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH

#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/common/memory.hh>
#include <dune/xt/grid/boundaryinfo.hh>
#include <dune/xt/grid/layers.hh>
#include <dune/xt/grid/gridprovider.hh>
#include <dune/xt/grid/view/subdomain/part.hh>
#include <dune/xt/la/container.hh>

#include <dune/gdt/assembler/boundary.hh>
#include <dune/gdt/assembler/coupling.hh>
#include <dune/gdt/playground/spaces/block.hh>
#include <dune/gdt/local/integrands/elliptic-ipdg.hh>
#include <dune/gdt/local/functionals/integrals.hh>
#include <dune/gdt/local/operators/integrals.hh>

#include "../problems/base.hh"
#include "base.hh"
#include "ipdg.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

/**
 * \todo add pattern() to StationaryContainerBasedDefaultDiscretization, avoid computation of local_pattern below
 */
template <class GridType,
          ChooseSpaceBackend spacebackend = ChooseSpaceBackend::fem, // we only have local grid parts atm
          XT::LA::Backends la = XT::LA::default_sparse_backend,
          int pol = 1,
          class RangeFieldType = double,
          size_t dimRange = 1,
          LocalEllipticIpdgIntegrands::Method local_method = LocalEllipticIpdgIntegrands::default_method,
          LocalEllipticIpdgIntegrands::Method coupling_method = LocalEllipticIpdgIntegrands::default_method>
class BlockIpdgDiscretizer
{
  typedef IpdgDiscretizer<GridType,
                          XT::Grid::Layers::dd_subdomain,
                          spacebackend,
                          la,
                          pol,
                          RangeFieldType,
                          dimRange,
                          local_method>
      LocalDiscretizer;
  typedef typename LocalDiscretizer::DiscretizationType LocalDiscretizationType;
  typedef typename LocalDiscretizer::SpaceType LocalSpaceType;

public:
  typedef typename LocalDiscretizer::ProblemType ProblemType;
  typedef BlockSpace<LocalSpaceType> SpaceType;
  typedef typename LocalDiscretizer::MatrixType MatrixType;
  typedef typename LocalDiscretizer::VectorType VectorType;
  typedef StationaryContainerBasedDefaultDiscretization<ProblemType, SpaceType, MatrixType, VectorType, SpaceType>
      DiscretizationType;
  static const constexpr ChooseDiscretizer type = ChooseDiscretizer::block_ipdg;
  static const constexpr XT::LA::Backends la_backend = la;
  static const int polOrder = pol;

  static std::string static_id()
  {
    return std::string("gdt.linearelliptic.discretization.block-ipdg.order_")
           + Dune::XT::Common::to_string(int(polOrder)); // int() needed, otherwise we get a linker error
  }

  static DiscretizationType
  discretize(XT::Grid::GridProvider<GridType, XT::Grid::DD::SubdomainGrid<GridType>>& grid_provider,
             const ProblemType& problem,
             const int /*level*/ = 0,
             const size_t inner_boundary_index = std::numeric_limits<size_t>::max() - 42)
  {
    auto logger = XT::Common::TimedLogger().get(static_id());
    const auto& dd_grid = grid_provider.dd_grid();
    logger.info() << "Creating " << dd_grid.size() << " local discretizations... " << std::endl;
    XT::Common::Configuration local_boundary_cfg;
    local_boundary_cfg["type"] = "xt.grid.boundaryinfo.boundarysegment";
    local_boundary_cfg["default"] = "dirichlet";
    local_boundary_cfg["neumann"] =
        "[" + XT::Common::to_string(inner_boundary_index) + " " + XT::Common::to_string(inner_boundary_index + 1) + "]";
    LinearElliptic::ProblemBase<typename GridType::template Codim<0>::Entity,
                                typename GridType::ctype,
                                GridType::dimension,
                                typename SpaceType::RangeFieldType,
                                1>
        local_problem(problem.diffusion_factor(),
                      problem.diffusion_tensor(),
                      problem.force(),
                      problem.dirichlet(),
                      problem.neumann(),
                      XT::Common::Configuration(),
                      local_boundary_cfg);
    std::vector<LocalDiscretizationType> local_discretizations;
    std::vector<LocalSpaceType> local_spaces;
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      local_discretizations.emplace_back(
          LocalDiscretizer::discretize(grid_provider, local_problem, boost::numeric_cast<int>(ss)));
      local_spaces.emplace_back(local_discretizations.back().test_space());
    }
    logger.info() << "Creating space... " << std::endl;
    SpaceType space(dd_grid, std::move(local_spaces));

    logger.info() << "Preparing container..." << std::endl;
    std::vector<XT::LA::SparsityPatternDefault> local_patterns(dd_grid.size());
    std::vector<std::map<size_t, XT::LA::SparsityPatternDefault>> inside_outside_patterns(dd_grid.size());
    std::vector<std::map<size_t, XT::LA::SparsityPatternDefault>> outside_inside_patterns(dd_grid.size());
    std::map<size_t, XT::LA::SparsityPatternDefault> boundary_patterns;
    XT::LA::SparsityPatternDefault pattern(space.mapper().size());
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      local_patterns[ss] = local_spaces[ss].compute_face_and_volume_pattern(); // todo: from the local discretization
      copy_local_to_global(local_patterns[ss], space, ss, ss, pattern);
      if (dd_grid.boundary(ss)) {
        // in general, this can differ from the local one (think of CG)
        boundary_patterns[ss] = local_spaces[ss].compute_face_pattern(dd_grid.boundaryGridPart(ss));
        copy_local_to_global(boundary_patterns[ss], space, ss, ss, pattern);
      }
      for (auto&& nn : dd_grid.neighborsOf(ss)) {
        if (ss < nn) { //  each coupling only once
          inside_outside_patterns[ss][nn] =
              local_spaces[ss].compute_face_pattern(dd_grid.couplingGridPart(ss, nn), local_spaces[nn]);
          copy_local_to_global(inside_outside_patterns[ss][nn], space, ss, nn, pattern);
          outside_inside_patterns[nn][ss] =
              local_spaces[nn].compute_face_pattern(dd_grid.couplingGridPart(nn, ss), local_spaces[ss]);
          copy_local_to_global(outside_inside_patterns[nn][ss], space, nn, ss, pattern);
        }
      }
    }
    pattern.sort();
    MatrixType system_matrix(space.mapper().size(), space.mapper().size(), pattern);
    VectorType rhs_vector(space.mapper().size());
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      copy_local_to_global(local_discretizations[ss].system_matrix(), local_patterns[ss], space, ss, ss, system_matrix);
      copy_local_to_global(local_discretizations[ss].rhs_vector(), space, ss, rhs_vector);
    }

    logger.info() << "Assembling coupling contributions..." << std::endl;
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      for (auto&& nn : dd_grid.neighborsOf(ss)) {
        if (ss < nn) { //  each coupling only once
          MatrixType inside_inside_matrix(
              local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), local_patterns[ss]);
          MatrixType outside_outside_matrix(
              local_spaces[nn].mapper().size(), local_spaces[nn].mapper().size(), local_patterns[nn]);
          MatrixType inside_outside_matrix(
              local_spaces[ss].mapper().size(), local_spaces[nn].mapper().size(), inside_outside_patterns[ss][nn]);
          MatrixType outside_inside_matrix(
              local_spaces[nn].mapper().size(), local_spaces[ss].mapper().size(), outside_inside_patterns[nn][ss]);
          auto coupling_grid_part = dd_grid.couplingGridPart(ss, nn);
          // put all of this into a coupling operator
          CouplingAssembler<LocalSpaceType, decltype(coupling_grid_part)> coupling_assembler(
              coupling_grid_part, local_spaces[ss], local_spaces[ss], local_spaces[nn], local_spaces[nn]);
          typedef LocalEllipticIpdgIntegrands::Inner<typename ProblemType::DiffusionFactorType,
                                                     typename ProblemType::DiffusionTensorType,
                                                     coupling_method>
              CouplingIntegrandType;
          LocalCouplingIntegralOperator<CouplingIntegrandType> local_coupling_operator(problem.diffusion_factor(),
                                                                                problem.diffusion_tensor());
          LocalCouplingTwoFormAssembler<LocalCouplingIntegralOperator<CouplingIntegrandType>> local_coupling_assembler(
              local_coupling_operator);
          coupling_assembler.append(local_coupling_assembler,
                                    inside_inside_matrix,
                                    outside_outside_matrix,
                                    inside_outside_matrix,
                                    outside_inside_matrix);
          coupling_assembler.assemble();
          copy_local_to_global(inside_inside_matrix, local_patterns[ss], space, ss, ss, system_matrix);
          copy_local_to_global(outside_outside_matrix, local_patterns[nn], space, nn, nn, system_matrix);
          copy_local_to_global(inside_outside_matrix, inside_outside_patterns[ss][nn], space, ss, nn, system_matrix);
          copy_local_to_global(outside_inside_matrix, outside_inside_patterns[nn][ss], space, nn, ss, system_matrix);
        }
      }
    }

    logger.info() << "Assembling boundary contributions..." << std::endl;
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      if (dd_grid.boundary(ss)) {
        auto boundary_grid_part = dd_grid.boundaryGridPart(ss);
        auto boundary_pattern = local_spaces[ss].compute_face_and_volume_pattern(boundary_grid_part);
        MatrixType boundary_matrix(
            local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), boundary_pattern);
        VectorType boundary_vector(local_spaces[ss].mapper().size());
        BoundaryAssembler<LocalSpaceType, decltype(boundary_grid_part)> boundary_assembler(
            boundary_grid_part, local_spaces[ss], local_spaces[ss]);
        auto boundary_info =
            XT::Grid::BoundaryInfoFactory<typename decltype(boundary_grid_part)::IntersectionType>::create(
                problem.boundary_info_cfg());
        typedef LocalEllipticIpdgIntegrands::BoundaryLHS<typename ProblemType::DiffusionFactorType,
                                                         typename ProblemType::DiffusionTensorType,
                                                         coupling_method>
            BoundaryLhsIntegrandType;
        LocalBoundaryIntegralOperator<BoundaryLhsIntegrandType> local_boundary_operator(problem.diffusion_factor(),
                                                                                problem.diffusion_tensor());
        LocalBoundaryTwoFormAssembler<LocalBoundaryIntegralOperator<BoundaryLhsIntegrandType>>
            local_boundary_operator_assembler(local_boundary_operator);
        boundary_assembler.append(
            local_boundary_operator_assembler,
            boundary_matrix,
            new XT::Grid::ApplyOn::DirichletIntersections<decltype(boundary_grid_part)>(*boundary_info));
        typedef LocalEllipticIpdgIntegrands::BoundaryRHS<typename ProblemType::FunctionType,
                                                         typename ProblemType::DiffusionFactorType,
                                                         typename ProblemType::DiffusionTensorType,
                                                         coupling_method>
            BoundaryRhsIntegrandType;
        LocalFaceIntegralFunctional<BoundaryRhsIntegrandType> local_boundary_functional(
            problem.dirichlet(), problem.diffusion_factor(), problem.diffusion_tensor());
        LocalFaceFunctionalAssembler<LocalFaceIntegralFunctional<BoundaryRhsIntegrandType>>
            local_boundary_functional_assembler(local_boundary_functional);
        boundary_assembler.append(
            local_boundary_functional_assembler,
            boundary_vector,
            new XT::Grid::ApplyOn::DirichletIntersections<decltype(boundary_grid_part)>(*boundary_info));
        boundary_assembler.assemble();
        copy_local_to_global(boundary_matrix, boundary_pattern, space, ss, ss, system_matrix);
        copy_local_to_global(boundary_vector, space, ss, rhs_vector);
      }
    }

    // create the discretization (no copy of the containers done here, bc. of cow)
    return DiscretizationType(problem, space, system_matrix, rhs_vector);
  } // ... discretize(...)

private:
  static void copy_local_to_global(const XT::LA::SparsityPatternDefault& local_pattern,
                                   const SpaceType& space,
                                   const size_t test_subdomain,
                                   const size_t ansatz_subdomain,
                                   XT::LA::SparsityPatternDefault& global_pattern)
  {
    const auto& mapper = space.mapper();
    for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {
      const size_t global_ii = mapper.mapToGlobal(test_subdomain, local_ii);
      const auto& local_rows = local_pattern.inner(local_ii);
      for (const auto& local_jj : local_rows) {
        const size_t global_jj = mapper.mapToGlobal(ansatz_subdomain, local_jj);
        global_pattern.insert(global_ii, global_jj);
      }
    }
  } // ... copy_local_to_global(...)

  static void copy_local_to_global(const MatrixType& local_matrix,
                                   const XT::LA::SparsityPatternDefault& local_pattern,
                                   const SpaceType& space,
                                   const size_t test_subdomain,
                                   const size_t ansatz_subdomain,
                                   MatrixType& global_matrix)
  {
    for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {
      const size_t global_ii = space.mapper().mapToGlobal(test_subdomain, local_ii);
      for (const size_t& local_jj : local_pattern.inner(local_ii)) {
        const size_t global_jj = space.mapper().mapToGlobal(ansatz_subdomain, local_jj);
        global_matrix.add_to_entry(global_ii, global_jj, local_matrix.get_entry(local_ii, local_jj));
      }
    }
  } // ... copy_local_to_global_matrix(...)

  static void copy_local_to_global(const VectorType& local_vector,
                                   const SpaceType& space,
                                   const size_t subdomain,
                                   VectorType& global_vector)
  {
    for (size_t local_ii = 0; local_ii < local_vector.size(); ++local_ii) {
      const size_t global_ii = space.mapper().mapToGlobal(subdomain, local_ii);
      global_vector.add_to_entry(global_ii, local_vector.get_entry(local_ii));
    }
  } // ... copy_local_to_global_matrix(...)
}; // class BlockIpdgDiscretizer

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH
<commit_msg>[test.linearelliptic.block-ipdg] update memory management<commit_after>#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH

#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/common/memory.hh>
#include <dune/xt/grid/boundaryinfo.hh>
#include <dune/xt/grid/layers.hh>
#include <dune/xt/grid/gridprovider.hh>
#include <dune/xt/grid/view/subdomain/part.hh>
#include <dune/xt/la/container.hh>

#include <dune/gdt/assembler/boundary.hh>
#include <dune/gdt/assembler/coupling.hh>
#include <dune/gdt/playground/spaces/block.hh>
#include <dune/gdt/local/integrands/elliptic-ipdg.hh>
#include <dune/gdt/local/functionals/integrals.hh>
#include <dune/gdt/local/operators/integrals.hh>

#include "../problems/base.hh"
#include "base.hh"
#include "ipdg.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

/**
 * \todo add pattern() to StationaryContainerBasedDefaultDiscretization, avoid computation of local_pattern below
 */
template <class GridType,
          ChooseSpaceBackend spacebackend = ChooseSpaceBackend::fem, // we only have local grid parts atm
          XT::LA::Backends la = XT::LA::default_sparse_backend,
          int pol = 1,
          class RangeFieldType = double,
          size_t dimRange = 1,
          LocalEllipticIpdgIntegrands::Method local_method = LocalEllipticIpdgIntegrands::default_method,
          LocalEllipticIpdgIntegrands::Method coupling_method = LocalEllipticIpdgIntegrands::default_method>
class BlockIpdgDiscretizer
{
  typedef IpdgDiscretizer<GridType,
                          XT::Grid::Layers::dd_subdomain,
                          spacebackend,
                          la,
                          pol,
                          RangeFieldType,
                          dimRange,
                          local_method>
      LocalDiscretizer;
  typedef typename LocalDiscretizer::DiscretizationType LocalDiscretizationType;
  typedef typename LocalDiscretizer::SpaceType LocalSpaceType;

public:
  typedef typename LocalDiscretizer::ProblemType ProblemType;
  typedef BlockSpace<LocalSpaceType> SpaceType;
  typedef typename LocalDiscretizer::MatrixType MatrixType;
  typedef typename LocalDiscretizer::VectorType VectorType;
  typedef StationaryContainerBasedDefaultDiscretization<ProblemType, SpaceType, MatrixType, VectorType, SpaceType>
      DiscretizationType;
  static const constexpr ChooseDiscretizer type = ChooseDiscretizer::block_ipdg;
  static const constexpr XT::LA::Backends la_backend = la;
  static const int polOrder = pol;

  static std::string static_id()
  {
    return std::string("gdt.linearelliptic.discretization.block-ipdg.order_")
           + Dune::XT::Common::to_string(int(polOrder)); // int() needed, otherwise we get a linker error
  }

  static DiscretizationType
  discretize(XT::Grid::GridProvider<GridType, XT::Grid::DD::SubdomainGrid<GridType>>& grid_provider,
             const ProblemType& problem,
             const int /*level*/ = 0,
             const size_t inner_boundary_index = std::numeric_limits<size_t>::max() - 42)
  {
    auto logger = XT::Common::TimedLogger().get(static_id());
    const auto& dd_grid = grid_provider.dd_grid();
    logger.info() << "Creating " << dd_grid.size() << " local discretizations... " << std::endl;
    XT::Common::Configuration local_boundary_cfg;
    local_boundary_cfg["type"] = "xt.grid.boundaryinfo.boundarysegment";
    local_boundary_cfg["default"] = "dirichlet";
    local_boundary_cfg["neumann"] =
        "[" + XT::Common::to_string(inner_boundary_index) + " " + XT::Common::to_string(inner_boundary_index + 1) + "]";
    LinearElliptic::ProblemBase<typename GridType::template Codim<0>::Entity,
                                typename GridType::ctype,
                                GridType::dimension,
                                typename SpaceType::RangeFieldType,
                                1>
        local_problem(problem.diffusion_factor(),
                      problem.diffusion_tensor(),
                      problem.force(),
                      problem.dirichlet(),
                      problem.neumann(),
                      XT::Common::Configuration(),
                      local_boundary_cfg);
    std::vector<LocalDiscretizationType> local_discretizations;
    auto local_spaces_ptr = std::make_shared<std::vector<LocalSpaceType>>();
    auto& local_spaces = *local_spaces_ptr;
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      local_discretizations.emplace_back(
          LocalDiscretizer::discretize(grid_provider, local_problem, boost::numeric_cast<int>(ss)));
      local_spaces.emplace_back(local_discretizations.back().test_space());
    }
    logger.info() << "Creating space... " << std::endl;
    SpaceType space(dd_grid, local_spaces_ptr);

    logger.info() << "Preparing container..." << std::endl;
    std::vector<XT::LA::SparsityPatternDefault> local_patterns(dd_grid.size());
    std::vector<std::map<size_t, XT::LA::SparsityPatternDefault>> inside_outside_patterns(dd_grid.size());
    std::vector<std::map<size_t, XT::LA::SparsityPatternDefault>> outside_inside_patterns(dd_grid.size());
    std::map<size_t, XT::LA::SparsityPatternDefault> boundary_patterns;
    XT::LA::SparsityPatternDefault pattern(space.mapper().size());
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      local_patterns[ss] = local_spaces[ss].compute_face_and_volume_pattern(); // todo: from the local discretization
      copy_local_to_global(local_patterns[ss], space, ss, ss, pattern);
      if (dd_grid.boundary(ss)) {
        // in general, this can differ from the local one (think of CG)
        boundary_patterns[ss] = local_spaces[ss].compute_face_pattern(dd_grid.boundaryGridPart(ss));
        copy_local_to_global(boundary_patterns[ss], space, ss, ss, pattern);
      }
      for (auto&& nn : dd_grid.neighborsOf(ss)) {
        if (ss < nn) { //  each coupling only once
          inside_outside_patterns[ss][nn] =
              local_spaces[ss].compute_face_pattern(dd_grid.couplingGridPart(ss, nn), local_spaces[nn]);
          copy_local_to_global(inside_outside_patterns[ss][nn], space, ss, nn, pattern);
          outside_inside_patterns[nn][ss] =
              local_spaces[nn].compute_face_pattern(dd_grid.couplingGridPart(nn, ss), local_spaces[ss]);
          copy_local_to_global(outside_inside_patterns[nn][ss], space, nn, ss, pattern);
        }
      }
    }
    pattern.sort();
    MatrixType system_matrix(space.mapper().size(), space.mapper().size(), pattern);
    VectorType rhs_vector(space.mapper().size());
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      copy_local_to_global(local_discretizations[ss].system_matrix(), local_patterns[ss], space, ss, ss, system_matrix);
      copy_local_to_global(local_discretizations[ss].rhs_vector(), space, ss, rhs_vector);
    }

    logger.info() << "Assembling coupling contributions..." << std::endl;
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      for (auto&& nn : dd_grid.neighborsOf(ss)) {
        if (ss < nn) { //  each coupling only once
          MatrixType inside_inside_matrix(
              local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), local_patterns[ss]);
          MatrixType outside_outside_matrix(
              local_spaces[nn].mapper().size(), local_spaces[nn].mapper().size(), local_patterns[nn]);
          MatrixType inside_outside_matrix(
              local_spaces[ss].mapper().size(), local_spaces[nn].mapper().size(), inside_outside_patterns[ss][nn]);
          MatrixType outside_inside_matrix(
              local_spaces[nn].mapper().size(), local_spaces[ss].mapper().size(), outside_inside_patterns[nn][ss]);
          auto coupling_grid_part = dd_grid.couplingGridPart(ss, nn);
          // put all of this into a coupling operator
          CouplingAssembler<LocalSpaceType, decltype(coupling_grid_part)> coupling_assembler(
              coupling_grid_part, local_spaces[ss], local_spaces[ss], local_spaces[nn], local_spaces[nn]);
          typedef LocalEllipticIpdgIntegrands::Inner<typename ProblemType::DiffusionFactorType,
                                                     typename ProblemType::DiffusionTensorType,
                                                     coupling_method>
              CouplingIntegrandType;
          LocalCouplingIntegralOperator<CouplingIntegrandType> local_coupling_operator(problem.diffusion_factor(),
                                                                                problem.diffusion_tensor());
          LocalCouplingTwoFormAssembler<LocalCouplingIntegralOperator<CouplingIntegrandType>> local_coupling_assembler(
              local_coupling_operator);
          coupling_assembler.append(local_coupling_assembler,
                                    inside_inside_matrix,
                                    outside_outside_matrix,
                                    inside_outside_matrix,
                                    outside_inside_matrix);
          coupling_assembler.assemble();
          copy_local_to_global(inside_inside_matrix, local_patterns[ss], space, ss, ss, system_matrix);
          copy_local_to_global(outside_outside_matrix, local_patterns[nn], space, nn, nn, system_matrix);
          copy_local_to_global(inside_outside_matrix, inside_outside_patterns[ss][nn], space, ss, nn, system_matrix);
          copy_local_to_global(outside_inside_matrix, outside_inside_patterns[nn][ss], space, nn, ss, system_matrix);
        }
      }
    }

    logger.info() << "Assembling boundary contributions..." << std::endl;
    for (size_t ss = 0; ss < dd_grid.size(); ++ss) {
      if (dd_grid.boundary(ss)) {
        auto boundary_grid_part = dd_grid.boundaryGridPart(ss);
        auto boundary_pattern = local_spaces[ss].compute_face_and_volume_pattern(boundary_grid_part);
        MatrixType boundary_matrix(
            local_spaces[ss].mapper().size(), local_spaces[ss].mapper().size(), boundary_pattern);
        VectorType boundary_vector(local_spaces[ss].mapper().size());
        BoundaryAssembler<LocalSpaceType, decltype(boundary_grid_part)> boundary_assembler(
            boundary_grid_part, local_spaces[ss], local_spaces[ss]);
        auto boundary_info =
            XT::Grid::BoundaryInfoFactory<typename decltype(boundary_grid_part)::IntersectionType>::create(
                problem.boundary_info_cfg());
        typedef LocalEllipticIpdgIntegrands::BoundaryLHS<typename ProblemType::DiffusionFactorType,
                                                         typename ProblemType::DiffusionTensorType,
                                                         coupling_method>
            BoundaryLhsIntegrandType;
        LocalBoundaryIntegralOperator<BoundaryLhsIntegrandType> local_boundary_operator(problem.diffusion_factor(),
                                                                                problem.diffusion_tensor());
        LocalBoundaryTwoFormAssembler<LocalBoundaryIntegralOperator<BoundaryLhsIntegrandType>>
            local_boundary_operator_assembler(local_boundary_operator);
        boundary_assembler.append(
            local_boundary_operator_assembler,
            boundary_matrix,
            new XT::Grid::ApplyOn::DirichletIntersections<decltype(boundary_grid_part)>(*boundary_info));
        typedef LocalEllipticIpdgIntegrands::BoundaryRHS<typename ProblemType::FunctionType,
                                                         typename ProblemType::DiffusionFactorType,
                                                         typename ProblemType::DiffusionTensorType,
                                                         coupling_method>
            BoundaryRhsIntegrandType;
        LocalFaceIntegralFunctional<BoundaryRhsIntegrandType> local_boundary_functional(
            problem.dirichlet(), problem.diffusion_factor(), problem.diffusion_tensor());
        LocalFaceFunctionalAssembler<LocalFaceIntegralFunctional<BoundaryRhsIntegrandType>>
            local_boundary_functional_assembler(local_boundary_functional);
        boundary_assembler.append(
            local_boundary_functional_assembler,
            boundary_vector,
            new XT::Grid::ApplyOn::DirichletIntersections<decltype(boundary_grid_part)>(*boundary_info));
        boundary_assembler.assemble();
        copy_local_to_global(boundary_matrix, boundary_pattern, space, ss, ss, system_matrix);
        copy_local_to_global(boundary_vector, space, ss, rhs_vector);
      }
    }

    // create the discretization (no copy of the containers done here, bc. of cow)
    return DiscretizationType(problem, space, system_matrix, rhs_vector);
  } // ... discretize(...)

private:
  static void copy_local_to_global(const XT::LA::SparsityPatternDefault& local_pattern,
                                   const SpaceType& space,
                                   const size_t test_subdomain,
                                   const size_t ansatz_subdomain,
                                   XT::LA::SparsityPatternDefault& global_pattern)
  {
    const auto& mapper = space.mapper();
    for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {
      const size_t global_ii = mapper.mapToGlobal(test_subdomain, local_ii);
      const auto& local_rows = local_pattern.inner(local_ii);
      for (const auto& local_jj : local_rows) {
        const size_t global_jj = mapper.mapToGlobal(ansatz_subdomain, local_jj);
        global_pattern.insert(global_ii, global_jj);
      }
    }
  } // ... copy_local_to_global(...)

  static void copy_local_to_global(const MatrixType& local_matrix,
                                   const XT::LA::SparsityPatternDefault& local_pattern,
                                   const SpaceType& space,
                                   const size_t test_subdomain,
                                   const size_t ansatz_subdomain,
                                   MatrixType& global_matrix)
  {
    for (size_t local_ii = 0; local_ii < local_pattern.size(); ++local_ii) {
      const size_t global_ii = space.mapper().mapToGlobal(test_subdomain, local_ii);
      for (const size_t& local_jj : local_pattern.inner(local_ii)) {
        const size_t global_jj = space.mapper().mapToGlobal(ansatz_subdomain, local_jj);
        global_matrix.add_to_entry(global_ii, global_jj, local_matrix.get_entry(local_ii, local_jj));
      }
    }
  } // ... copy_local_to_global_matrix(...)

  static void copy_local_to_global(const VectorType& local_vector,
                                   const SpaceType& space,
                                   const size_t subdomain,
                                   VectorType& global_vector)
  {
    for (size_t local_ii = 0; local_ii < local_vector.size(); ++local_ii) {
      const size_t global_ii = space.mapper().mapToGlobal(subdomain, local_ii);
      global_vector.add_to_entry(global_ii, local_vector.get_entry(local_ii));
    }
  } // ... copy_local_to_global_matrix(...)
}; // class BlockIpdgDiscretizer

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_BLOCK_IPDG_HH
<|endoftext|>


<commit_before><commit_msg>remove old filesystem<commit_after><|endoftext|>


<commit_before>#include <Arduino.h>
#include "main.h"
#include "uplink.h"
#include "usonic.h"

extern "C" {
    #include "battery.h"
    #include "motor.h"
    #include "pinout.h"
    #include "odometry.h"
}

//////////////////////
/// Scheduler vars ///
//////////////////////
uint16_t scheduler_send_status        = INT16_MAX;
uint16_t scheduler_send_sensor        = INT16_MAX;
uint16_t scheduler_measure_ultrasonic = INT16_MAX;
uint16_t scheduler_measure_battery    = INT16_MAX;

//////////////////////
/// Setup function ///
//////////////////////
void setup() {
  battery_setup();
  motor_setup();
  odometry_setup();
  uplink_setup();
  ultrasonic_setup();
}

////////////////////
/// Endless loop ///
////////////////////
void loop() {

   if (scheduler_measure_battery > SCHEDULER_MEASURE_BATTERY_DELAY){
        battery_measure();
        scheduler_measure_battery = 0;
   }

   if (scheduler_measure_ultrasonic > SCHEDULER_MEASURE_ULTRASONIC_DELAY){
        ultrasonic_measure();
        scheduler_measure_ultrasonic = 0;
   }

   if (scheduler_send_status > SCHEDULER_SEND_STATUS_DELAY){
        //uplink_sendStatus();
        scheduler_send_status = 0;
   }

   if (scheduler_send_sensor > SCHEDULER_SEND_SENSOR_DELAY){
        uplink_sendSensor();
        scheduler_send_sensor = 0;
   }

   scheduler_send_status++;
   scheduler_send_sensor++;
   scheduler_measure_ultrasonic++;
   scheduler_measure_battery++;
}
<commit_msg>replaced int by uint<commit_after>#include <Arduino.h>
#include "main.h"
#include "uplink.h"
#include "usonic.h"

extern "C" {
    #include "battery.h"
    #include "motor.h"
    #include "pinout.h"
    #include "odometry.h"
}

//////////////////////
/// Scheduler vars ///
//////////////////////
uint16_t scheduler_send_status        = UINT16_MAX;
uint16_t scheduler_send_sensor        = UINT16_MAX;
uint16_t scheduler_measure_ultrasonic = UINT16_MAX;
uint16_t scheduler_measure_battery    = UINT16_MAX;

//////////////////////
/// Setup function ///
//////////////////////
void setup() {
  battery_setup();
  motor_setup();
  odometry_setup();
  uplink_setup();
  ultrasonic_setup();
}

////////////////////
/// Endless loop ///
////////////////////
void loop() {

   if (scheduler_measure_battery > SCHEDULER_MEASURE_BATTERY_DELAY){
        battery_measure();
        scheduler_measure_battery = 0;
   }

   if (scheduler_measure_ultrasonic > SCHEDULER_MEASURE_ULTRASONIC_DELAY){
        ultrasonic_measure();
        scheduler_measure_ultrasonic = 0;
   }

   if (scheduler_send_status > SCHEDULER_SEND_STATUS_DELAY){
        //uplink_sendStatus();
        scheduler_send_status = 0;
   }

   if (scheduler_send_sensor > SCHEDULER_SEND_SENSOR_DELAY){
        uplink_sendSensor();
        scheduler_send_sensor = 0;
   }

   scheduler_send_status++;
   scheduler_send_sensor++;
   scheduler_measure_ultrasonic++;
   scheduler_measure_battery++;
}
<|endoftext|>


<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "gsldatahandle.hh"
#include "gsldatautils.hh"
#include "gslfilter.hh"
#include "bseblockutils.hh"
#include <complex>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <FLAC/stream_decoder.h>

namespace Bse {

using std::vector;
using std::string;
using std::min;

class DataHandleFlac;

struct CDataHandleFlac : public GslDataHandle
{
  // back pointer to get casting right, even in presence of C++ vtable:
  DataHandleFlac* cxx_dh;
};

class DataHandleFlac {
private:
  static FLAC__StreamDecoderWriteStatus
  flac_write_callback (const FLAC__StreamDecoder  *decoder,
                       const FLAC__Frame          *frame,
                       const FLAC__int32          *const buffer[],
                       void                       *client_data)
  {
    DataHandleFlac *dh = static_cast<DataHandleFlac *> (client_data);
    dh->m_buffer_start = frame->header.number.sample_number * frame->header.channels;
    dh->m_buffer.clear();

    // scale with 1/32768 for 16 bit, 1/(2^23) for 24 bit
    double scale = 2.0 / (1 << frame->header.bits_per_sample);
    for (int i = 0; i < frame->header.blocksize; i++)
      {
        // interleave channels
        for (int ch = 0; ch < frame->header.channels; ch++)
          dh->m_buffer.push_back (buffer[ch][i] * scale);
      }
    return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  }

  // pass error status from flac callback to caller
  bool                              m_error_occurred;
  FLAC__StreamDecoderErrorStatus    m_error_status;

  static void
  flac_error_callback (const FLAC__StreamDecoder     *decoder,
                       FLAC__StreamDecoderErrorStatus status,
                       void                          *client_data)
  {
    DataHandleFlac *dh = static_cast<DataHandleFlac *> (client_data);
    dh->m_error_occurred = true;
    dh->m_error_status = status;
  }

protected:
  CDataHandleFlac	m_dhandle;
  int                   m_n_channels;
  bool			m_init_ok;
  string                m_file_name;
  FLAC__StreamDecoder  *m_decoder;
  int64                 m_buffer_start;
  vector<float>         m_buffer;
  float                 m_osc_freq;

public:
  DataHandleFlac (const string& file_name,
		  float         osc_freq) :
    m_init_ok (false),
    m_decoder (NULL)
  {
    memset (&m_dhandle, 0, sizeof (m_dhandle));
    m_init_ok = gsl_data_handle_common_init (&m_dhandle, NULL);
    m_file_name = file_name;
    m_dhandle.name = g_strdup (m_file_name.c_str());
    m_osc_freq = osc_freq;
  }

  /* protected destructor: (use reference counting instead) */
  virtual
  ~DataHandleFlac()
  {
    if (m_init_ok)
      gsl_data_handle_common_free (&m_dhandle);
  }

  BseErrorType
  open (GslDataHandleSetup *setup)
  {
    m_decoder = FLAC__stream_decoder_new();
    if (!m_decoder)
      return BSE_ERROR_IO;

    m_error_occurred = false;
    int err = FLAC__stream_decoder_init_file (m_decoder, m_file_name.c_str(),
                                              flac_write_callback, NULL, flac_error_callback, this);
    if (err != 0)
      return BSE_ERROR_IO;

    /* decode enough to figure out number of channels */
    FLAC__bool mdok;
    do {
      mdok = FLAC__stream_decoder_process_single (m_decoder);
    } while (FLAC__stream_decoder_get_channels (m_decoder) == 0 && mdok);

    if (FLAC__stream_decoder_get_channels (m_decoder) == 0)
      return BSE_ERROR_IO;

    if (m_error_occurred)
      return BSE_ERROR_IO;

    m_n_channels = setup->n_channels = FLAC__stream_decoder_get_channels (m_decoder);
    setup->n_values = FLAC__stream_decoder_get_total_samples (m_decoder);
    setup->bit_depth = FLAC__stream_decoder_get_bits_per_sample (m_decoder);
    setup->mix_freq = FLAC__stream_decoder_get_sample_rate (m_decoder);
    setup->xinfos = bse_xinfos_add_float (setup->xinfos, "osc-freq", m_osc_freq);

    return BSE_ERROR_NONE;
  }

  void
  close()
  {
    m_dhandle.setup.xinfos = NULL;	/* cleanup pointer reference */
  }

  int64
  read_samples (int64  voffset,
	        int64  n_values,
	        float *values)
  {
    if (voffset >= m_buffer_start + m_buffer.size())
      {
        // try to read on, probably we'll have just the samples we need, then
        m_error_occurred = false;
        FLAC__bool decode_ok = FLAC__stream_decoder_process_single (m_decoder);

        if (!decode_ok || m_error_occurred)
          return -1;
      }

    if (voffset >= m_buffer_start && voffset < m_buffer_start + m_buffer.size())
      {
        int64 buffer_offset = voffset - m_buffer_start;
        n_values = MIN (n_values, m_buffer.size() - buffer_offset);
        std::copy (m_buffer.begin() + buffer_offset, m_buffer.begin() + buffer_offset + n_values, values);
        return n_values;
      }

    // need to seek to get to the right location
    m_error_occurred = false;
    FLAC__bool seek_ok = FLAC__stream_decoder_seek_absolute (m_decoder, voffset / m_n_channels);
    if (!seek_ok || m_error_occurred)
      return -1;

    if (voffset == m_buffer_start)
      return read_samples (voffset, n_values, values);    // will work this time, since we have the right samples now

    return 0;
  }

  static GslDataHandle*
  dh_create (DataHandleFlac *cxx_dh)
  {
    static GslDataHandleFuncs dh_vtable =
    {
      dh_open,
      dh_read,
      dh_close,
      NULL,
      NULL,
      dh_destroy,
    };

    if (cxx_dh->m_init_ok)
      {
	cxx_dh->m_dhandle.vtable = &dh_vtable;
	cxx_dh->m_dhandle.cxx_dh = cxx_dh;	/* make casts work, later on */
	return &cxx_dh->m_dhandle;
      }
    else
      {
	delete cxx_dh;
	return NULL;
      }
  }
  static DataHandleFlac*
  dh_cast (GslDataHandle *dhandle)
  {
    return static_cast<CDataHandleFlac *> (dhandle)->cxx_dh;
  }
private:
/* for the "C" API (vtable) */
  static BseErrorType
  dh_open (GslDataHandle *dhandle, GslDataHandleSetup *setup)
  {
    return dh_cast (dhandle)->open (setup);
  }
  static void
  dh_close (GslDataHandle *dhandle)
  {
    dh_cast (dhandle)->close();
  }
  static void
  dh_destroy (GslDataHandle *dhandle)
  {
    delete dh_cast (dhandle);
  }
  static int64
  dh_read (GslDataHandle *dhandle,
	   int64          voffset,
	   int64          n_values,
	   gfloat        *values)
  {
    return dh_cast (dhandle)->read_samples (voffset, n_values, values);
  }
};

}

using namespace Bse;

extern "C" GslDataHandle*
bse_data_handle_new_flac (const char    *file_name,
                          gfloat         osc_freq)
{
  DataHandleFlac *cxx_dh = new DataHandleFlac (file_name, osc_freq);
  return DataHandleFlac::dh_create (cxx_dh);
}
<commit_msg>FLAC: fix length information for multi-channel files<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "gsldatahandle.hh"
#include "gsldatautils.hh"
#include "gslfilter.hh"
#include "bseblockutils.hh"
#include <complex>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <FLAC/stream_decoder.h>

namespace Bse {

using std::vector;
using std::string;
using std::min;

class DataHandleFlac;

struct CDataHandleFlac : public GslDataHandle
{
  // back pointer to get casting right, even in presence of C++ vtable:
  DataHandleFlac* cxx_dh;
};

class DataHandleFlac {
private:
  static FLAC__StreamDecoderWriteStatus
  flac_write_callback (const FLAC__StreamDecoder  *decoder,
                       const FLAC__Frame          *frame,
                       const FLAC__int32          *const buffer[],
                       void                       *client_data)
  {
    DataHandleFlac *dh = static_cast<DataHandleFlac *> (client_data);
    dh->m_buffer_start = frame->header.number.sample_number * frame->header.channels;
    dh->m_buffer.clear();

    // scale with 1/32768 for 16 bit, 1/(2^23) for 24 bit
    double scale = 2.0 / (1 << frame->header.bits_per_sample);
    for (int i = 0; i < frame->header.blocksize; i++)
      {
        // interleave channels
        for (int ch = 0; ch < frame->header.channels; ch++)
          dh->m_buffer.push_back (buffer[ch][i] * scale);
      }
    return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  }

  // pass error status from flac callback to caller
  bool                              m_error_occurred;
  FLAC__StreamDecoderErrorStatus    m_error_status;

  static void
  flac_error_callback (const FLAC__StreamDecoder     *decoder,
                       FLAC__StreamDecoderErrorStatus status,
                       void                          *client_data)
  {
    DataHandleFlac *dh = static_cast<DataHandleFlac *> (client_data);
    dh->m_error_occurred = true;
    dh->m_error_status = status;
  }

protected:
  CDataHandleFlac	m_dhandle;
  int                   m_n_channels;
  bool			m_init_ok;
  string                m_file_name;
  FLAC__StreamDecoder  *m_decoder;
  int64                 m_buffer_start;
  vector<float>         m_buffer;
  float                 m_osc_freq;

public:
  DataHandleFlac (const string& file_name,
		  float         osc_freq) :
    m_init_ok (false),
    m_decoder (NULL)
  {
    memset (&m_dhandle, 0, sizeof (m_dhandle));
    m_init_ok = gsl_data_handle_common_init (&m_dhandle, NULL);
    m_file_name = file_name;
    m_dhandle.name = g_strdup (m_file_name.c_str());
    m_osc_freq = osc_freq;
  }

  /* protected destructor: (use reference counting instead) */
  virtual
  ~DataHandleFlac()
  {
    if (m_init_ok)
      gsl_data_handle_common_free (&m_dhandle);
  }

  BseErrorType
  open (GslDataHandleSetup *setup)
  {
    m_decoder = FLAC__stream_decoder_new();
    if (!m_decoder)
      return BSE_ERROR_IO;

    m_error_occurred = false;
    int err = FLAC__stream_decoder_init_file (m_decoder, m_file_name.c_str(),
                                              flac_write_callback, NULL, flac_error_callback, this);
    if (err != 0)
      return BSE_ERROR_IO;

    /* decode enough to figure out number of channels */
    FLAC__bool mdok;
    do {
      mdok = FLAC__stream_decoder_process_single (m_decoder);
    } while (FLAC__stream_decoder_get_channels (m_decoder) == 0 && mdok);

    if (FLAC__stream_decoder_get_channels (m_decoder) == 0)
      return BSE_ERROR_IO;

    if (m_error_occurred)
      return BSE_ERROR_IO;

    m_n_channels = setup->n_channels = FLAC__stream_decoder_get_channels (m_decoder);
    setup->n_values = FLAC__stream_decoder_get_total_samples (m_decoder) * m_n_channels;
    setup->bit_depth = FLAC__stream_decoder_get_bits_per_sample (m_decoder);
    setup->mix_freq = FLAC__stream_decoder_get_sample_rate (m_decoder);
    setup->xinfos = bse_xinfos_add_float (setup->xinfos, "osc-freq", m_osc_freq);

    return BSE_ERROR_NONE;
  }

  void
  close()
  {
    m_dhandle.setup.xinfos = NULL;	/* cleanup pointer reference */
  }

  int64
  read_samples (int64  voffset,
	        int64  n_values,
	        float *values)
  {
    if (voffset >= m_buffer_start + m_buffer.size())
      {
        // try to read on, probably we'll have just the samples we need, then
        m_error_occurred = false;
        FLAC__bool decode_ok = FLAC__stream_decoder_process_single (m_decoder);

        if (!decode_ok || m_error_occurred)
          return -1;
      }

    if (voffset >= m_buffer_start && voffset < m_buffer_start + m_buffer.size())
      {
        int64 buffer_offset = voffset - m_buffer_start;
        n_values = MIN (n_values, m_buffer.size() - buffer_offset);
        std::copy (m_buffer.begin() + buffer_offset, m_buffer.begin() + buffer_offset + n_values, values);
        return n_values;
      }

    // need to seek to get to the right location
    m_error_occurred = false;
    FLAC__bool seek_ok = FLAC__stream_decoder_seek_absolute (m_decoder, voffset / m_n_channels);
    if (!seek_ok || m_error_occurred)
      return -1;

    if (voffset == m_buffer_start)
      return read_samples (voffset, n_values, values);    // will work this time, since we have the right samples now

    return 0;
  }

  static GslDataHandle*
  dh_create (DataHandleFlac *cxx_dh)
  {
    static GslDataHandleFuncs dh_vtable =
    {
      dh_open,
      dh_read,
      dh_close,
      NULL,
      NULL,
      dh_destroy,
    };

    if (cxx_dh->m_init_ok)
      {
	cxx_dh->m_dhandle.vtable = &dh_vtable;
	cxx_dh->m_dhandle.cxx_dh = cxx_dh;	/* make casts work, later on */
	return &cxx_dh->m_dhandle;
      }
    else
      {
	delete cxx_dh;
	return NULL;
      }
  }
  static DataHandleFlac*
  dh_cast (GslDataHandle *dhandle)
  {
    return static_cast<CDataHandleFlac *> (dhandle)->cxx_dh;
  }
private:
/* for the "C" API (vtable) */
  static BseErrorType
  dh_open (GslDataHandle *dhandle, GslDataHandleSetup *setup)
  {
    return dh_cast (dhandle)->open (setup);
  }
  static void
  dh_close (GslDataHandle *dhandle)
  {
    dh_cast (dhandle)->close();
  }
  static void
  dh_destroy (GslDataHandle *dhandle)
  {
    delete dh_cast (dhandle);
  }
  static int64
  dh_read (GslDataHandle *dhandle,
	   int64          voffset,
	   int64          n_values,
	   gfloat        *values)
  {
    return dh_cast (dhandle)->read_samples (voffset, n_values, values);
  }
};

}

using namespace Bse;

extern "C" GslDataHandle*
bse_data_handle_new_flac (const char    *file_name,
                          gfloat         osc_freq)
{
  DataHandleFlac *cxx_dh = new DataHandleFlac (file_name, osc_freq);
  return DataHandleFlac::dh_create (cxx_dh);
}
<|endoftext|>


<commit_before>#pragma once

#include <iterator>

#include <R.h>
#include <Rinternals.h>

extern "C"
{

class sexp_scaled_point_iterator
   : public std::iterator<std::input_iterator_tag, double>
{

private:

    double * vector;
    size_t dimention;

public:

    sexp_scaled_point_iterator(const SEXP & val, size_t d)
        : vector(REAL(val))
    { }

    sexp_scaled_point_iterator(const SEXP & val, size_t d, size_t begin_index)
        : vector(REAL(val) + begin_index)
        , dimention(d)
    { }

    sexp_scaled_point_iterator (const sexp_scaled_point_iterator& x) = default;

    double operator*() const
    {
        return *vector;
    }

    double * operator->() const
    {
        return vector;
    }

    sexp_scaled_point_iterator& operator++()
    {
        vector += dimention;
        return *this;
    }

    sexp_scaled_point_iterator operator++(int)
    {
        sexp_scaled_point_iterator temp(*this);
        vector += dimention;
        return temp;
    }

    friend bool operator==(sexp_scaled_point_iterator const & a, sexp_scaled_point_iterator const & b)
    {
        return (a.vector == b.vector) && (a.dimention == b.dimention);
    }

    friend bool operator!=(sexp_scaled_point_iterator const & a, sexp_scaled_point_iterator const & b)
    {
        return !(a == b);
    }
};

} // extern "C";
<commit_msg>Delete obsolete files ;)<commit_after><|endoftext|>


<commit_before>#pragma once

#include "constants.hpp"
#include "filesystem.hpp"
#include "local_datagram_client.hpp"
#include "session.hpp"
#include "types.hpp"
#include <unistd.h>
#include <vector>

class grabber_client final {
public:
  grabber_client(const grabber_client&) = delete;

  grabber_client(void) {
    // Check socket file existance
    if (!filesystem::exists(constants::get_grabber_socket_file_path())) {
      throw std::runtime_error("grabber socket is not found");
    }

    // Check socket file permission
    if (auto current_console_user_id = session::get_current_console_user_id()) {
      if (!filesystem::is_owned(constants::get_grabber_socket_file_path(), *current_console_user_id)) {
        throw std::runtime_error("grabber socket is not writable");
      }
    } else {
      throw std::runtime_error("session::get_current_console_user_id error");
    }

    client_ = std::make_unique<local_datagram_client>(constants::get_grabber_socket_file_path());
  }

  void connect(krbn::connect_from connect_from) {
    krbn::operation_type_connect_struct s;
    s.connect_from = connect_from;
    s.pid = getpid();
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void system_preferences_values_updated(const system_preferences::values values) {
    krbn::operation_type_system_preferences_values_updated_struct s;
    s.values = values;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void clear_simple_modifications(void) {
    krbn::operation_type_clear_simple_modifications_struct s;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void add_simple_modification(krbn::key_code from_key_code, krbn::key_code to_key_code) {
    krbn::operation_type_add_simple_modification_struct s;
    s.from_key_code = from_key_code;
    s.to_key_code = to_key_code;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void clear_fn_function_keys(void) {
    krbn::operation_type_clear_fn_function_keys_struct s;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void add_fn_function_key(krbn::key_code from_key_code, krbn::key_code to_key_code) {
    krbn::operation_type_add_fn_function_key_struct s;
    s.from_key_code = from_key_code;
    s.to_key_code = to_key_code;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void set_caps_lock_led_state(krbn::led_state led_state) {
    krbn::operation_type_set_caps_lock_led_state_struct s;
    s.led_state = led_state;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

private:
  std::unique_ptr<local_datagram_client> client_;
};
<commit_msg>add clear_devices,add_device,complete_devices<commit_after>#pragma once

#include "constants.hpp"
#include "filesystem.hpp"
#include "local_datagram_client.hpp"
#include "session.hpp"
#include "types.hpp"
#include <unistd.h>
#include <vector>

class grabber_client final {
public:
  grabber_client(const grabber_client&) = delete;

  grabber_client(void) {
    // Check socket file existance
    if (!filesystem::exists(constants::get_grabber_socket_file_path())) {
      throw std::runtime_error("grabber socket is not found");
    }

    // Check socket file permission
    if (auto current_console_user_id = session::get_current_console_user_id()) {
      if (!filesystem::is_owned(constants::get_grabber_socket_file_path(), *current_console_user_id)) {
        throw std::runtime_error("grabber socket is not writable");
      }
    } else {
      throw std::runtime_error("session::get_current_console_user_id error");
    }

    client_ = std::make_unique<local_datagram_client>(constants::get_grabber_socket_file_path());
  }

  void connect(krbn::connect_from connect_from) {
    krbn::operation_type_connect_struct s;
    s.connect_from = connect_from;
    s.pid = getpid();
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void system_preferences_values_updated(const system_preferences::values values) {
    krbn::operation_type_system_preferences_values_updated_struct s;
    s.values = values;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void clear_simple_modifications(void) {
    krbn::operation_type_clear_simple_modifications_struct s;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void add_simple_modification(krbn::key_code from_key_code, krbn::key_code to_key_code) {
    krbn::operation_type_add_simple_modification_struct s;
    s.from_key_code = from_key_code;
    s.to_key_code = to_key_code;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void clear_fn_function_keys(void) {
    krbn::operation_type_clear_fn_function_keys_struct s;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void add_fn_function_key(krbn::key_code from_key_code, krbn::key_code to_key_code) {
    krbn::operation_type_add_fn_function_key_struct s;
    s.from_key_code = from_key_code;
    s.to_key_code = to_key_code;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void clear_devices(void) {
    krbn::operation_type_clear_devices_struct s;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void add_device(krbn::vendor_product_id vendor_product_id, bool ignore) {
    krbn::operation_type_add_device_struct s;
    s.vendor_product_id = vendor_product_id;
    s.ignore = ignore;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void complete_devices(void) {
    krbn::operation_type_complete_devices_struct s;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

  void set_caps_lock_led_state(krbn::led_state led_state) {
    krbn::operation_type_set_caps_lock_led_state_struct s;
    s.led_state = led_state;
    client_->send_to(reinterpret_cast<uint8_t*>(&s), sizeof(s));
  }

private:
  std::unique_ptr<local_datagram_client> client_;
};
<|endoftext|>


<commit_before>//
//  net.cpp
//  Luves
//
//  Created by leviathan on 16/5/17.
//  Copyright © 2016年 leviathan. All rights reserved.
//
#include <stdio.h>

#include "net.h"

namespace luves
{
    //
    //Socket属性操作
    //
    int SocketOp::SetNonblock(int fd)
    {
        int flags=fcntl(fd, F_GETFL,0);
        if(flags<0)
            return errno;
        return fcntl(fd, F_SETFL,flags|O_NONBLOCK);
    }

    int SocketOp::SetReuseaddr(int fd)
    {
        int flags=1;
        int len=sizeof(flags);
        return setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flags, len);
    }

    int SocketOp::SetReuseport(int fd)
    {
        int flags=1;
        int len=sizeof(flags);
        return setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &flags, len);
    }

    //
    //Ip4地址模块
    //
    std::string Ip4Addr::ToString()
    {
        uint32_t host = addr_.sin_addr.s_addr;
        char str[64];
        sprintf(str, "%d.%d.%d.%d:%d",(host>> 0)&0xff,(host >> 8)&0xff,(host >> 16)&0xff,(host>> 24)&0xff, ntohs(addr_.sin_port));
        return str;
    }

    //
    //Socket
    //
    Socket::~Socket()
    {
        Socket::Close(fd_);
    }

    void Socket::Close(int fd)
    {
        close(fd);
    }

    int Socket::CreateNonBlockSocket()
    {
        int socket_fd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        FATALIF_LOG(!socket_fd,"socket fd create failed!");
        return socket_fd;
    }

    int Socket::Bind(int fd,sockaddr_in * server_addr)
    {
        int ret =bind(fd,(struct sockaddr *)server_addr,sizeof(*server_addr));
        if (ret==-1)
        {
            close(fd);
            ERROR_LOG("bind to %d failed! %d %s",fd,errno,strerror(errno));
            return ret;
        }
        return 0;
    }

    void Socket::Listen(int fd)
    {
        int ret=listen(fd, 20);
        if (ret==-1)
        {
            ERROR_LOG("listen to %d failed! %d %s",fd,errno,strerror(errno));
        }
    }

    int Socket::Accept(int fd,sockaddr_in * client_addr)
    {
        socklen_t client_len=sizeof(*client_addr);
        int accept_fd=accept(fd, (struct sockaddr *)client_addr,&client_len);
        if(accept_fd==-1 & errno!=EAGAIN)
            ERROR_LOG("accept to %d failed! %d %s",fd,errno,strerror(errno));
        return accept_fd;
    }

    void Socket::Connect(int fd,sockaddr_in * server_addr)
    {
        connect(fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    }

}
<commit_msg>modify listen backlog<commit_after>//
//  net.cpp
//  Luves
//
//  Created by leviathan on 16/5/17.
//  Copyright © 2016年 leviathan. All rights reserved.
//
#include <stdio.h>

#include "net.h"

namespace luves
{
    //
    //Socket属性操作
    //
    int SocketOp::SetNonblock(int fd)
    {
        int flags=fcntl(fd, F_GETFL,0);
        if(flags<0)
            return errno;
        return fcntl(fd, F_SETFL,flags|O_NONBLOCK);
    }

    int SocketOp::SetReuseaddr(int fd)
    {
        int flags=1;
        int len=sizeof(flags);
        return setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flags, len);
    }

    int SocketOp::SetReuseport(int fd)
    {
        int flags=1;
        int len=sizeof(flags);
        return setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &flags, len);
    }

    //
    //Ip4地址模块
    //
    std::string Ip4Addr::ToString()
    {
        uint32_t host = addr_.sin_addr.s_addr;
        char str[64];
        sprintf(str, "%d.%d.%d.%d:%d",(host>> 0)&0xff,(host >> 8)&0xff,(host >> 16)&0xff,(host>> 24)&0xff, ntohs(addr_.sin_port));
        return str;
    }

    //
    //Socket
    //
    Socket::~Socket()
    {
        Socket::Close(fd_);
    }

    void Socket::Close(int fd)
    {
        close(fd);
    }

    int Socket::CreateNonBlockSocket()
    {
        int socket_fd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        FATALIF_LOG(!socket_fd,"socket fd create failed!");
        return socket_fd;
    }

    int Socket::Bind(int fd,sockaddr_in * server_addr)
    {
        int ret =bind(fd,(struct sockaddr *)server_addr,sizeof(*server_addr));
        if (ret==-1)
        {
            close(fd);
            ERROR_LOG("bind to %d failed! %d %s",fd,errno,strerror(errno));
            return ret;
        }
        return 0;
    }

    void Socket::Listen(int fd)
    {
        int ret=listen(fd, 1024);
        if (ret==-1)
        {
            ERROR_LOG("listen to %d failed! %d %s",fd,errno,strerror(errno));
        }
    }

    int Socket::Accept(int fd,sockaddr_in * client_addr)
    {
        socklen_t client_len=sizeof(*client_addr);
        int accept_fd=accept(fd, (struct sockaddr *)client_addr,&client_len);
        if(accept_fd==-1 & errno!=EAGAIN)
            ERROR_LOG("accept to %d failed! %d %s",fd,errno,strerror(errno));
        return accept_fd;
    }

    void Socket::Connect(int fd,sockaddr_in * server_addr)
    {
        connect(fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    }

}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * Vulkan CTS Framework
 * --------------------
 *
 * Copyright (c) 2018 The Khronos Group Inc.
 * Copyright (c) 2018 Intel Corporation
 *
 * 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.
 *
 *//*!
 * \file
 * \brief RenderDoc utility
 *//*--------------------------------------------------------------------*/

#include "vkRenderDocUtil.hpp"

#include "deDynamicLibrary.hpp"
#include "deUniquePtr.hpp"
#include "tcuDefs.hpp"

#include "renderdoc_app.h"
#include <stdexcept>

#if (DE_OS == DE_OS_WIN32)
#	define RENDERDOC_LIBRARY_NAME "renderdoc.dll"
#else
#	define RENDERDOC_LIBRARY_NAME "librenderdoc.so"
#endif

namespace vk
{

struct RenderDocPrivate
{
										RenderDocPrivate	(void)	: m_api(DE_NULL), m_valid(false) {}

	de::MovePtr<de::DynamicLibrary>		m_library;
	::RENDERDOC_API_1_1_2*				m_api;
	bool								m_valid;
};

RenderDocUtil::RenderDocUtil (void)
	: m_priv	(new RenderDocPrivate)
{
	try
	{
		m_priv->m_library	 = de::MovePtr<de::DynamicLibrary>(new de::DynamicLibrary(RENDERDOC_LIBRARY_NAME));
	}
	catch (const std::runtime_error& e)
	{
		tcu::print("Library %s not loaded: %s, RenderDoc API not available", e.what(), RENDERDOC_LIBRARY_NAME);
	}

	if (m_priv->m_library)
	{
		::pRENDERDOC_GetAPI pGetApi = (::pRENDERDOC_GetAPI)m_priv->m_library->getFunction("RENDERDOC_GetAPI");
		const int			ret		= pGetApi(eRENDERDOC_API_Version_1_1_2, (void **)&m_priv->m_api);

		if (ret == 1)
		{
			m_priv->m_api->TriggerCapture();

			m_priv->m_valid = true;
		}
		else
		{
			tcu::print("RENDERDOC_GetAPI returned %d status, RenderDoc API not available", ret);
		}
	}
}

RenderDocUtil::~RenderDocUtil (void)
{
	if (m_priv)
	{
		delete m_priv;
	}
}

bool RenderDocUtil::isValid (void)
{
	return m_priv != DE_NULL && m_priv->m_valid;
}

void RenderDocUtil::startFrame (vk::VkInstance instance)
{
	if (!isValid()) return;

	m_priv->m_api->StartFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}

void RenderDocUtil::endFrame (vk::VkInstance instance)
{
	if (!isValid()) return;

	m_priv->m_api->EndFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}

} // vk
<commit_msg>Fix renderdoc library name on android<commit_after>/*-------------------------------------------------------------------------
 * Vulkan CTS Framework
 * --------------------
 *
 * Copyright (c) 2018 The Khronos Group Inc.
 * Copyright (c) 2018 Intel Corporation
 *
 * 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.
 *
 *//*!
 * \file
 * \brief RenderDoc utility
 *//*--------------------------------------------------------------------*/

#include "vkRenderDocUtil.hpp"

#include "deDynamicLibrary.hpp"
#include "deUniquePtr.hpp"
#include "tcuDefs.hpp"

#include "renderdoc_app.h"
#include <stdexcept>

#if (DE_OS == DE_OS_WIN32)
#	define RENDERDOC_LIBRARY_NAME "renderdoc.dll"
#elif (DE_OS == DE_OS_ANDROID)
#	define RENDERDOC_LIBRARY_NAME "libVkLayer_GLES_RenderDoc.so"
#else
#	define RENDERDOC_LIBRARY_NAME "librenderdoc.so"
#endif

namespace vk
{

struct RenderDocPrivate
{
										RenderDocPrivate	(void)	: m_api(DE_NULL), m_valid(false) {}

	de::MovePtr<de::DynamicLibrary>		m_library;
	::RENDERDOC_API_1_1_2*				m_api;
	bool								m_valid;
};

RenderDocUtil::RenderDocUtil (void)
	: m_priv	(new RenderDocPrivate)
{
	try
	{
		m_priv->m_library	 = de::MovePtr<de::DynamicLibrary>(new de::DynamicLibrary(RENDERDOC_LIBRARY_NAME));
	}
	catch (const std::runtime_error& e)
	{
		tcu::print("Library %s not loaded: %s, RenderDoc API not available", e.what(), RENDERDOC_LIBRARY_NAME);
	}

	if (m_priv->m_library)
	{
		::pRENDERDOC_GetAPI pGetApi = (::pRENDERDOC_GetAPI)m_priv->m_library->getFunction("RENDERDOC_GetAPI");
		const int			ret		= pGetApi(eRENDERDOC_API_Version_1_1_2, (void **)&m_priv->m_api);

		if (ret == 1)
		{
			m_priv->m_api->TriggerCapture();

			m_priv->m_valid = true;
		}
		else
		{
			tcu::print("RENDERDOC_GetAPI returned %d status, RenderDoc API not available", ret);
		}
	}
}

RenderDocUtil::~RenderDocUtil (void)
{
	if (m_priv)
	{
		delete m_priv;
	}
}

bool RenderDocUtil::isValid (void)
{
	return m_priv != DE_NULL && m_priv->m_valid;
}

void RenderDocUtil::startFrame (vk::VkInstance instance)
{
	if (!isValid()) return;

	m_priv->m_api->StartFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}

void RenderDocUtil::endFrame (vk::VkInstance instance)
{
	if (!isValid()) return;

	m_priv->m_api->EndFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(instance), DE_NULL);
}

} // vk
<|endoftext|>


<commit_before>/*Copyright 2010-2013 George Karagoulis

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.*/

#ifndef GUTIL_NO_GUI_FUNCTIONALITY

#include "messageboxlogger.h"
#include <QMessageBox>
#include <QDateTime>
#include <QMetaType>
USING_NAMESPACE_GUTIL;

NAMESPACE_GUTIL1(QT);

MessageBoxLogger::MessageBoxLogger(QWidget *parent)
    :QObject((QObject *)parent),
      m_parentWidget(parent)
{
    qRegisterMetaType<LoggingData>("LoggingData");
}

void MessageBoxLogger::Log(const LoggingData &d) noexcept
{
    // Invoke this as a queued signal so the logging happens in our event loop
    QMetaObject::invokeMethod(this, "_log", Qt::QueuedConnection,
                              Q_ARG(LoggingData, d));
}

void MessageBoxLogger::_log(const LoggingData &d)
{
    QString title = QString("%1 %2")
            .arg(QDateTime::fromTime_t(d.LogTime).toString())
            .arg(d.Title.ConstData());
    QString msg(d.Message.ConstData());
    switch(d.MessageLevel)
    {
    case LogLevelInfo:
        QMessageBox::information(m_parentWidget, title, msg);
        break;
    case LogLevelWarning:
        QMessageBox::warning(m_parentWidget, title, msg);
        break;
    case LogLevelError:
        QMessageBox::critical(m_parentWidget, title, msg);
        break;
    default:
        break;
    }
}

END_NAMESPACE_GUTIL1;

#endif // GUI_FUNCTIONALITY
<commit_msg>Made this an AutoConnection so if you are on the same thread it doesn't get queued.<commit_after>/*Copyright 2010-2013 George Karagoulis

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.*/

#ifndef GUTIL_NO_GUI_FUNCTIONALITY

#include "messageboxlogger.h"
#include <QMessageBox>
#include <QDateTime>
#include <QMetaType>
USING_NAMESPACE_GUTIL;

NAMESPACE_GUTIL1(QT);

MessageBoxLogger::MessageBoxLogger(QWidget *parent)
    :QObject((QObject *)parent),
      m_parentWidget(parent)
{
    qRegisterMetaType<LoggingData>("LoggingData");
}

void MessageBoxLogger::Log(const LoggingData &d) noexcept
{
    // Invoke this as a queued signal so the logging happens in our event loop
    QMetaObject::invokeMethod(this, "_log", Qt::AutoConnection,
                              Q_ARG(LoggingData, d));
}

void MessageBoxLogger::_log(const LoggingData &d)
{
    QString title = QString("%1 %2")
            .arg(QDateTime::fromTime_t(d.LogTime).toString())
            .arg(d.Title.ConstData());
    QString msg(d.Message.ConstData());
    switch(d.MessageLevel)
    {
    case LogLevelInfo:
        QMessageBox::information(m_parentWidget, title, msg);
        break;
    case LogLevelWarning:
        QMessageBox::warning(m_parentWidget, title, msg);
        break;
    case LogLevelError:
        QMessageBox::critical(m_parentWidget, title, msg);
        break;
    default:
        break;
    }
}

END_NAMESPACE_GUTIL1;

#endif // GUI_FUNCTIONALITY
<|endoftext|>


<commit_before>#include <unistd.h>
#include <iostream>
#include <string.h>
#include <string>
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <fstream>

#define BUFSIZE 100

/* program to glitch pictures
 * TODO:
 * []bitmap / single file support
 *  *[X]extention recognition
 *  *[X]read file
 *  *[]one glitch method
 *  *[]bitmap output
 * []multiple file support
 * []multiple extension support
*/

using namespace std;

//fun crap, for runtime info
float chrono(clock_t t1, clock_t t2){
  float ticks = t2 - t2;
  float cps = (float)ticks/CLOCKS_PER_SEC;

  string calcs = to_string(ticks) + " ticks, or " + to_string(cps) + " seconds";

  return (float)(t2 - t1)/CLOCKS_PER_SEC;
}

string load(char *argv[]){
  string contents;
  ifstream infile;
  infile.open(argv[1]);
  if(infile.is_open())
    while(infile.good())
      getline(infile, contents);

  infile.close();
  return contents;
}

//runs a check on the extension, making sure the file is a bitmap
//maybe a more secure way of doing this?
string getExt(int argc, char *argv[]){
  if(argv[1] != NULL){
    size_t nameSize = strlen(argv[1]);
    string ext = "";

    for(int i = 0; i < nameSize; i++){
      if(argv[1][i] == '.'){
        for(int k = i; k < nameSize; k++){
          ext += argv[1][k];
        }
      }
    }

    if(ext != ".bmp"){
      cout << ext + " file format not supported (yet?), sorey m8" << endl;
      exit(1);
    }
    else
      return ext;
  }
  else{
    cout << "no file specified, try './glitch somefile.bmp'" << endl;
    exit(2);
  }
}

int main(int argc, char *argv[]){
  clock_t t1, t2;
  t1 = clock();
  //cout << "clock1 good" << endl;
  getExt(argc, argv);
  //cout << "getExt good" << endl;
  load(argv);
  //cout << "load good" << endl;
  t2 = clock();
  cout << chrono(t1, t2) << endl;

  return 0;
}
<commit_msg>remove maelstrom.cpp for idea revamp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <ctime>

#include "marian.h"

marian::Var layer(size_t max) {

    using namespace marian;

    Var x0 = 1, x1 = 2, x2 = 3;
    Var y = 0.0;
    for(int i = 0; i < max; i++) {
        Var xi = i;
        y = y + x0 + log(x2) + x1;
        for(int j = 0; j < i; ++j) {
            y = y + xi;
        }
    }

    return y;
}

int main(int argc, char** argv) {
    srand(time(NULL));

    using namespace marian;

    Var y1 = layer(10);
    Var y2 = layer(5);

    Var y = y1 + log(y2);

    set_zero_all_adjoints();
    y.calc_gradients();

    std::cerr << "y1 = " << y1.val() << std::endl;
    std::cerr << "y2 = " << y2.val() << std::endl;
    std::cerr << "y = " << y.val() << std::endl;

    std::cerr << "dy/dy1 = " << y1.grad() << std::endl;
    std::cerr << "dy/dy2 = " << y2.grad() << std::endl;

}<commit_msg>changed name<commit_after>#include <iostream>
#include <ctime>

#include "marian.h"

marian::Var layer(size_t max) {

    using namespace marian;

    Var x0 = 1, x1 = 2, x2 = 3;
    Var y = 0.0;
    for(int i = 0; i < max; i++) {
        Var xi = i;
        y = y + x0 + log(x2) + x1;
        for(int j = 0; j < i; ++j) {
            y = y + xi;
        }
    }

    return y;
}

int main(int argc, char** argv) {
    srand(time(NULL));

    using namespace marian;

    Var y1 = layer(10);
    Var y2 = layer(rand() % 20 + 1);

    Var y = y1 + log(y2);

    set_zero_all_adjoints();
    y.calc_gradients();

    std::cerr << "y1 = " << y1.val() << std::endl;
    std::cerr << "y2 = " << y2.val() << std::endl;
    std::cerr << "y = " << y.val() << std::endl;

    std::cerr << "dy/dy1 = " << y1.grad() << std::endl;
    std::cerr << "dy/dy2 = " << y2.grad() << std::endl;

}<|endoftext|>


<commit_before>#include <iostream>
#define _USE_MATH_DEFINES
#include <cmath>

#include "ics3/ics"

int main(int argc, char **argv) {
  std::cout << "angle of degree test section" << std::endl;
  {
    ics::Angle degree = ics::Angle::createDegree();
    degree.set(0);
    std::cout << degree.get() << ':' << degree.getRaw() << std::endl;
    degree.set(90);
    std::cout << degree.get() << ':' << degree.getRaw() << std::endl;
    degree.set(60);
    std::cout << degree.get() << ':' << degree.getRaw() << std::endl;
    try {
      degree.set(150);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument &e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle of radian test section" << std::endl;
    ics::Angle radian = ics::Angle::createRadian();
    radian.set(0);
    std::cout << radian.get() << ':' << radian.getRaw() << std::endl;
    radian.set(M_PI / 2);
    std::cout << radian.get() << ':' << radian.getRaw() << std::endl;
    radian.set(M_PI / 3);
    std::cout << radian.get() << ':' << radian.getRaw() << std::endl;
    try {
      radian.set(M_PI);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument &e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "parameter test section" << std::endl;
    ics::Parameter current = ics::Parameter::current();
    current.set(30);
    std::cout << static_cast<int>(current.get()) << std::endl;
    try {
      current.set(70);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument &e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "EepParam test section" << std::endl;
    ics::EepParam speed = ics::EepParam::speed();
    std::cout << speed.get() << std::endl;
    speed.set(100);
    std::cout << speed.get() << std::endl;
    try {
      speed.set(200);
      std::cerr << "Never run this" << std::endl;
    } catch (std::invalid_argument e) {
      std::cout << e.what() << std::endl;
    }
  }
  return 0;
}
<commit_msg>Update test.cpp for default value check<commit_after>#include <iostream>
#define _USE_MATH_DEFINES
#include <cmath>

#include "ics3/ics"

int main(int argc, char **argv) {
  std::cout << "angle of degree test section" << std::endl;
  {
    ics::Angle degree = ics::Angle::createDegree();
    std::cout << degree.get() << ':' << degree.getRaw() << std::endl;
    degree.set(0);
    std::cout << degree.get() << ':' << degree.getRaw() << std::endl;
    degree.set(90);
    std::cout << degree.get() << ':' << degree.getRaw() << std::endl;
    degree.set(60);
    std::cout << degree.get() << ':' << degree.getRaw() << std::endl;
    try {
      degree.set(150);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument &e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle of radian test section" << std::endl;
    ics::Angle radian = ics::Angle::createRadian();
    std::cout << radian.get() << ':' << radian.getRaw() << std::endl;
    radian.set(0);
    std::cout << radian.get() << ':' << radian.getRaw() << std::endl;
    radian.set(M_PI / 2);
    std::cout << radian.get() << ':' << radian.getRaw() << std::endl;
    radian.set(M_PI / 3);
    std::cout << radian.get() << ':' << radian.getRaw() << std::endl;
    try {
      radian.set(M_PI);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument &e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "parameter test section" << std::endl;
    ics::Parameter current = ics::Parameter::current();
    std::cout << static_cast<int>(current.get()) << std::endl;
    current.set(30);
    std::cout << static_cast<int>(current.get()) << std::endl;
    try {
      current.set(70);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument &e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "EepParam test section" << std::endl;
    ics::EepParam speed = ics::EepParam::speed();
    std::cout << speed.get() << std::endl;
    speed.set(100);
    std::cout << speed.get() << std::endl;
    try {
      speed.set(200);
      std::cerr << "Never run this" << std::endl;
    } catch (std::invalid_argument e) {
      std::cout << e.what() << std::endl;
    }
  }
  return 0;
}
<|endoftext|>