text:
#include "engine/engine.hpp"
#include "engine/api/route_parameters.hpp"
#include "engine/engine_config.hpp"
#include "engine/status.hpp"

#include "engine/datafacade/process_memory_datafacade.hpp"
#include "engine/datafacade/shared_memory_datafacade.hpp"

#include "storage/shared_barriers.hpp"
#include "util/simple_logger.hpp"

#include <boost/assert.hpp>
#include <boost/interprocess/sync/named_condition.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>

#include <algorithm>
#include <fstream>
#include <memory>
#include <utility>
#include <vector>

namespace
{
// Abstracted away the query locking into a template function
// Works the same for every plugin.
template <typename ParameterT, typename PluginT, typename ResultT>
osrm::engine::Status
RunQuery(const std::unique_ptr<osrm::engine::DataWatchdog> &watchdog,
         const std::shared_ptr<osrm::engine::datafacade::BaseDataFacade> &facade,
         const ParameterT &parameters,
         PluginT &plugin,
         ResultT &result)
{
    if (watchdog)
    {
        BOOST_ASSERT(!facade);
        auto lock_and_facade = watchdog->GetDataFacade();

        return plugin.HandleRequest(lock_and_facade.second, parameters, result);
    }

    BOOST_ASSERT(facade);

    return plugin.HandleRequest(facade, parameters, result);
}

} // anon. ns

namespace osrm
{
namespace engine
{

Engine::Engine(const EngineConfig &config)
    : lock(config.use_shared_memory ? std::make_unique<storage::SharedBarriers>()
                                    : std::unique_ptr<storage::SharedBarriers>()),
      route_plugin(config.max_locations_viaroute),       //
      table_plugin(config.max_locations_distance_table), //
      nearest_plugin(config.max_results_nearest),        //
      trip_plugin(config.max_locations_trip),            //
      match_plugin(config.max_locations_map_matching),   //
      tile_plugin()                                      //

{
    if (config.use_shared_memory)
    {
        if (!DataWatchdog::TryConnect())
        {
            throw util::exception(
                "No shared memory blocks found, have you forgotten to run osrm-datastore?");
        }

        watchdog = std::make_unique<DataWatchdog>();
        BOOST_ASSERT(watchdog);
    }
    else
    {
        if (!config.storage_config.IsValid())
        {
            throw util::exception("Invalid file paths given!");
        }
        immutable_data_facade =
            std::make_shared<datafacade::ProcessMemoryDataFacade>(config.storage_config);
    }
}

Status Engine::Route(const api::RouteParameters &params, util::json::Object &result) const
{
    return RunQuery(watchdog, immutable_data_facade, params, route_plugin, result);
}

Status Engine::Table(const api::TableParameters &params, util::json::Object &result) const
{
    return RunQuery(watchdog, immutable_data_facade, params, table_plugin, result);
}

Status Engine::Nearest(const api::NearestParameters &params, util::json::Object &result) const
{
    return RunQuery(watchdog, immutable_data_facade, params, nearest_plugin, result);
}

Status Engine::Trip(const api::TripParameters &params, util::json::Object &result) const
{
    return RunQuery(watchdog, immutable_data_facade, params, trip_plugin, result);
}

Status Engine::Match(const api::MatchParameters &params, util::json::Object &result) const
{
    return RunQuery(watchdog, immutable_data_facade, params, match_plugin, result);
}

Status Engine::Tile(const api::TileParameters &params, std::string &result) const
{
    return RunQuery(watchdog, immutable_data_facade, params, tile_plugin, result);
}

} // engine ns
} // osrm ns

max_stars_repo_name: edudude/osrm-backend

max_issues_repo_name: edudude/osrm-backend

max_forks_repo_name: edudude/osrm-backend


text:
// Copyright 2015-2020 Tier IV, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef OPENSCENARIO_INTERPRETER__SYNTAX__UNSIGNED_SHORT_HPP_
#define OPENSCENARIO_INTERPRETER__SYNTAX__UNSIGNED_SHORT_HPP_

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <openscenario_interpreter/error.hpp>
#include <std_msgs/msg/u_int16.hpp>
#include <string>

namespace openscenario_interpreter
{
inline namespace syntax
{
struct UnsignedShort : public std_msgs::msg::UInt16
{
  using value_type = decltype(std_msgs::msg::UInt16::data);

  explicit UnsignedShort() = default;

  explicit UnsignedShort(value_type value) { data = value; }

  explicit UnsignedShort(const std::string & s)
  try {
    data = boost::lexical_cast<value_type>(s);
  } catch (const boost::bad_lexical_cast &) {
    throw INVALID_NUMERIC_LITERAL_SPECIFIED(s);
  }

  constexpr operator value_type() const noexcept { return data; }

  decltype(auto) operator++() noexcept
  {
    ++data;
    return *this;
  }

  auto & operator+=(const double & rhs)
  {
    data += rhs;
    return *this;
  }

  auto & operator*=(const double & rhs)
  {
    data *= rhs;
    return *this;
  }
};

static_assert(std::is_standard_layout<UnsignedShort>::value, "");

static_assert(not std::is_trivial<UnsignedShort>::value, "");

std::istream & operator>>(std::istream &, UnsignedShort &);

std::ostream & operator<<(std::ostream &, const UnsignedShort &);
}  // namespace syntax
}  // namespace openscenario_interpreter

#endif  // OPENSCENARIO_INTERPRETER__SYNTAX__UNSIGNED_SHORT_HPP_

ext: hpp


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.
// Copyright (c) 2013-2014 Adam Wulkiewicz, Lodz, Poland.

// This file was modified by Oracle on 2014.
// Modifications copyright (c) 2014, Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_BACKWARD_COMPATIBILITY_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_BACKWARD_COMPATIBILITY_HPP

#include <boost/geometry/core/closure.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/strategies/distance.hpp>
#include <boost/geometry/strategies/tags.hpp>

#include <boost/geometry/algorithms/assign.hpp>

#include <boost/geometry/algorithms/dispatch/distance.hpp>

#include <boost/geometry/algorithms/detail/distance/default_strategies.hpp>
#include <boost/geometry/algorithms/detail/distance/point_to_geometry.hpp>
#include <boost/geometry/algorithms/detail/distance/multipoint_to_geometry.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace distance
{

template<typename Point, typename Segment, typename Strategy>
struct point_to_segment
{
    static inline typename strategy::distance::services::return_type
        <
            Strategy,
            Point,
            typename point_type<Segment>::type
        >::type
    apply(Point const& point, Segment const& segment, Strategy const& )
    {
        typename detail::distance::default_ps_strategy
            <
                Point,
                typename point_type<Segment>::type,
                Strategy
            >::type segment_strategy;

        typename point_type<Segment>::type p[2];
        geometry::detail::assign_point_from_index<0>(segment, p[0]);
        geometry::detail::assign_point_from_index<1>(segment, p[1]);
        return segment_strategy.apply(point, p[0], p[1]);
    }
};

}} // namespace detail::distance
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

// Point-segment version 1, with point-point strategy
template <typename Point, typename Segment, typename Strategy>
struct distance
<
    Point, Segment, Strategy,
    point_tag, segment_tag, strategy_tag_distance_point_point,
    false
> : detail::distance::point_to_segment<Point, Segment, Strategy>
{};

// Point-line version 1, where point-point strategy is specified
template <typename Point, typename Linestring, typename Strategy>
struct distance
<
    Point, Linestring, Strategy,
    point_tag, linestring_tag, strategy_tag_distance_point_point,
    false
>
{

    static inline typename strategy::distance::services::return_type
        <
            Strategy, Point, typename point_type<Linestring>::type
        >::type
    apply(Point const& point,
          Linestring const& linestring,
          Strategy const&)
    {
        typedef typename detail::distance::default_ps_strategy
                    <
                        Point,
                        typename point_type<Linestring>::type,
                        Strategy
                    >::type ps_strategy_type;

        return detail::distance::point_to_range
            <
                Point, Linestring, closed, ps_strategy_type
            >::apply(point, linestring, ps_strategy_type());
    }
};

// Point-ring , where point-point strategy is specified
template <typename Point, typename Ring, typename Strategy>
struct distance
<
    Point, Ring, Strategy,
    point_tag, ring_tag, strategy_tag_distance_point_point,
    false
>
{
    typedef typename strategy::distance::services::return_type
        <
            Strategy, Point, typename point_type<Ring>::type
        >::type return_type;

    static inline return_type apply(Point const& point,
            Ring const& ring,
            Strategy const&)
    {
        typedef typename detail::distance::default_ps_strategy
            <
                Point,
                typename point_type<Ring>::type,
                Strategy
            >::type ps_strategy_type;

        return detail::distance::point_to_ring
            <
                Point, Ring,
                geometry::closure<Ring>::value,
                ps_strategy_type
            >::apply(point, ring, ps_strategy_type());
    }
};

// Point-polygon , where point-point strategy is specified
template <typename Point, typename Polygon, typename Strategy>
struct distance
<
    Point, Polygon, Strategy,
    point_tag, polygon_tag, strategy_tag_distance_point_point,
    false
>
{
    typedef typename strategy::distance::services::return_type
        <
            Strategy, Point, typename point_type<Polygon>::type
        >::type return_type;

    static inline return_type apply(Point const& point,
                                    Polygon const& polygon,
                                    Strategy const&)
    {
        typedef typename detail::distance::default_ps_strategy
            <
                Point,
                typename point_type<Polygon>::type,
                Strategy
            >::type ps_strategy_type;

        return detail::distance::point_to_polygon
            <
                Point,
                Polygon,
                geometry::closure<Polygon>::value,
                ps_strategy_type
            >::apply(point, polygon, ps_strategy_type());
    }
};

template
<
    typename Point,
    typename MultiGeometry,
    typename MultiGeometryTag,
    typename Strategy
>
struct distance
    <
        Point, MultiGeometry, Strategy,
        point_tag, MultiGeometryTag,
        strategy_tag_distance_point_point, false
    >
{
    typedef typename strategy::distance::services::return_type
        <
            Strategy, Point, typename point_type<MultiGeometry>::type
        >::type return_type;

    static inline return_type apply(Point const& point,
                                    MultiGeometry const& multigeometry,
                                    Strategy const&)
    {
        typedef typename detail::distance::default_ps_strategy
            <
                Point,
                typename point_type<MultiGeometry>::type,
                Strategy
            >::type ps_strategy_type;

        return distance
            <
                Point, MultiGeometry, ps_strategy_type,
                point_tag, MultiGeometryTag,
                strategy_tag_distance_point_segment, false
            >::apply(point, multigeometry, ps_strategy_type());
    }
};

template
<
    typename Geometry,
    typename MultiPoint,
    typename GeometryTag,
    typename Strategy
>
struct distance
    <
        Geometry, MultiPoint, Strategy,
        GeometryTag, multi_point_tag,
        strategy_tag_distance_point_point, false
    >
{
    typedef typename strategy::distance::services::return_type
        <
            Strategy,
            typename point_type<MultiPoint>::type,
            typename point_type<Geometry>::type
        >::type return_type;

    static inline return_type apply(Geometry const& geometry,
                                    MultiPoint const& multipoint,
                                    Strategy const&)
    {
        typedef typename detail::distance::default_ps_strategy
            <
                typename point_type<MultiPoint>::type,
                typename point_type<Geometry>::type,
                Strategy
            >::type ps_strategy_type;

        return distance
            <
                Geometry, MultiPoint, ps_strategy_type,
                GeometryTag, multi_point_tag,
                strategy_tag_distance_point_segment, false
            >::apply(geometry, multipoint, ps_strategy_type());
    }
};

template
<
    typename MultiPoint,
    typename MultiGeometry,
    typename MultiGeometryTag,
    typename Strategy
>
struct distance
    <
        MultiPoint, MultiGeometry, Strategy,
        multi_point_tag, MultiGeometryTag,
        strategy_tag_distance_point_point, false
    >
{
    typedef typename strategy::distance::services::return_type
        <
            Strategy,
            typename point_type<MultiPoint>::type,
            typename point_type<MultiGeometry>::type
        >::type return_type;

    static inline return_type apply(MultiPoint const& multipoint,
                                    MultiGeometry const& multigeometry,
                                    Strategy const&)
    {
        typedef typename detail::distance::default_ps_strategy
            <
                typename point_type<MultiPoint>::type,
                typename point_type<MultiGeometry>::type,
                Strategy
            >::type ps_strategy_type;

        return distance
            <
                MultiPoint, MultiGeometry, ps_strategy_type,
                multi_point_tag, MultiGeometryTag,
                strategy_tag_distance_point_segment, false
            >::apply(multipoint, multigeometry, ps_strategy_type());
    }
};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_BACKWARD_COMPATIBILITY_HPP


text:
#ifndef __DIRPROD_RANGE_HPP__
#define __DIRPROD_RANGE_HPP__

#include <array>

#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/size.hpp>

#include "iterator.hpp"

namespace dirprod
{

template<class... Ranges>
class range
{
public:
    friend class range_iterator<Ranges...>;

    using iterator = range_iterator<Ranges...>;
    using const_iterator = iterator;
    using iterator_type = typename iterator::iterator_type;
    using value_type = typename iterator::value_type;
    using size_type = size_t;
    using difference_type = typename iterator::difference_type;

    range(Ranges&&... ranges):
        ranges_(std::forward<Ranges>(ranges)...),
        first_(std::apply([](auto&... rngs) { return iterator_type(boost::begin(rngs)...); }, ranges_)),
        last_(std::apply([](auto&... rngs) { return iterator_type(boost::end(rngs)...); }, ranges_)),
        dists_(std::apply([](auto&... rng) { return decltype(dists_){static_cast<typename iterator::difference_type>(boost::size(rng))...}; }, ranges_))
    {}

    auto begin()
    {
        return iterator(*this);
    }

    auto end()
    {
        auto it = begin();
        std::get<N - 1>(it.iterators_) = std::get<N - 1>(last_);
        return it;
    }

    auto begin() const
    {
        return const_iterator(*this);
    }

    auto end() const
    {
        auto it = begin();
        std::get<N - 1>(it.iterators_) = std::get<N - 1>(last_);
        return it;
    }

private:
    static const std::size_t N = sizeof...(Ranges);

    std::tuple<Ranges...> ranges_;
    iterator_type first_;
    iterator_type last_;
    std::array<typename iterator::difference_type, N> dists_;
};

template<class... Ranges>
range(Ranges&&...) -> range<Ranges...>;

// One element specialization.
template<class R>
class range<R>
{
public:
    range(R&& rng): range_(std::forward<R>(rng))
    {}

    auto begin()
    {
        return boost::begin(range_);
    }

    auto end()
    {
        return boost::end(range_);
    }

private:
    R range_;
};

} // namespace dirprod

#endif // __DIRPROD_RANGE_HPP__

max_forks_repo_name: igsha/dirprod


text:
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "ApkManager.h"

#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>
#include <stdexcept>

namespace {

void check_directory(std::string& dir) {
  if (!boost::filesystem::is_directory(dir.c_str())) {
    std::cerr << "error: not a writable directory: " << dir
              << std::endl;
    exit(EXIT_FAILURE);
  }
}

}

std::shared_ptr<FILE*> ApkManager::new_asset_file(const char* filename) {
  check_directory(m_apk_dir);
  std::ostringstream path;
  path << m_apk_dir << "/assets/secondary-program-dex-jars/";
  std::string assets_dir = path.str();
  check_directory(assets_dir);
  path << filename;

  FILE* fd = fopen(path.str().c_str(), "w");
  if (fd != nullptr) {
    m_files.emplace_back(std::make_shared<FILE*>(fd));
    return m_files.back();
  } else {
    throw new std::runtime_error("Error creating new asset file");
  }
}

ext: cpp


text:
 /**
 * Copyright (c) 2009 Carnegie Mellon University.
 *     All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS
 *  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.  See the License for the specific language
 *  governing permissions and limitations under the License.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */
#ifndef GRAPHLAB_GRAPH_JSON_PARSER_HPP
#define GRAPHLAB_GRAPH_JSON_PARSER_HPP

#include <string>
#include <sstream>
#include <iostream>
#include <vector>

#if defined(__clang) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic push
#endif

#pragma GCC diagnostic ignored "-Wreorder"
#include <libjson/libjson.h>

#if defined(__clang) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic pop
#endif

#include <boost/functional.hpp>
#include <graphlab/util/stl_util.hpp>
#include <graphlab/util/hdfs.hpp>
#include <graphlab/logger/logger.hpp>
#include <graphlab/serialization/serialization_includes.hpp>
#include <graphlab/graph/distributed_graph.hpp>
#include <graphlab/graph/ingress/distributed_identity_ingress.hpp>

namespace graphlab {

  namespace builtin_parsers {
    template <typename EdgeData>
    bool empty_edge_parser(EdgeData& e, const std::string& line) {
      return true;
    }

    template <typename VertexData>
    bool empty_vertex_parser(VertexData& v, const std::string& line) {
      return true;
    }

  }

template<typename VertexData, typename EdgeData>
class distributed_graph;

template <typename VertexData, typename EdgeData>
class json_parser {

  public:
    typedef distributed_graph<VertexData, EdgeData> graph_type;
    typedef EdgeData edge_data_type;
    typedef VertexData vertex_data_type;

    typedef typename graph_type::vertex_id_type vertex_id_type;
    typedef typename graph_type::lvid_type lvid_type;

    typedef boost::function<bool(edge_data_type&, const std::string&)> edge_parser_type;
    typedef boost::function<bool(vertex_data_type&, const std::string&)> vertex_parser_type;
    typedef boost::function<bool(graph_type&, const std::string&)> line_parser_type;

  public:
  json_parser (graph_type& graph, const std::string& prefix, bool gzip=false,
      edge_parser_type edge_parser=builtin_parsers::empty_edge_parser<EdgeData>,
      vertex_parser_type vertex_parser=builtin_parsers::empty_vertex_parser<VertexData>) :
    graph(graph), prefix(prefix), gzip(gzip), edge_parser(edge_parser), vertex_parser(vertex_parser) {
    }

  bool load() {
    line_parser_type graph_structure_parser = parse_graph_structure_from_json;
    line_parser_type vid2lvid_parser = parse_vid2lvid_from_json;
    line_parser_type edata_parser = boost::bind(parse_edatalist_from_json, _1, _2, edge_parser);
    line_parser_type vrecord_parser = boost::bind(parse_vrecord_from_json, _1, _2, vertex_parser);

    bool success = parse_by_line(graphfilename(), graph_structure_parser);
    success = success & parse_by_line(vid2lvidfilename(), vid2lvid_parser);
    success = success & parse_by_line(edatafilename(), edata_parser);
    success = success & parse_by_line(vrecordfilename(), vrecord_parser);

    if (!success) {
      logstream(LOG_FATAL) << "Fail parsing graph json" << std::endl;
      return false;
    }

    graph.local_graph.finalized = true;

    ASSERT_GE(graph.local_graph.num_vertices(), graph.local_graph.gstore.num_vertices);
    ASSERT_EQ(graph.vid2lvid.size(), graph.local_graph.num_vertices());
    ASSERT_EQ(graph.lvid2record.size(), graph.local_graph.num_vertices());

    logstream(LOG_INFO) << "Finished loading graph" << graph.procid()
      << "\n\tnverts: " << graph.num_local_own_vertices()
      << "\n\tnreplicas: " << graph.local_graph.num_vertices()
      << "\n\tnedges: " << graph.local_graph.num_edges()
      << std::endl;

    if (graph.ingress_ptr == NULL) {
      graph.ingress_ptr = new distributed_identity_ingress<VertexData, EdgeData>(graph.rpc.dc(), graph);
    }

    graph.ingress_ptr->exchange_global_info();
    delete graph.ingress_ptr;

    graph.finalized = true;
    return success;
  }

  bool parse_by_line (const std::string& srcfilename, line_parser_type line_parser) {
    std::string fname;
    //check for "/" ending in directory"
    if(!boost::ends_with(prefix,"/"))
        fname = prefix + "/" + srcfilename;
    else
        fname = prefix + srcfilename;

    logstream(LOG_INFO) << "Load graph json from " << fname << std::endl;

    boost::iostreams::filtering_stream<boost::iostreams::input> fin;
    // loading from hdfs
    if (boost::starts_with(prefix, "hdfs://")) {
      graphlab::hdfs& hdfs = hdfs::get_hdfs();
      graphlab::hdfs::fstream in_file(hdfs, fname);
      if (!in_file.good()) {
        logstream(LOG_FATAL) << "Fail to open file " << fname << std::endl;
        return false;
      }

      if (gzip) fin.push(boost::iostreams::gzip_decompressor());
      fin.push(in_file);

      if (!fin.good()) {
        logstream(LOG_FATAL) << "Fail to read from stream " << fname << std::endl;
        return false;
      }

      load_from_stream(fname, fin, line_parser);

      if (gzip) fin.pop();
      fin.pop();
    } else { // loading from disk
      std::ifstream in_file(fname.c_str(),
          std::ios_base::in | std::ios_base::binary);

      if (!in_file.good()) {
        logstream(LOG_FATAL) << "Fail to open file " << fname << std::endl;
        return false;
      }

      if (gzip) fin.push(boost::iostreams::gzip_decompressor());
      fin.push(in_file);

      if (!fin.good()) {
        logstream(LOG_FATAL) << "Fail to read from stream " << fname << std::endl;
        return false;
      }

      load_from_stream(fname, fin, line_parser);

      if (gzip) fin.pop();
      fin.pop();
    }

    return true;
  }
    /**
       \internal
       This internal function is used to load a single line from an input stream
     */
    template<typename Fstream>
    bool load_from_stream(std::string filename, Fstream& fin,
                          line_parser_type& line_parser) {
      size_t linecount = 0;
      timer ti; ti.start();
      while(fin.good() && !fin.eof()) {
        std::string line;
        std::getline(fin, line);
        if(line.empty()) continue;
        if(fin.fail()) break;
        const bool success = line_parser(graph, line);
        if (!success) {
          logstream(LOG_WARNING)
            << "Error parsing line " << linecount << " in "
            << filename << ": " << std::endl
            << "\t\"" << line << "\"" << std::endl;
          return false;
        }
        ++linecount;
        if (ti.current_time() > 5.0) {
          logstream(LOG_INFO) << linecount << " Lines read" << std::endl;
          ti.start();
        }
      }
      return true;
    } // end of load from stream

  /* Parse the graph structure from json */
  static bool parse_graph_structure_from_json (graph_type& graph, const std::string& str) {
    JSONNode n = libjson::parse(str);
    JSONNode::const_iterator i = n.begin();
    typedef typename graph_type::local_graph_type local_graph_type;
    local_graph_type& local_graph = graph.get_local_graph();
    while(i != n.end()) {
      if (i->name() == "numEdges") {
        local_graph.gstore.num_edges = i->as_int();
      } else if (i->name() == "numVertices") {
        local_graph.gstore.num_vertices= i->as_int();
      } else if (i->name() == "csr") {
        // parse rowIndex -> graph.local_graph.gstore.csr_source
        // parse colIndex -> graph.local_graph.gstore.csr_target
        JSONNode csr = *i;
        JSONNode::const_iterator j = csr.begin();
        while (j != csr.end()) {
          if (j->name() == "rowIndex") {
              parse_vid_array (local_graph.gstore.CSR_src, *j);
          } else if (j->name() == "colIndex") {
              parse_vid_array (local_graph.gstore.CSR_dst, *j);
          } else {
              logstream(LOG_ERROR) << "Error parsing json into graph. Unknown json node name:"
                << "CSR:" << j->name() << std::endl;
          }
          ++j;
        }
      } else if (i->name() == "csc") {
        // parse rowIndex -> graph.local_graph.gstore.csc_target
        // parse colIndex -> graph.local_graph.gstore.csc_source
        JSONNode csc = *i;
        JSONNode::const_iterator j = csc.begin();

        while (j != csc.end()) {
          if (j->name() == "rowIndex") {
              parse_vid_array (local_graph.gstore.CSC_dst, *j);
          } else if (j->name() == "colIndex") {
              parse_vid_array (local_graph.gstore.CSC_src, *j);
          } else {
              logstream(LOG_ERROR) << "Error parsing json into graph. Unknown json node name:"
                << "CSC:"<<j->name() << std::endl;
          }
          ++j;
        }
      } else if (i->name() == "c2rMap") {
        parse_vid_array (local_graph.gstore.c2r_map, *i);
      } else {
        logstream(LOG_ERROR) << "Error parsing json into graph. Unknown json node name:" <<
          i->name() << std::endl;
      }
      ++i;
    } // end while

    ASSERT_EQ(local_graph.gstore.num_edges, local_graph.gstore.c2r_map.size());
    ASSERT_EQ(local_graph.gstore.num_edges, local_graph.gstore.CSR_dst.size());
    ASSERT_EQ(local_graph.gstore.num_edges, local_graph.gstore.CSC_src.size());

    graph.lvid2record.reserve(local_graph.gstore.num_vertices);
    graph.lvid2record.resize(local_graph.gstore.num_vertices);
    local_graph.reserve(local_graph.gstore.num_vertices);
    // local_graph.finalized = true;
    return true;
  }

  /* Parse the vid2lvid map from json */
  static bool parse_vid2lvid_from_json (graph_type& graph, const std::string& str) {
    JSONNode n = libjson::parse(str);
    JSONNode::const_iterator i = n.begin();
    typedef typename graph_type::local_graph_type local_graph_type;
    while(i != n.end()) {
      if (i->name() == "vid2lvid") {
        JSONNode::const_iterator j = i->begin();
        typename graph_type::vid2lvid_map_type & map = graph.vid2lvid;
        map.clear();
        while(j != i->end()) {
          graph.vid2lvid[boost::lexical_cast<vertex_id_type>(j->name())] = (boost::lexical_cast<lvid_type>)(j->as_int());
          ++j;
        }
      } else {
        // report error
        return false;
      }
      ++i;
    }
    return true;
  }

  /* Parse the edata list from json */
  static bool parse_edatalist_from_json (graph_type& graph, const std::string& str,
      edge_parser_type edge_parser) {
    JSONNode n = libjson::parse(str);
    JSONNode::const_iterator i = n.begin();
    typedef typename graph_type::local_graph_type local_graph_type;
    local_graph_type& local_graph = graph.get_local_graph();
    while(i != n.end()) {
       if (i->name() == "edataList") {
        // parse  edatalist -> graph.local_graph.gstore.edata
        JSONNode edatanode= *i;
        JSONNode::const_iterator j = edatanode.begin();
        std::vector<edge_data_type>& edatalist = local_graph.gstore.edge_data_list;
        edatalist.clear();
        edatalist.reserve(local_graph.gstore.num_edges);
        edge_data_type e;
        while (j != edatanode.end()) {
          edge_parser(e, j->as_string());
          edatalist.push_back(e);
          ++j;
        }
       } else {
         return false;
         // report error
       }
      ++i;
    }
    return true;
  }

  /* Parse the vertex record list from json */
  static bool parse_vrecord_from_json (graph_type& graph, const std::string& str,
      vertex_parser_type vertex_parser) {

    typedef typename graph_type::local_graph_type local_graph_type;
    local_graph_type& local_graph = graph.get_local_graph();

    JSONNode n = libjson::parse(str);
    JSONNode::const_iterator i = n.begin();

    vertex_data_type vdata;
    typename graph_type::vertex_record vrecord;

    while (i != n.end()) {
      if (i->name() == "mirrors") {
        JSONNode::const_iterator j = (*i).begin();
        while (j != (*i).end()) {
          int mirror = j->as_int();
          vrecord._mirrors.set_bit((procid_t)mirror);
          ++j;
        }
      } else if (i->name() == "inEdges") {
        vrecord.num_in_edges = i->as_int();
      } else if (i->name() == "outEdges") {
        vrecord.num_out_edges = i->as_int();
      } else if (i->name() == "gvid") {
        // Check unsafe
        vrecord.gvid = boost::lexical_cast<vertex_id_type>(i->as_int());
      } else if (i->name() == "owner") {
        vrecord.owner = (procid_t)i->as_int();
      } else if (i->name() == "VertexData") {
        if (!(i->type() == JSON_NULL))
          vertex_parser(vdata, i->as_string());
      } else {
        logstream(LOG_ERROR) << "Error parsing json into vrecord. Unknown json node name:" <<
          i->name() << std::endl;
      }
      ++i;
    }

      if (graph.vid2lvid.find(vrecord.gvid) == graph.vid2lvid.end()) {
        // Check if this a singlton node
        // ignore for now
        logstream(LOG_WARNING) << "Singleton node detected: gvid = " << vrecord.gvid << ". Ignored" << std::endl;
      } else {
        lvid_type lvid = graph.vid2lvid[vrecord.gvid];
        graph.lvid2record[lvid] = vrecord;
        local_graph.add_vertex(lvid, vdata);
        if (vrecord.owner == graph.procid()) ++graph.local_own_nverts;
      }

    return true;
  }

  /*  Helper function starts here  */
  private:
  /* Parse an json integer array and copy to a int vector */
  static bool parse_vid_array (std::vector<vertex_id_type>& to, const JSONNode& n) {
    if (n.type() != JSON_ARRAY) return false;
    to.clear();
    JSONNode::const_iterator i = n.begin();
    while (i != n.end()) {
      to.push_back(i->as_int());
      ++i;
    }
    return true;
  }

  std::string zeropadding(const std::string& s, int width) {
      ASSERT_LE(s.length(), width);
      std::ostringstream ss;
      ss << std::setw(width) << std::setfill('0') << s;
      return ss.str();
  }

  const std::string graphfilename() {
    procid_t pid = graph.procid();
    std::string suffix =  gzip ? ".gz" : "";
    return "graph/graph"+tostr(pid)+"-r-"+zeropadding(tostr(pid), 5)+suffix;
    // return "graph/graph"+tostr(pid)+"-r-00000"+suffix;
  }

  const std::string vid2lvidfilename() {
    procid_t pid = graph.procid();
    std::string suffix =  gzip ? ".gz" : "";
    return "graph/vid2lvid"+tostr(pid)+"-r-"+zeropadding(tostr(pid), 5)+suffix;
    // return "graph/vid2lvid"+tostr(pid)+"-r-00000"+suffix;
  }

  const std::string edatafilename() {
    procid_t pid = graph.procid();
    std::string suffix =  gzip ? ".gz" : "";
    return "graph/edata"+tostr(pid)+"-r-"+zeropadding(tostr(pid),5)+suffix;
    // return "graph/edata"+tostr(pid)+"-r-00000"+suffix;
  }

  const std::string vrecordfilename() {
    procid_t pid = graph.procid();
    std::string suffix =  gzip ? ".gz" : "";
    return "vrecord/vdata"+tostr(pid)+"-r-"+zeropadding(tostr(pid),5)+suffix;
    // return "vrecord/vdata"+tostr(pid)+"-r-00000"+ suffix;
  }

  private:
    graph_type& graph;
    std::string prefix;
    bool gzip;
    edge_parser_type edge_parser;
    vertex_parser_type vertex_parser;
}; // json_parser

} // namespace graphlab
#endif

max_issues_repo_name: keerthanashanmugam/graphlabapi

max_forks_repo_name: keerthanashanmugam/graphlabapi


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2010.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <mpllibs/metamonad/let.hpp>
#include <mpllibs/metamonad/lazy.hpp>
#include <mpllibs/metamonad/eval_case.hpp>
#include <mpllibs/metamonad/eval_syntax.hpp>
#include <mpllibs/metamonad/eval_guard.hpp>
#include <mpllibs/metamonad/syntax.hpp>

#include <boost/test/unit_test.hpp>

#include <boost/mpl/list.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/assert.hpp>

#include <boost/type_traits.hpp>

#include "common.hpp"

namespace
{
  template <class A, class B>
  struct some_template;
}

BOOST_AUTO_TEST_CASE(test_let)
{
  using boost::mpl::equal;
  using boost::mpl::equal_to;
  using boost::mpl::plus;
  using boost::mpl::list;

  using mpllibs::metamonad::let;
  using mpllibs::metamonad::lazy;
  using mpllibs::metamonad::eval_case;
  using mpllibs::metamonad::matches;
  using mpllibs::metamonad::matches_c;
  using mpllibs::metamonad::syntax;
  using mpllibs::metamonad::eval_syntax;
  using mpllibs::metamonad::eval_guard;

  using boost::is_same;

  // test_let_name
  BOOST_MPL_ASSERT((
    equal_to<int13, eval_syntax<let<x, syntax<int13>, syntax<x> > >::type>
  ));

  // test_let_not_name
  BOOST_MPL_ASSERT((
    equal_to<int11, eval_syntax<let<x, syntax<int13>, syntax<int11> > >::type>
  ));

  // test_template
  BOOST_MPL_ASSERT((
    equal_to<
      int26,
      eval_syntax<let<x, syntax<int13>, syntax<double_value<x> > > >::type
    >
  ));

  // test_let_not_evaluating_its_body
  BOOST_MPL_ASSERT((
    is_same<syntax<int>, let<x, syntax<double>, syntax<int> >::type>
  ));

  // test_case_in_multi_let
  BOOST_MPL_ASSERT((
    is_same<
      syntax<eval_case<int, matches_c<int, some_template<int, double> > > >,
      let<
        x, syntax<double>,
        syntax<eval_case<int, matches_c<int, some_template<int, x> > > >
      >::type
    >
  ));

  // test_list_in_let
  BOOST_MPL_ASSERT((
    equal<
      list<int, double>,
      eval_syntax<let<x, syntax<int>, syntax<list<x, double> > > >::type
    >
  ));

  // test_let_and_eval_guard
  BOOST_MPL_ASSERT((
    is_same<
      syntax<eval_guard<int13> >,
      let<x, syntax<int13>, syntax<eval_guard<x> > >::type
    >
  ));
}


text:
//
// Created by Javier on 21/11/2016.
//

#include <boost/uuid/string_generator.hpp>
#include "Api.h"
#include "../business_logic/BuyerUseCases.h"
#include "JsonSerializer.h"

using namespace ashop::presentation;

Api::Api(crow::SimpleApp &app,
         ashop::business_logic::BuyerUseCases &buyer_use_cases)
        : app(app),
          buyer_use_cases(buyer_use_cases) {

    this->initializeRouting();
}

/*
 * REST API routing intialization goes here:
 *  - URL, query-string parameters, method ==> controller
 *  - ...
 */
void Api::initializeRouting() {

    CROW_ROUTE(this->app, "/help")
            ([this](const crow::request &request, crow::response &response) {

                this->controller_help_get(request, response);
            });

    CROW_ROUTE(this->app, "/baskets/<string>")
            ([this](const crow::request &request,
                    crow::response &response,
                    std::string basket_id) {

                this->controller_basket_get(request, response, basket_id);
            });
}

void Api::controller_help_get(const crow::request &request, crow::response &response) {
    response.write("Help!");
    response.end();
}

void Api::controller_basket_get(const crow::request &request, crow::response &response, std::string basket_id) {

    auto basket = this->buyer_use_cases.get_basket(boost::uuids::string_generator()(basket_id));

    if (basket) {
        response.set_header("Content-Type", "application/json");

        json11::Json json{JsonSerializer::to_map(basket.get())};
        response.write(json.dump());
    }

    response.end();
}

max_stars_repo_name: javierjeronimo/ashop-cplusplus-crow

max_issues_repo_name: javierjeronimo/ashop-cplusplus-crow

max_forks_repo_name: javierjeronimo/ashop-cplusplus-crow


text:
/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>
 * Licensed under the MIT license. See the license file LICENSE.
 */

#pragma once

#include <Eigen/Dense>

template<typename T>
class SufficientStatistics
{

};

/* sufficient statistics for gaussian distribution
 * has outer product, sum over data and count
 */
template<typename T>
class ssGauss : public SufficientStatistics<T>
{

};

/* sufficient statistics for categorical distribution
 * mainly just counts
 */
template<typename T>
class ssCat : public SufficientStatistics<T>
{

};

max_stars_repo_name: jstraub/dpMM

max_issues_repo_name: jstraub/dpMM

max_forks_repo_name: jstraub/dpMM


text:
#include "macsecmgr.h"

#include <exec.h>
#include <shellcmd.h>
#include <swss/stringutility.h>
#include <swss/redisutility.h>
#include <boost/algorithm/string/predicate.hpp>

#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <error.h>
#include <string>
#include <vector>
#include <map>
#include <tuple>
#include <algorithm>
#include <sstream>
#include <cctype>

using namespace std;
using namespace swss;

#define WPA_SUPPLICANT_CMD "/sbin/wpa_supplicant"
#define WPA_CLI_CMD        "/sbin/wpa_cli"
#define WPA_CONF           "/etc/wpa_supplicant.conf"
#define SOCK_DIR           "/var/run/"

constexpr std::uint64_t RETRY_TIME = 30;

/* retry interval, in millisecond */
constexpr std::uint64_t RETRY_INTERVAL = 100;

static void lexical_convert(const std::string &policy_str, MACsecMgr::MACsecProfile::Policy & policy)
{
    SWSS_LOG_ENTER();

    if (boost::iequals(policy_str, "integrity_only"))
    {
        policy = MACsecMgr::MACsecProfile::Policy::INTEGRITY_ONLY;
    }
    else if (boost::iequals(policy_str, "security"))
    {
        policy = MACsecMgr::MACsecProfile::Policy::SECURITY;
    }
    else
    {
        throw std::invalid_argument("Invalid policy : " + policy_str);
    }
}

static void lexical_convert(const std::string &cipher_str, MACsecMgr::MACsecProfile::CipherSuite & cipher_suite)
{
    SWSS_LOG_ENTER();

    if (boost::iequals(cipher_str, "GCM-AES-128"))
    {
        cipher_suite = MACsecMgr::MACsecProfile::CipherSuite::GCM_AES_128;
    }
    else if (boost::iequals(cipher_str, "GCM-AES-256"))
    {
        cipher_suite = MACsecMgr::MACsecProfile::CipherSuite::GCM_AES_256;
    }
    else if (boost::iequals(cipher_str, "GCM-AES-XPN-128"))
    {
        cipher_suite = MACsecMgr::MACsecProfile::CipherSuite::GCM_AES_XPN_128;
    }
    else if (boost::iequals(cipher_str, "GCM-AES-XPN-256"))
    {
        cipher_suite = MACsecMgr::MACsecProfile::CipherSuite::GCM_AES_XPN_256;
    }
    else
    {
        throw std::invalid_argument("Invalid cipher_suite : " + cipher_str);
    }
}

template<class T>
static bool get_value(
    const MACsecMgr::TaskArgs & ta,
    const std::string & field,
    T & value)
{
    SWSS_LOG_ENTER();

    auto value_opt = swss::fvsGetValue(ta, field, true);
    if (!value_opt)
    {
        SWSS_LOG_DEBUG("Cannot find field : %s", field.c_str());
        return false;
    }

    try
    {
        lexical_convert(*value_opt, value);
    }
    catch(const boost::bad_lexical_cast &e)
    {
        SWSS_LOG_ERROR("Cannot convert value(%s) in field(%s)", value_opt->c_str(), field.c_str());
        return false;
    }

    return true;
}

static void wpa_cli_commands(std::ostringstream & ostream)
{
    // Intentionally emtpy function to adapt
    // the recursively calling of wpa_cli_commands
}

template<typename T, typename...Args>
static void wpa_cli_commands(
    std::ostringstream & ostream,
    T && t,
    Args && ... args)
{
    ostream << " " << t;
    wpa_cli_commands(ostream, args...);
}

template<typename...Args>
static void wpa_cli_commands(
    std::ostringstream & ostream,
    const std::string & t,
    Args && ... args)
{
    ostream << shellquote(t) << " ";
    wpa_cli_commands(ostream, args...);
}

template<typename...Args>
static void wpa_cli_commands(
    std::ostringstream & ostream,
    const std::string & sock,
    const std::string & port_name,
    const std::string & network_id,
    Args && ... args)
{
    ostream << WPA_CLI_CMD;
    wpa_cli_commands(ostream, "-g", sock);
    if (!port_name.empty())
    {
        wpa_cli_commands(ostream, "IFNAME=" + port_name);
    }
    if (!network_id.empty())
    {
        wpa_cli_commands(ostream, "set_network", network_id);
    }
    wpa_cli_commands(ostream, args...);
}

template<typename...Args>
static std::string wpa_cli_exec(
    const std::string & sock,
    const std::string & port_name,
    const std::string & network_id,
    Args && ... args)
{
    std::ostringstream ostream;
    std::string res;
    wpa_cli_commands(
        ostream,
        sock,
        port_name,
        network_id,
        std::forward<Args>(args)...);
    EXEC_WITH_ERROR_THROW(ostream.str(), res);
    return res;
}

template<typename...Args>
static void wpa_cli_exec_and_check(
    const std::string & sock,
    const std::string & port_name,
    const std::string & network_id,
    Args && ... args)
{
    std::string res = wpa_cli_exec(
        sock,
        port_name,
        network_id,
        std::forward<Args>(args)...);
    if (res.find("OK") != 0)
    {
        std::ostringstream ostream;
        wpa_cli_commands(
            ostream,
            sock,
            port_name,
            network_id,
            std::forward<Args>(args)...);
        throw std::runtime_error(
            "Wpa_cli command : " + ostream.str() + " -> " +res);
    }
}

MACsecMgr::MACsecMgr(
    DBConnector *cfgDb,
    DBConnector *stateDb,
    const vector<std::string> &tables) :
        Orch(cfgDb, tables),
        m_statePortTable(stateDb, STATE_PORT_TABLE_NAME)
{
}

MACsecMgr::~MACsecMgr()
{
    // Disable MACsec for all ports
    while (!m_macsec_ports.empty())
    {
        auto port = m_macsec_ports.begin();
        const TaskArgs temp;
        disableMACsec(port->first, temp);
    }
}

void MACsecMgr::doTask(Consumer &consumer)
{
    SWSS_LOG_ENTER();

    using TaskType = std::tuple<const std::string,const std::string>;
    using TaskFunc = task_process_status (MACsecMgr::*)(const std::string &, const TaskArgs &);
    const static std::map<TaskType, TaskFunc > TaskMap = {
        { { CFG_MACSEC_PROFILE_TABLE_NAME, SET_COMMAND }, &MACsecMgr::loadProfile},
        { { CFG_MACSEC_PROFILE_TABLE_NAME, DEL_COMMAND }, &MACsecMgr::removeProfile},
        { { CFG_PORT_TABLE_NAME, SET_COMMAND }, &MACsecMgr::enableMACsec},
        { { CFG_PORT_TABLE_NAME, DEL_COMMAND }, &MACsecMgr::disableMACsec},
    };

    const std::string & table_name = consumer.getTableName();
    auto itr = consumer.m_toSync.begin();
    while (itr != consumer.m_toSync.end())
    {
        task_process_status task_done = task_failed;
        auto & message = itr->second;
        const std::string & op = kfvOp(message);

        auto task = TaskMap.find(std::make_tuple(table_name, op));
        if (task != TaskMap.end())
        {
            task_done = (this->*task->second)(
                kfvKey(message),
                kfvFieldsValues(message));
        }
        else
        {
            SWSS_LOG_ERROR(
                "Unknown task : %s - %s",
                table_name.c_str(),
                op.c_str());
        }

        if (task_done == task_need_retry)
        {
            SWSS_LOG_DEBUG(
                "Task %s - %s need retry",
                table_name.c_str(),
                op.c_str());
            ++itr;
        }
        else
        {
            if (task_done != task_success)
            {
                SWSS_LOG_WARN("Task %s - %s fail",
                    table_name.c_str(),
                    op.c_str());
            }
            else
            {
                SWSS_LOG_DEBUG(
                    "Task %s - %s success",
                    table_name.c_str(),
                    op.c_str());
            }

            itr = consumer.m_toSync.erase(itr);
        }
    }
}

#define GetValue(args, name) (get_value(args, #name, name))

bool MACsecMgr::MACsecProfile::update(const TaskArgs & ta)
{
    SWSS_LOG_ENTER();

    // The following fields are optional
    if (GetValue(ta, fallback_cak) && !GetValue(ta, fallback_ckn))
    {
        return false;
    }
    if (!GetValue(ta, enable_replay_protect))
    {
        enable_replay_protect = false;
    }
    if (!GetValue(ta, replay_window))
    {
        replay_window = 0;
    }
    if (!GetValue(ta, send_sci))
    {
        send_sci = true;
    }
    if (!GetValue(ta, rekey_period))
    {
        rekey_period = 0;
    }
    if (!GetValue(ta, priority))
    {
        priority = 255;
    }
    if (!GetValue(ta, policy))
    {
        policy = Policy::SECURITY;
    }

    // The following fields are necessary
    return GetValue(ta, cipher_suite)
        && GetValue(ta, primary_cak)
        && GetValue(ta, primary_ckn);
}

task_process_status MACsecMgr::loadProfile(
    const std::string & profile_name,
    const TaskArgs & profile_attr)
{
    SWSS_LOG_ENTER();

    auto profile = m_profiles.emplace(
        std::piecewise_construct,
        std::make_tuple(profile_name),
        std::make_tuple());
    try
    {
        if (profile.first->second.update(profile_attr))
        {
            SWSS_LOG_NOTICE(
                "The MACsec profile '%s' is loaded",
                profile_name.c_str());
        }
        // If the profile has been used
        if (profile.second)
        {
            for (auto & port : m_macsec_ports)
            {
                if (port.second.profile_name == profile_name)
                {
                    // Hot update
                    SWSS_LOG_DEBUG("Hot update");
                }
            }
        }
        return task_success;
    }
    catch(const std::invalid_argument & e)
    {
        SWSS_LOG_WARN("%s", e.what());
        return task_failed;
    }
}

task_process_status MACsecMgr::removeProfile(
    const std::string & profile_name,
    const TaskArgs & profile_attr)
{
    SWSS_LOG_ENTER();

    auto profile = m_profiles.find(profile_name);
    if (profile == m_profiles.end())
    {
        SWSS_LOG_WARN(
            "The MACsec profile '%s' wasn't loaded",
            profile_name.c_str());
        return task_invalid_entry;
    }

    // The MACsec profile cannot be removed if it is occupied
    auto port = std::find_if(
        m_macsec_ports.begin(),
        m_macsec_ports.end(),
        [&](const decltype(m_macsec_ports)::value_type & pair)
        {
            return pair.second.profile_name == profile_name;
        });
    if (port != m_macsec_ports.end())
    {
        // This MACsec profile is occupied by some ports
        // remove it after all ports disable MACsec
        SWSS_LOG_DEBUG(
            "The MACsec profile '%s' is used by the port '%s'",
            profile_name.c_str(),
            port->first.c_str());
        return task_need_retry;
    }
    SWSS_LOG_NOTICE("The MACsec profile '%s' is removed", profile_name.c_str());
    m_profiles.erase(profile);
    return task_success;
}

task_process_status MACsecMgr::enableMACsec(
    const std::string & port_name,
    const TaskArgs & port_attr)
{
    SWSS_LOG_ENTER();

    std::string profile_name;
    if (!get_value(port_attr, "macsec", profile_name)
        || profile_name.empty())
    {
        SWSS_LOG_DEBUG("MACsec field of port '%s' is empty", port_name.c_str());
        return disableMACsec(port_name, port_attr);
    }

    // If the MACsec profile is ready
    auto itr = m_profiles.find(profile_name);
    if (itr == m_profiles.end())
    {
        SWSS_LOG_DEBUG(
            "The MACsec profile '%s' for the port '%s' isn't ready",
            profile_name.c_str(),
            port_name.c_str());
        return task_need_retry;
    }
    auto & profile = itr->second;

    // If the port is ready
    if (!isPortStateOk(port_name))
    {
        SWSS_LOG_DEBUG("The port '%s' isn't ready", port_name.c_str());
        return task_need_retry;
    }

    // Create MKA Session object
    auto port = m_macsec_ports.emplace(
        std::piecewise_construct,
        std::make_tuple(port_name),
        std::make_tuple());
    if (!port.second)
    {
        if (port.first->second.profile_name == profile_name)
        {
            SWSS_LOG_NOTICE(
                "The MACsec profile '%s' on the port '%s' has been loaded",
                profile_name.c_str(),
                port_name.c_str());
            return task_success;
        }
        else
        {
            SWSS_LOG_NOTICE(
                "The MACsec profile '%s' on the port '%s' "
                "will be replaced by the MACsec profile '%s'",
                port.first->second.profile_name.c_str(),
                port_name.c_str(),
                profile_name.c_str());
            auto result = disableMACsec(port_name, port_attr);
            if (result != task_success)
            {
                return result;
            }
        }
    }
    auto & session = port.first->second;
    session.profile_name = profile_name;
    ostringstream ostream;
    ostream << SOCK_DIR << port_name;
    session.sock = ostream.str();
    session.wpa_supplicant_pid = startWPASupplicant(session.sock);
    if (session.wpa_supplicant_pid < 0)
    {
        SWSS_LOG_WARN("Cannot start the wpa_supplicant of the port '%s' : %s",
            port_name.c_str(),
            strerror(errno));
        m_macsec_ports.erase(port.first);
        return task_need_retry;
    }
    else if (session.wpa_supplicant_pid == 0)
    {
        SWSS_LOG_WARN("Cannot start the wpa_supplicant of the port '%s' : %s",
        port_name.c_str(),
        strerror(errno));
        m_macsec_ports.erase(port.first);
        return task_failed;
    }

    // Enable MACsec
    if (!configureMACsec(port_name, session, profile))
    {
        SWSS_LOG_WARN("The MACsec profile '%s' on the port '%s' loading fail",
            profile_name.c_str(),
            port_name.c_str());
        return disableMACsec(port_name, port_attr);
    }
    SWSS_LOG_NOTICE("The MACsec profile '%s' on the port '%s' loading success",
        profile_name.c_str(),
        port_name.c_str());
    return task_success;
}

task_process_status MACsecMgr::disableMACsec(
    const std::string & port_name,
    const TaskArgs & port_attr)
{
    SWSS_LOG_ENTER();

    auto itr = m_macsec_ports.find(port_name);
    if (itr == m_macsec_ports.end())
    {
        SWSS_LOG_NOTICE("The MACsec was not enabled on the port '%s'",
            port_name.c_str());
        return task_success;
    }
    auto & session = itr->second;
    task_process_status ret = task_success;
    if (!unconfigureMACsec(port_name, session))
    {
        SWSS_LOG_WARN(
            "Cannot stop MKA session on the port '%s'",
            port_name.c_str());
        ret = task_failed;
    }
    if (!stopWPASupplicant(session.wpa_supplicant_pid))
    {
        SWSS_LOG_WARN(
            "Cannot stop WPA_SUPPLICANT process of the port '%s'",
            port_name.c_str());
        ret = task_failed;
    }
    if (ret == task_success)
    {
        SWSS_LOG_NOTICE("The MACsec profile '%s' on the port '%s' is removed",
            itr->second.profile_name.c_str(),
            port_name.c_str());
    }
    m_macsec_ports.erase(itr);
    return ret;
}

bool MACsecMgr::isPortStateOk(const std::string & port_name)
{
    SWSS_LOG_ENTER();

    std::vector<FieldValueTuple> temp;
    std::string state;
    std::string oper_status;

    if (m_statePortTable.get(port_name, temp)
        && get_value(temp, "state", state)
        && state == "ok"
        && get_value(temp, "netdev_oper_status", oper_status)
        && oper_status == "up")
    {
        SWSS_LOG_DEBUG("Port '%s' is ready", port_name.c_str());
        return true;
    }
    SWSS_LOG_DEBUG("Port '%s' is not ready", port_name.c_str());
    return false;
}

pid_t MACsecMgr::startWPASupplicant(const std::string & sock) const
{
    SWSS_LOG_ENTER();

    pid_t wpa_supplicant_pid = fork();
    if (wpa_supplicant_pid == 0)
    {
        exit(execl(
            WPA_SUPPLICANT_CMD,
            WPA_SUPPLICANT_CMD,
            "-s",
            "-D", "macsec_sonic",
            "-g", sock.c_str(),
            NULL));
    }
    else if (wpa_supplicant_pid > 0)
    {
        // Wait wpa_supplicant ready
        bool wpa_supplicant_loading = false;
        auto retry_time = RETRY_TIME;
        while(!wpa_supplicant_loading && retry_time > 0)
        {
            try
            {
                wpa_cli_exec(sock, "", "", "status");
                wpa_supplicant_loading = true;
            }
            catch(const std::runtime_error&)
            {
                retry_time--;
                std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_INTERVAL));
            }
        }
        if (wpa_supplicant_loading)
        {
            SWSS_LOG_DEBUG("Start wpa_supplicant success");
        }
        else
        {
            stopWPASupplicant(wpa_supplicant_pid);
            wpa_supplicant_pid = 0;
            SWSS_LOG_WARN("Cannot connect to wpa_supplicant.");
        }
    }
    return wpa_supplicant_pid;
}

bool MACsecMgr::stopWPASupplicant(pid_t pid) const
{
    SWSS_LOG_ENTER();

    if(kill(pid, SIGINT) != 0)
    {
        SWSS_LOG_WARN("Cannot stop wpa_supplicant(%d)", pid);
        return false;
    }
    int status = 0;
    waitpid(pid, &status, 0);
    SWSS_LOG_DEBUG(
        "Stop wpa_supplicant(%d) with return value (%d)",
        pid,
        status);
    return status == 0;
}

bool MACsecMgr::configureMACsec(
    const std::string & port_name,
    const MKASession & session,
    const MACsecProfile & profile) const
{
    SWSS_LOG_ENTER();

    try
    {
        wpa_cli_exec_and_check(
            session.sock,
            "",
            "",
            "interface_add",
            port_name,
            WPA_CONF,
            "macsec_sonic");

        const std::string res = wpa_cli_exec(
            session.sock,
            port_name,
            "",
            "add_network");
        const std::string network_id(
            res.begin(),
            std::find_if_not(
                res.begin(),
                res.end(),
                [](unsigned char c)
                {
                    return std::isdigit(c);
                }
            )
        );
        if (network_id.empty())
        {
            throw std::runtime_error("Cannot add network : " + res);
        }

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "key_mgmt",
            "NONE");

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "eapol_flags",
            0);

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "macsec_policy",
            1);

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "macsec_integ_only",
            (profile.policy == MACsecProfile::Policy::INTEGRITY_ONLY ? 1 : 0));

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "mka_cak",
            profile.primary_cak);

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "mka_ckn",
            profile.primary_ckn);

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "mka_priority",
            profile.priority);

        if (profile.rekey_period)
        {
            wpa_cli_exec_and_check(
                session.sock,
                port_name,
                network_id,
                "mka_rekey_period",
                profile.rekey_period);
        }

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "macsec_ciphersuite",
            profile.cipher_suite);

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "macsec_include_sci",
            (profile.send_sci ? 1 : 0));

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            network_id,
            "macsec_replay_protect",
            (profile.enable_replay_protect ? 1 : 0));

        if (profile.enable_replay_protect)
        {
            wpa_cli_exec_and_check(
                session.sock,
                port_name,
                network_id,
                "macsec_replay_window",
                profile.replay_window);
        }

        wpa_cli_exec_and_check(
            session.sock,
            port_name,
            "",
            "enable_network",
            network_id);
    }
    catch(const std::runtime_error & e)
    {
        SWSS_LOG_WARN("Enable MACsec fail : %s", e.what());
        return false;
    }
    return true;
}

bool MACsecMgr::unconfigureMACsec(
    const std::string & port_name,
    const MKASession & session) const
{
    SWSS_LOG_ENTER();
    try
    {
        wpa_cli_exec_and_check(
            session.sock,
            "",
            "",
            "interface_remove",
            port_name);
    }
    catch(const std::runtime_error & e)
    {
        SWSS_LOG_WARN("Disable MACsec fail : %s", e.what());
        return false;
    }
    return true;
}


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_SCALAR_OUTER_SCAN_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_SCALAR_OUTER_SCAN_HPP_INCLUDED

#include <nt2/core/functions/outer_scan.hpp>
#include <nt2/core/functions/details/scan_step.hpp>
#include <boost/fusion/include/pop_front.hpp>
#include <nt2/include/functions/scalar/numel.hpp>

namespace nt2 { namespace ext
{
  //============================================================================
  // General outer_scan
  //============================================================================
  BOOST_DISPATCH_IMPLEMENT  ( outer_scan_, tag::cpu_
                            , (Out)(In)(Neutral)(Bop)(Uop)
                            , ((ast_< Out, nt2::container::domain>))
                              ((ast_< In, nt2::container::domain>))
                              (unspecified_<Neutral>)
                              (unspecified_<Bop>)
                              (unspecified_<Uop>)
                            )
  {
    typedef void                                                              result_type;
    typedef typename Out::value_type                                          value_type;
    typedef typename In::extent_type                                          extent_type;

    BOOST_FORCEINLINE result_type
    operator()(Out& out, In& in, Neutral const& neutral, Bop const& bop, Uop const&) const
    {
      extent_type ext = in.extent();
      std::size_t obound =  boost::fusion::at_c<2>(ext);
      std::size_t ibound  = boost::fusion::at_c<0>(ext);
      std::size_t mbound =  boost::fusion::at_c<1>(ext);
      std::size_t iboundxmbound = ibound * mbound;

      for(std::size_t o = 0, o_ = 0;
          o < obound;
          ++o, o_+=iboundxmbound)
      {
        for(std::size_t i = 0, i_ = o_; i < ibound; ++i, ++i_)
        {
          value_type summary = neutral(nt2::meta::as_<value_type>());
          summary = details::scan_step(summary, out, in, bop, i_, mbound, ibound, false);
        }
      }
    }
  };

} }

#endif


text:
#include <iostream>
#include <fstream>
#include <chrono>

#include <opencv2/core.hpp>

#include <dlib/opencv.h>
#include <dlib/data_io.h>
#include <dlib/dnn.h>
#include <dlib/array2d.h>
#include <dlib/image_transforms.h>

#include "ReadMNISTDatas.hpp"
#include "TrainFilePath.hpp"
#include "../TestDNN/DLIBInput.hpp"
#include "NetworkStringTraits.hpp"

namespace enabler { extern void* enabler; }

template <class T>
using UnqualifiedType = std::remove_pointer_t<std::remove_cv_t<std::remove_reference_t<T>>>;

template <class Network>
void saveWeights(std::ostream& output, Network&& net);

template <class Network, class T>
void saveWeightsImpl(std::ostream& output, Network&& net, dlib::input<T> const& input);

template <class Network, class Subnet>
void saveWeightsImpl(std::ostream& output, Network&& net, Subnet&& subnet);

int main()
{
  using net_type = dlib::loss_multiclass_log<
    dlib::fc<10,
    dlib::relu<dlib::fc<84,
    dlib::relu<dlib::fc<120,
    dlib::max_pool<2, 2, 2, 2, dlib::relu<dlib::con<16, 5, 5, 1, 1,
    dlib::max_pool<2, 2, 2, 2, dlib::relu<dlib::con<6, 5, 5, 1, 1,
    dlib::input<cv::Mat>
    >>>>>>>>>>>>;

  net_type net;
  dlib::deserialize("mnist_network.dat") >> net;

  std::fstream output("weights.csv", std::ios::out | std::ios::trunc);
  saveWeights(output, net);

  return 0;
}

template <class Network>
void saveWeights(std::ostream& output, Network&& net)
{
  auto&& subnet = net.subnet();
  saveWeightsImpl(output, subnet, subnet.subnet());
}

using InputLayer = dlib::input<cv::Mat>;
/*
template <
  class Network,
  class Subnet,
  std::enable_if_t<
    std::is_same<UnqualifiedType<Subnet>, dlib::input<cv::Mat>>::value
  >*& = enabler::enabler
>
*/
template <class Network>
void saveWeightsImpl(std::ostream& output, Network&& net, InputLayer input)
{
  return;
}

template <class Network, class Subnet>
void saveWeightsImpl(std::ostream& output, Network&& net, Subnet&& subnet)
{
  using NetworkType = std::remove_reference_t<Network>;
  using SubnetType = std::remove_reference_t<Subnet>;
  saveWeightsImpl(
    output,
    std::forward<NetworkType::subnet_type>(net.subnet()),
    std::forward<SubnetType::subnet_type>(subnet.subnet())
  );

  output << NetworkStringTraits<NetworkType>::STRING << "\n";
  dlib::tensor const& tensor = net.layer_details().get_layer_params();
  output << "Layer:" << NetworkType::num_layers << ","
         << "Row:" << tensor.nr() << ","
         << "Column:" << tensor.nc() << ","
         << "Channel:" << tensor.k() << "\n";

  for (long k = 0; k < tensor.k(); ++k)
  {
    auto ptr = tensor.host();
    output << "Node" << k << "\n";
    for (long r = 0; r < tensor.nr(); ++r)
    {
      for (long c = 0; c < tensor.nc(); ++c)
      {
        output << ptr[c * tensor.k() + r * tensor.nc() + k] << ",";
      }
      output.seekp(std::ios::cur, -1) << "\n";
    }
    output << "\n";
  }

  output << "\n";
}


text:
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Lua plugin for Zen Scripting
//
// Copyright (C) 2001 - 2016 Raymond A. Richards
//
//  This software is provided 'as-is', without any express or implied
//  warranty.  In no event will the authors be held liable for any damages
//  arising from the use of this software.
//
//  Permission is granted to anyone to use this software for any purpose,
//  including commercial applications, and to alter it and redistribute it
//  freely, subject to the following restrictions:
//
//  1. The origin of this software must not be misrepresented; you must not
//     claim that you wrote the original software. If you use this software
//     in a product, an acknowledgment in the product documentation would be
//     appreciated but is not required.
//  2. Altered source versions must be plainly marked as such, and must not be
//     misrepresented as being the original software.
//  3. This notice may not be removed or altered from any source distribution.
//
//  Tony Richards trichards@indiezen.com
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#ifndef ZEN_ZLUA_CONFIG_HPP_INCLUDED
#define ZEN_ZLUA_CONFIG_HPP_INCLUDED

#include <Zen/Core/Memory/managed_ptr.hpp>

#include <boost/any.hpp>

#include <string>
#include <map>

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace ZLua {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
;

/// Light wrapper of a map of strings with string as the key type.
/// This is used by LuaEngine to convert a Lua table into a
/// std::map<std::string, std::string>.  The Lua table must have
/// keys of string types and the values can be of any type but is
/// converted to a string.
/// @see new_Config
class Config
{
public:
	typedef Zen::Memory::managed_ptr<Config>   pScriptObject_type;
	typedef std::map<std::string, std::string>config_type;

             Config();
             Config(const Config& _right);
	virtual ~Config();

	std::string get(const std::string& _key);
	void set(const std::string& _key, boost::any _value);
	Config& operator=(const Config& _right);

	config_type	m_config;

};	// class Config

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
}	// namespace ZLua
}	// namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

#endif	// ZEN_ZLUA_CONFIG_HPP_INCLUDED

max_stars_repo_name: indie-zen-plugins/ZLua

max_issues_repo_name: indie-zen-plugins/ZLua

max_forks_repo_name: indie-zen-plugins/ZLua


text:
#include "sample.h"
#include <thrift/transport/TSocket.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>

#include <iostream>

#include <boost/lexical_cast.hpp>

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

int main(int argc, char **argv) {
	stdcxx::shared_ptr<TSocket> socket(new TSocket("localhost", 9090));
	stdcxx::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
	stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
	stdcxx::shared_ptr<sampleClient> client(new sampleClient(protocol));

	transport->open();

	try {
		std::string hello;
		client->hello(hello, "World");
		std::cout << hello << std::endl;

		std::string ipaddr;
		client->ipaddr(ipaddr);
		std::cout << ipaddr << std::endl;

		int random = client->random(5);
		std::cout << boost::lexical_cast<std::string>(random) << std::endl;

		std::string uuid;
		client->uuid(uuid);
		std::cout << uuid << std::endl;

		Calc calc;
		client->calculator(calc, 7, 13);
		std::cout << calc << std::endl;
	}
	catch (sampleException &e) {
		std::cerr << e << std::endl;
	}

	transport->close();

	getchar();
	return 0;
}


text:
#include <Eigen/Dense>
#include <iostream>

using namespace Eigen;
using namespace std;

int main() {
  ArrayXXf a(3, 3);
  ArrayXXf b(3, 3);
  a << 1, 2, 3,
      4, 5, 6,
      7, 8, 9;
  b << 1, 2, 3,
      1, 2, 3,
      1, 2, 3;

  // Adding two arrays
  cout << "a + b = " << endl << a + b << endl << endl;

  // Subtracting a scalar from an array
  cout << "a - 2 = " << endl << a - 2 << endl;
}


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/usd/usd/property.h"
#include "pxr/usd/usd/editTarget.h"
#include "pxr/usd/usd/wrapUtils.h"

#include "pxr/base/tf/pyContainerConversions.h"
#include "pxr/base/tf/pyResultConversions.h"

#include <boost/python/class.hpp>

using std::string;

using namespace boost::python;

PXR_NAMESPACE_USING_DIRECTIVE

void wrapUsdProperty()
{
    class_<UsdProperty, bases<UsdObject> >("Property")
        .def(Usd_ObjectSubclass())
        .def("GetBaseName", &UsdProperty::GetBaseName)
        .def("GetNamespace", &UsdProperty::GetNamespace)
        .def("SplitName", &UsdProperty::SplitName,
             return_value_policy<TfPySequenceToList>())

        .def("GetDisplayGroup", &UsdProperty::GetDisplayGroup)
        .def("SetDisplayGroup", &UsdProperty::SetDisplayGroup,
             arg("displayGroup"))
        .def("ClearDisplayGroup", &UsdProperty::ClearDisplayGroup)
        .def("HasAuthoredDisplayGroup", &UsdProperty::HasAuthoredDisplayGroup)

        .def("GetNestedDisplayGroups", &UsdProperty::GetNestedDisplayGroups,
             return_value_policy<TfPySequenceToList>())

        .def("SetNestedDisplayGroups", &UsdProperty::SetNestedDisplayGroups,
             arg("nestedGroups"))

        .def("GetDisplayName", &UsdProperty::GetDisplayName)
        .def("SetDisplayName", &UsdProperty::SetDisplayName, arg("name"))
        .def("ClearDisplayName", &UsdProperty::ClearDisplayName)
        .def("HasAuthoredDisplayName", &UsdProperty::HasAuthoredDisplayName)

        .def("GetPropertyStack", &UsdProperty::GetPropertyStack,
             arg("time"))

        .def("IsCustom", &UsdProperty::IsCustom)
        .def("SetCustom", &UsdProperty::SetCustom, arg("isCustom"))

        .def("IsDefined", &UsdProperty::IsDefined)
        .def("IsAuthored", &UsdProperty::IsAuthored)
        .def("IsAuthoredAt", &UsdProperty::IsAuthoredAt, arg("editTarget"))
        ;

    TfPyRegisterStlSequencesFromPython<UsdProperty>();
}

max_stars_repo_name: dalgos-adsk/USD

max_issues_repo_name: piscees/USD

max_forks_repo_name: piscees/USD


text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*
	This example shows "Minimalistic CNN-based model" for gender prediction from
	face images. The original idea and definition of the model is given in the
	document available at this address:
	http://www.eurecom.fr/fr/publication/4768/download/mm-publi-4768.pdf

	This model is a gender classifier trained using a private dataset of about
	200k different face images, , with a balanced distribution between female
	and male genders. It was generated according to the network definition and
	settings given in the paper for gender prediction from face images. Even if
	the dataset used for the training is different from that used by G. Antipov
	et al, the classification results on the LFW evaluation are similar overall.

	To take up the authors' proposal to join the results of three networks, a
	simplification was made by finally presenting RGB images, thus simulating
	three "grayscale" networks via the three image planes. Better results could
	be probably obtained with a more complex and deeper network, but the performance
	of the classification is nevertheless surprising compared to the simplicity
	of the network used and thus its very small size.

	The model was trained using about 200k images, with a balanced distribution
	between female and male genders. Faces extracted from a non-public database
	were augmented, after alignment according to the 5-point model provided
	by Dlib. The CNN pretrained model he model was saved just after training so
	that if necessary it could be fine-tuned using another database.

	Finally, this gender model is provided for free by Cydral and is licensed
	under the Creative Commons Zero v1.0 Universal.
*/

#include "dlib/data_io.h"
#include "dlib/string.h"
#include <dlib/cmd_line_parser.h>
#include <dlib/image_transforms.h>
#include <dlib/dir_nav.h>
#include <dlib/dnn.h>
#include <dlib/data_io.h>
#include <dlib/image_processing/frontal_face_detector.h>

#include <iostream>
#include <iterator>

using namespace std;
using namespace dlib;

const char* VERSION = "1.1";

// ----------------------------------------------------------------------------------------

// This block of statements defines the network as proposed for the CNN Model I.
// We however removed the "dropout" regularization on the activations of convolutional layers.
template <int N, template <typename> class BN, int stride, typename SUBNET>
using block = BN<con<N, 3, 3, stride, stride, relu<BN<con<N, 3, 3, stride, stride, SUBNET>>>>>;

template <int N, typename SUBNET> using res_ = relu<block<N, bn_con, 1, SUBNET>>;
template <int N, typename SUBNET> using ares_ = relu<block<N, affine, 1, SUBNET>>;

template <typename SUBNET> using alevel1 = avg_pool<2, 2, 2, 2, ares_<64, SUBNET>>;
template <typename SUBNET> using alevel2 = avg_pool<2, 2, 2, 2, ares_<32, SUBNET>>;

using agender_type = loss_multiclass_log<fc<2, multiply<relu<fc<16, multiply<alevel1<alevel2< input_rgb_image_sized<32>>>>>>>>>;

// ----------------------------------------------------------------------------------------

#define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
#define PBWIDTH 40
void display_progressbar(float percentage)
{
	uint32_t val = (int)(percentage * 100);
	uint32_t lpad = (int)(percentage * PBWIDTH);
	uint32_t rpad = PBWIDTH - lpad;
	printf("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, "");
	fflush(stdout);
}

// ----------------------------------------------------------------------------------------

// An helper function to load dataset for testing.
enum label_ : uint16_t
{
	female_label,
	male_label,
};
struct image_info
{
	enum label_ label_image;
	string filename;
};

std::vector<image_info> get_image_listing(
	const std::string& images_folder,
	const enum label_& label
)
{
	std::vector<image_info> results;
	image_info temp;
	temp.label_image = label;

	auto dir = directory(images_folder);
	for (auto image_file : dir.get_files())
	{
		temp.filename = image_file;
		results.push_back(temp);
	}

	return results;
}
std::vector<image_info> get_train_listing_females(const std::string& ifolder) { return get_image_listing(ifolder, female_label); }
std::vector<image_info> get_train_listing_males(const std::string& ifolder) { return get_image_listing(ifolder, male_label); }

int main(int argc, char** argv) try {
	// Use a parser to set parameters.
	command_line_parser parser;

	parser.add_option("h", "");
	parser.add_option("help", "Displays this information");
	parser.add_option("version", "Display version");
	parser.add_option("test-folders", "Test the gender classifier ./females ./males", 2);
	parser.add_option("test-image", "Test the gender classifier ./image.jpg", 1);
	parser.parse(argc, argv);

	parser.check_incompatible_options("help", "version");
	parser.check_incompatible_options("help", "test-folders");
	parser.check_incompatible_options("help", "test-image");
	parser.check_incompatible_options("version", "test-folders");
	parser.check_incompatible_options("version", "test-image");
	parser.check_incompatible_options("test-folders", "test-image");

	if (parser.option("help") || parser.option("h"))
	{
		cout << "Usage: ./dnn_gender_classifier_ex [options]\n";
		parser.print_options(cout);
		cout << endl << "Note:" << endl << "You will need two different models to test this classifier.";
		cout << endl << "First, download and then decompress the gender model from: " << endl;
		cout << "http://dlib.net/files/dnn_gender_classifier_v1.dat.bz2" << endl;
		cout << "Then, you also need the face landmarking model file from:" << endl;
		cout << "http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2" << endl;
		cout << endl << endl;
		return EXIT_SUCCESS;
	}
	if (parser.option("version"))
	{
		cout << "dnn_gender_classifier_ex v" << VERSION
			 << "\nCompiled: " << __TIME__ << " " << __DATE__ << endl << endl;
		return EXIT_SUCCESS;
	}

	if (parser.option("test-folders"))
	{
		// Initialize networks.
		frontal_face_detector detector = get_frontal_face_detector();
		shape_predictor sp;
		deserialize("shape_predictor_5_face_landmarks.dat") >> sp;

		static const char* model_net_filename = "dnn_gender_classifier_v1.dat";
		agender_type net;
		deserialize(model_net_filename) >> net;

		// Load test images.
		auto female_images = get_train_listing_females(parser.option("test-folders").argument(0));
		cout << "female examples: " << female_images.size() << endl;

		auto male_images = get_train_listing_males(parser.option("test-folders").argument(1));
		cout << "male examples: " << male_images.size() << endl << endl;

		// Test all images.
		matrix<rgb_pixel> in;
		int32_t num_right = 0, num_wrong = 0, nb_elts = 0;
		cout << "analysing female faces in progress: " << endl;
		for (auto& img : female_images)
		{
			display_progressbar((nb_elts++ / (float)female_images.size()));
			load_image(in, img.filename);
			for (auto face : detector(in))
			{
				auto shape = sp(in, face);
				if (shape.num_parts())
				{
					matrix<rgb_pixel> face_chip;
					extract_image_chip(in, get_face_chip_details(shape, 32), face_chip);
					if (net(face_chip) == female_label)
						++num_right;
					else
						++num_wrong;
				}
			}
		}
		display_progressbar(1.0f);
		// ---
		cout << endl << "analysing male faces in progress: " << endl;
		nb_elts = 0;
		for (auto& img : male_images)
		{
			display_progressbar((nb_elts++ / (float)male_images.size()));
			load_image(in, img.filename);
			for (auto face : detector(in))
			{
				auto shape = sp(in, face);
				if (shape.num_parts())
				{
					matrix<rgb_pixel> face_chip;
					extract_image_chip(in, get_face_chip_details(shape, 32), face_chip);
					if (net(face_chip) == male_label)
						++num_right;
					else
						++num_wrong;
				}
			}
		}
		display_progressbar(1.0f);
		cout << endl;

		// And at final, display accuracy.
		cout << "testing num_right: " << num_right << endl;
		cout << "testing num_wrong: " << num_wrong << endl;
		cout << "testing accuracy:  " << num_right / (double)(num_right + num_wrong) << endl;
		return EXIT_SUCCESS;
	}

	if (parser.option("test-image"))
	{
		// Initialize networks.
		frontal_face_detector detector = get_frontal_face_detector();
		shape_predictor sp;
		deserialize("shape_predictor_5_face_landmarks.dat") >> sp;

		static const char* model_net_filename = "dnn_gender_classifier_v1.dat";
		agender_type net;
		deserialize(model_net_filename) >> net;

		// Load the source image.
		matrix<rgb_pixel> in;
		load_image(in, parser.option("test-image").argument(0));

		// As proposed in the paper, use Softmax for the last layer.
		softmax<agender_type::subnet_type> snet;
		snet.subnet() = net.subnet();

		// Evaluate the gender
		int32_t cur_face = 0;
		float confidence = 0.0f;
		enum label_ gender;
		for (auto face : detector(in))
		{
			auto shape = sp(in, face);
			if (shape.num_parts())
			{
				matrix<rgb_pixel> face_chip;
				extract_image_chip(in, get_face_chip_details(shape, 32), face_chip);
				matrix<float, 1, 2> p = mat(snet(face_chip));
				if (p(0) < p(1))
				{
					gender = male_label;
					confidence = p(1);
				}
				else
				{
					gender = female_label;
					confidence = p(0);
				}
				cout << "face#" << cur_face++ << " - detected gender: " << ((gender == female_label) ? "female" : "male");
				cout << std::fixed << std::setprecision(1) << " [" << (confidence * 100.0f) << "%]" << endl;
			}
		}
		return EXIT_SUCCESS;
	}
}
catch(std::exception& e)
{
    cout << e.what() << endl;
}

max_stars_repo_name: Pandinosaurus/dlib-models


text:
// Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/assert.hpp>
#include <boost/hana/drop_front.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/experimental/types.hpp>
#include <boost/hana/integral_constant.hpp>
namespace hana = boost::hana;

template <int> struct x;

int main() {
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<>{}, hana::size_c<0>),
        hana::experimental::types<>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<>{}, hana::size_c<1>),
        hana::experimental::types<>{}
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>>{}, hana::size_c<0>),
        hana::experimental::types<x<0>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>>{}, hana::size_c<1>),
        hana::experimental::types<>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>>{}, hana::size_c<2>),
        hana::experimental::types<>{}
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>>{}, hana::size_c<0>),
        hana::experimental::types<x<0>, x<1>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>>{}, hana::size_c<1>),
        hana::experimental::types<x<1>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>>{}, hana::size_c<2>),
        hana::experimental::types<>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>>{}, hana::size_c<3>),
        hana::experimental::types<>{}
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>>{}, hana::size_c<0>),
        hana::experimental::types<x<0>, x<1>, x<2>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>>{}, hana::size_c<1>),
        hana::experimental::types<x<1>, x<2>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>>{}, hana::size_c<2>),
        hana::experimental::types<x<2>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>>{}, hana::size_c<3>),
        hana::experimental::types<>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>>{}, hana::size_c<4>),
        hana::experimental::types<>{}
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>, x<3>>{}, hana::size_c<0>),
        hana::experimental::types<x<0>, x<1>, x<2>, x<3>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>, x<3>>{}, hana::size_c<1>),
        hana::experimental::types<x<1>, x<2>, x<3>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>, x<3>>{}, hana::size_c<2>),
        hana::experimental::types<x<2>, x<3>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>, x<3>>{}, hana::size_c<3>),
        hana::experimental::types<x<3>>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>, x<3>>{}, hana::size_c<4>),
        hana::experimental::types<>{}
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::drop_front(hana::experimental::types<x<0>, x<1>, x<2>, x<3>>{}, hana::size_c<5>),
        hana::experimental::types<>{}
    ));
}

max_issues_repo_name: lipper/arangodb

max_forks_repo_name: lipper/arangodb


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

/*! \file scenario/scenariogenerator.hpp
    \brief Scenario generator base classes
    \ingroup scenario
*/

#pragma once

#include <vector>

#include <boost/shared_ptr.hpp>
#include <orea/scenario/scenario.hpp>
#include <ql/time/date.hpp>
#include <ql/time/daycounters/actualactual.hpp>
#include <ql/timegrid.hpp>

namespace ore {
namespace analytics {
using QuantLib::TimeGrid;
using std::vector;

//! Scenario generator base class
/*! \ingroup scenario
 */
class ScenarioGenerator {
public:
    //! Default destructor
    virtual ~ScenarioGenerator() {}

    //! Return the next scenario for the given date.
    virtual boost::shared_ptr<Scenario> next(const Date& d) = 0;

    //! Reset the generator so calls to next() return the first scenario.
    /*! This allows re-generation of scenarios if required. */
    virtual void reset() = 0;
};

//! Scenario generator that generates an entire path
/*! \ingroup scenario
 */
class ScenarioPathGenerator : public ScenarioGenerator {
public:
    // TODO: Why dates AND timegrid, why not DateGrid???
    //! Constructor
    ScenarioPathGenerator( //! Today's date
        Date today,
        //! Future evaluation dates
        const vector<Date>& dates,
        //! Associated time grid
        TimeGrid timeGrid)                                    // DayCounter dayCounter = ActualActual())
        : today_(today), dates_(dates), timeGrid_(timeGrid) { // dayCounter_(dayCounter) {
        QL_REQUIRE(dates.size() > 0, "empty date vector passed");
        QL_REQUIRE(dates.front() > today, "date grid must start in the future");
    }

    virtual boost::shared_ptr<Scenario> next(const Date& d) {
        if (d == dates_.front()) { // new path
            path_ = nextPath();
            pathStep_ = 0;
        }
        QL_REQUIRE(pathStep_ < dates_.size() && d == dates_[pathStep_], "step mismatch");
        return path_[pathStep_++]; // post increment
    }

protected:
    virtual std::vector<boost::shared_ptr<Scenario>> nextPath() = 0;

    Date today_;
    vector<Date> dates_;
    Size pathStep_;
    // DayCounter dayCounter_;
    TimeGrid timeGrid_;
    std::vector<boost::shared_ptr<Scenario>> path_;
};
} // namespace analytics
} // namespace ore

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text: #include <boost/mpi/graph_communicator.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <string>
#include <iostream>
#include <boost/asio/ip/address.hpp>
#include <boost/format.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/format.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/format.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <redisclient/redisasyncclient.h>

using namespace redisclient;
using namespace std;
using namespace std::chrono;
namespace po = boost::program_options;
class Config
{
public:
  static std::string pubTopic;
  static std::string subTopic;
    static std::string redisIP;
    static uint64_t redisPort;
};

std::string Config::pubTopic;
std::string Config::subTopic;
std::string Config::redisIP;
uint64_t Config::redisPort;

class Client
{
public:
    Client(boost::asio::io_service &ioService,
           const boost::asio::ip::address &address,
           unsigned short port)
        : ioService(ioService), publishTimer(ioService),
          connectSubscriberTimer(ioService), connectPublisherTimer(ioService),
          address(address), port(port),
          publisher(ioService), subscriber(ioService)
    {
        publisher.installErrorHandler(std::bind(&Client::connectPublisher, this));
        subscriber.installErrorHandler(std::bind(&Client::connectSubscriber, this));
    }

    void publish(const std::string &str)
    {
        publisher.publish(Config::pubTopic, str);
    }

    void start()
    {
        connectPublisher();
        connectSubscriber();
        cout<<"Echoer Initialized"<<endl;
    }

protected:
    void errorPubProxy(const std::string &)
    {
        publishTimer.cancel();
        connectPublisher();
    }

    void errorSubProxy(const std::string &)
    {
        connectSubscriber();
    }

    void connectPublisher()
    {
        //std::cerr << "connectPublisher\n";

        if( publisher.state() == RedisAsyncClient::State::Connected )
        {
            std::cerr << "disconnectPublisher\n";

            publisher.disconnect();
            publishTimer.cancel();
        }

        boost::asio::ip::tcp::endpoint endpoint(address, port);
        publisher.connect(endpoint,
                          std::bind(&Client::onPublisherConnected, this, std::placeholders::_1));
    }

    void connectSubscriber()
    {
        //std::cerr << "connectSubscriber\n";

        if( subscriber.state() == RedisAsyncClient::State::Connected ||
                subscriber.state() == RedisAsyncClient::State::Subscribed )
        {
            std::cerr << "disconnectSubscriber\n";
            subscriber.disconnect();
        }

        boost::asio::ip::tcp::endpoint endpoint(address, port);
        subscriber.connect(endpoint,
                           std::bind(&Client::onSubscriberConnected, this, std::placeholders::_1));
    }

    void callLater(boost::asio::deadline_timer &timer,
                   void(Client::*callback)())
    {
        std::cerr << "callLater\n";
        timer.expires_from_now(boost::posix_time::seconds(1000));
        timer.async_wait([callback, this](const boost::system::error_code &ec) {
            if( !ec )
            {
                (this->*callback)();
            }
        });
    }

    void onPublishTimeout()
    {
        static size_t counter = 0;
        std::string msg = str(boost::format("message %1%")  % counter++);

        if( publisher.state() == RedisAsyncClient::State::Connected )
        {
            std::cerr << "pub " << msg << "\n";
            publish(msg);
        }

        callLater(publishTimer, &Client::onPublishTimeout);
    }

    void onPublisherConnected(boost::system::error_code ec)
    {
         if(ec){} //TBU
    }

    void onSubscriberConnected(boost::system::error_code ec)
    {
        if( ec )
        {
            std::cerr << "onSubscriberConnected: can't connect to redis: " << ec.message() << "\n";
            callLater(connectSubscriberTimer, &Client::connectSubscriber);
        }
        else
        {
            //std::cerr << "onSubscriberConnected ok\n";
            subscriber.subscribe(Config::subTopic,
                                 std::bind(&Client::onMessage, this, std::placeholders::_1));
        }
    }

    void onMessage(const std::vector<char> &buf)
    {
        std::string s(buf.begin(), buf.end());
        if (s.find(std::string("Dummy")) != string::npos) {
            //cout<<"Dummy #" << counter <<endl;
            return;//Avoid pinging back dummy publishers
        }
        //cout << "pong #" << this->counter <<endl;
        publish(s);
        counter ++;
    }

private:
    boost::asio::io_service &ioService;
    boost::asio::deadline_timer publishTimer;
    boost::asio::deadline_timer connectSubscriberTimer;
    boost::asio::deadline_timer connectPublisherTimer;
    const boost::asio::ip::address address;
    const unsigned short port;

    RedisAsyncClient publisher;
    RedisAsyncClient subscriber;
    int counter = 0;
};

int main(int argc, char ** argv)
{
    po::options_description description("Options");
  description.add_options()
  ("help", "produce help message")
  ("redisIP", po::value(&Config::redisIP)->default_value("127.0.0.1"), "Redis server IP")
  ("redisPort", po::value(&Config::redisPort)->default_value(6379), "Redis server port")
  ("PubTopic", po::value(&Config::pubTopic)->default_value("pong"), "Publish to Topic (Pong)")
  ("SubTopic", po::value(&Config::subTopic)->default_value("ping"), "Subscribe to Topic (ping) ");

  po::variables_map vm;

  try
  {
    po::store(po::parse_command_line(argc, argv, description), vm);
    po::notify(vm);
  }
  catch (const po::error &e)
  {
    std::cerr << e.what() << "\n";
    return EXIT_FAILURE;
  }

  if (vm.count("help"))
  {
    std::cout << description << "\n";
    return EXIT_SUCCESS;
  }

    boost::asio::ip::address address = boost::asio::ip::address::from_string(Config::redisIP);
    const unsigned short port = Config::redisPort;

    boost::asio::io_service ioService;

    Client client(ioService, address, port);

    client.start();
    ioService.run();

    std::cerr << "done\n";

    return 0;
}

max_stars_repo_name: schlesg/RedisBenchmark

max_issues_repo_name: schlesg/RedisBenchmark

max_forks_repo_name: schlesg/RedisBenchmark